View.java revision e6875f1575a71402cd86f75e4d031c95ccd43cc4
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.annotation.IntDef; 20import android.annotation.NonNull; 21import android.annotation.Nullable; 22import android.content.ClipData; 23import android.content.Context; 24import android.content.res.Configuration; 25import android.content.res.Resources; 26import android.content.res.TypedArray; 27import android.graphics.Bitmap; 28import android.graphics.Camera; 29import android.graphics.Canvas; 30import android.graphics.Insets; 31import android.graphics.Interpolator; 32import android.graphics.LinearGradient; 33import android.graphics.Matrix; 34import android.graphics.Paint; 35import android.graphics.Path; 36import android.graphics.PixelFormat; 37import android.graphics.Point; 38import android.graphics.PorterDuff; 39import android.graphics.PorterDuffXfermode; 40import android.graphics.Rect; 41import android.graphics.RectF; 42import android.graphics.Region; 43import android.graphics.Shader; 44import android.graphics.drawable.ColorDrawable; 45import android.graphics.drawable.Drawable; 46import android.hardware.display.DisplayManagerGlobal; 47import android.os.Bundle; 48import android.os.Handler; 49import android.os.IBinder; 50import android.os.Parcel; 51import android.os.Parcelable; 52import android.os.RemoteException; 53import android.os.SystemClock; 54import android.os.SystemProperties; 55import android.text.TextUtils; 56import android.util.AttributeSet; 57import android.util.FloatProperty; 58import android.util.LayoutDirection; 59import android.util.Log; 60import android.util.LongSparseLongArray; 61import android.util.Pools.SynchronizedPool; 62import android.util.Property; 63import android.util.SparseArray; 64import android.util.SuperNotCalledException; 65import android.util.TypedValue; 66import android.view.ContextMenu.ContextMenuInfo; 67import android.view.AccessibilityIterators.TextSegmentIterator; 68import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 69import android.view.AccessibilityIterators.WordTextSegmentIterator; 70import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 71import android.view.accessibility.AccessibilityEvent; 72import android.view.accessibility.AccessibilityEventSource; 73import android.view.accessibility.AccessibilityManager; 74import android.view.accessibility.AccessibilityNodeInfo; 75import android.view.accessibility.AccessibilityNodeProvider; 76import android.view.animation.Animation; 77import android.view.animation.AnimationUtils; 78import android.view.animation.Transformation; 79import android.view.inputmethod.EditorInfo; 80import android.view.inputmethod.InputConnection; 81import android.view.inputmethod.InputMethodManager; 82import android.widget.ScrollBarDrawable; 83 84import static android.os.Build.VERSION_CODES.*; 85import static java.lang.Math.max; 86 87import com.android.internal.R; 88import com.android.internal.util.Predicate; 89import com.android.internal.view.menu.MenuBuilder; 90 91import com.google.android.collect.Lists; 92import com.google.android.collect.Maps; 93 94import java.lang.annotation.Retention; 95import java.lang.annotation.RetentionPolicy; 96import java.lang.ref.WeakReference; 97import java.lang.reflect.Field; 98import java.lang.reflect.InvocationTargetException; 99import java.lang.reflect.Method; 100import java.lang.reflect.Modifier; 101import java.util.ArrayList; 102import java.util.Arrays; 103import java.util.Collections; 104import java.util.HashMap; 105import java.util.Locale; 106import java.util.concurrent.CopyOnWriteArrayList; 107import java.util.concurrent.atomic.AtomicInteger; 108 109/** 110 * <p> 111 * This class represents the basic building block for user interface components. A View 112 * occupies a rectangular area on the screen and is responsible for drawing and 113 * event handling. View is the base class for <em>widgets</em>, which are 114 * used to create interactive UI components (buttons, text fields, etc.). The 115 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 116 * are invisible containers that hold other Views (or other ViewGroups) and define 117 * their layout properties. 118 * </p> 119 * 120 * <div class="special reference"> 121 * <h3>Developer Guides</h3> 122 * <p>For information about using this class to develop your application's user interface, 123 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 124 * </div> 125 * 126 * <a name="Using"></a> 127 * <h3>Using Views</h3> 128 * <p> 129 * All of the views in a window are arranged in a single tree. You can add views 130 * either from code or by specifying a tree of views in one or more XML layout 131 * files. There are many specialized subclasses of views that act as controls or 132 * are capable of displaying text, images, or other content. 133 * </p> 134 * <p> 135 * Once you have created a tree of views, there are typically a few types of 136 * common operations you may wish to perform: 137 * <ul> 138 * <li><strong>Set properties:</strong> for example setting the text of a 139 * {@link android.widget.TextView}. The available properties and the methods 140 * that set them will vary among the different subclasses of views. Note that 141 * properties that are known at build time can be set in the XML layout 142 * files.</li> 143 * <li><strong>Set focus:</strong> The framework will handled moving focus in 144 * response to user input. To force focus to a specific view, call 145 * {@link #requestFocus}.</li> 146 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 147 * that will be notified when something interesting happens to the view. For 148 * example, all views will let you set a listener to be notified when the view 149 * gains or loses focus. You can register such a listener using 150 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 151 * Other view subclasses offer more specialized listeners. For example, a Button 152 * exposes a listener to notify clients when the button is clicked.</li> 153 * <li><strong>Set visibility:</strong> You can hide or show views using 154 * {@link #setVisibility(int)}.</li> 155 * </ul> 156 * </p> 157 * <p><em> 158 * Note: The Android framework is responsible for measuring, laying out and 159 * drawing views. You should not call methods that perform these actions on 160 * views yourself unless you are actually implementing a 161 * {@link android.view.ViewGroup}. 162 * </em></p> 163 * 164 * <a name="Lifecycle"></a> 165 * <h3>Implementing a Custom View</h3> 166 * 167 * <p> 168 * To implement a custom view, you will usually begin by providing overrides for 169 * some of the standard methods that the framework calls on all views. You do 170 * not need to override all of these methods. In fact, you can start by just 171 * overriding {@link #onDraw(android.graphics.Canvas)}. 172 * <table border="2" width="85%" align="center" cellpadding="5"> 173 * <thead> 174 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 175 * </thead> 176 * 177 * <tbody> 178 * <tr> 179 * <td rowspan="2">Creation</td> 180 * <td>Constructors</td> 181 * <td>There is a form of the constructor that are called when the view 182 * is created from code and a form that is called when the view is 183 * inflated from a layout file. The second form should parse and apply 184 * any attributes defined in the layout file. 185 * </td> 186 * </tr> 187 * <tr> 188 * <td><code>{@link #onFinishInflate()}</code></td> 189 * <td>Called after a view and all of its children has been inflated 190 * from XML.</td> 191 * </tr> 192 * 193 * <tr> 194 * <td rowspan="3">Layout</td> 195 * <td><code>{@link #onMeasure(int, int)}</code></td> 196 * <td>Called to determine the size requirements for this view and all 197 * of its children. 198 * </td> 199 * </tr> 200 * <tr> 201 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 202 * <td>Called when this view should assign a size and position to all 203 * of its children. 204 * </td> 205 * </tr> 206 * <tr> 207 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 208 * <td>Called when the size of this view has changed. 209 * </td> 210 * </tr> 211 * 212 * <tr> 213 * <td>Drawing</td> 214 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 215 * <td>Called when the view should render its content. 216 * </td> 217 * </tr> 218 * 219 * <tr> 220 * <td rowspan="4">Event processing</td> 221 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 222 * <td>Called when a new hardware key event occurs. 223 * </td> 224 * </tr> 225 * <tr> 226 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 227 * <td>Called when a hardware key up event occurs. 228 * </td> 229 * </tr> 230 * <tr> 231 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 232 * <td>Called when a trackball motion event occurs. 233 * </td> 234 * </tr> 235 * <tr> 236 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 237 * <td>Called when a touch screen motion event occurs. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td rowspan="2">Focus</td> 243 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 244 * <td>Called when the view gains or loses focus. 245 * </td> 246 * </tr> 247 * 248 * <tr> 249 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 250 * <td>Called when the window containing the view gains or loses focus. 251 * </td> 252 * </tr> 253 * 254 * <tr> 255 * <td rowspan="3">Attaching</td> 256 * <td><code>{@link #onAttachedToWindow()}</code></td> 257 * <td>Called when the view is attached to a window. 258 * </td> 259 * </tr> 260 * 261 * <tr> 262 * <td><code>{@link #onDetachedFromWindow}</code></td> 263 * <td>Called when the view is detached from its window. 264 * </td> 265 * </tr> 266 * 267 * <tr> 268 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 269 * <td>Called when the visibility of the window containing the view 270 * has changed. 271 * </td> 272 * </tr> 273 * </tbody> 274 * 275 * </table> 276 * </p> 277 * 278 * <a name="IDs"></a> 279 * <h3>IDs</h3> 280 * Views may have an integer id associated with them. These ids are typically 281 * assigned in the layout XML files, and are used to find specific views within 282 * the view tree. A common pattern is to: 283 * <ul> 284 * <li>Define a Button in the layout file and assign it a unique ID. 285 * <pre> 286 * <Button 287 * android:id="@+id/my_button" 288 * android:layout_width="wrap_content" 289 * android:layout_height="wrap_content" 290 * android:text="@string/my_button_text"/> 291 * </pre></li> 292 * <li>From the onCreate method of an Activity, find the Button 293 * <pre class="prettyprint"> 294 * Button myButton = (Button) findViewById(R.id.my_button); 295 * </pre></li> 296 * </ul> 297 * <p> 298 * View IDs need not be unique throughout the tree, but it is good practice to 299 * ensure that they are at least unique within the part of the tree you are 300 * searching. 301 * </p> 302 * 303 * <a name="Position"></a> 304 * <h3>Position</h3> 305 * <p> 306 * The geometry of a view is that of a rectangle. A view has a location, 307 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 308 * two dimensions, expressed as a width and a height. The unit for location 309 * and dimensions is the pixel. 310 * </p> 311 * 312 * <p> 313 * It is possible to retrieve the location of a view by invoking the methods 314 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 315 * coordinate of the rectangle representing the view. The latter returns the 316 * top, or Y, coordinate of the rectangle representing the view. These methods 317 * both return the location of the view relative to its parent. For instance, 318 * when getLeft() returns 20, that means the view is located 20 pixels to the 319 * right of the left edge of its direct parent. 320 * </p> 321 * 322 * <p> 323 * In addition, several convenience methods are offered to avoid unnecessary 324 * computations, namely {@link #getRight()} and {@link #getBottom()}. 325 * These methods return the coordinates of the right and bottom edges of the 326 * rectangle representing the view. For instance, calling {@link #getRight()} 327 * is similar to the following computation: <code>getLeft() + getWidth()</code> 328 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 329 * </p> 330 * 331 * <a name="SizePaddingMargins"></a> 332 * <h3>Size, padding and margins</h3> 333 * <p> 334 * The size of a view is expressed with a width and a height. A view actually 335 * possess two pairs of width and height values. 336 * </p> 337 * 338 * <p> 339 * The first pair is known as <em>measured width</em> and 340 * <em>measured height</em>. These dimensions define how big a view wants to be 341 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 342 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 343 * and {@link #getMeasuredHeight()}. 344 * </p> 345 * 346 * <p> 347 * The second pair is simply known as <em>width</em> and <em>height</em>, or 348 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 349 * dimensions define the actual size of the view on screen, at drawing time and 350 * after layout. These values may, but do not have to, be different from the 351 * measured width and height. The width and height can be obtained by calling 352 * {@link #getWidth()} and {@link #getHeight()}. 353 * </p> 354 * 355 * <p> 356 * To measure its dimensions, a view takes into account its padding. The padding 357 * is expressed in pixels for the left, top, right and bottom parts of the view. 358 * Padding can be used to offset the content of the view by a specific amount of 359 * pixels. For instance, a left padding of 2 will push the view's content by 360 * 2 pixels to the right of the left edge. Padding can be set using the 361 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 362 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 363 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 364 * {@link #getPaddingEnd()}. 365 * </p> 366 * 367 * <p> 368 * Even though a view can define a padding, it does not provide any support for 369 * margins. However, view groups provide such a support. Refer to 370 * {@link android.view.ViewGroup} and 371 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 372 * </p> 373 * 374 * <a name="Layout"></a> 375 * <h3>Layout</h3> 376 * <p> 377 * Layout is a two pass process: a measure pass and a layout pass. The measuring 378 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 379 * of the view tree. Each view pushes dimension specifications down the tree 380 * during the recursion. At the end of the measure pass, every view has stored 381 * its measurements. The second pass happens in 382 * {@link #layout(int,int,int,int)} and is also top-down. During 383 * this pass each parent is responsible for positioning all of its children 384 * using the sizes computed in the measure pass. 385 * </p> 386 * 387 * <p> 388 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 389 * {@link #getMeasuredHeight()} values must be set, along with those for all of 390 * that view's descendants. A view's measured width and measured height values 391 * must respect the constraints imposed by the view's parents. This guarantees 392 * that at the end of the measure pass, all parents accept all of their 393 * children's measurements. A parent view may call measure() more than once on 394 * its children. For example, the parent may measure each child once with 395 * unspecified dimensions to find out how big they want to be, then call 396 * measure() on them again with actual numbers if the sum of all the children's 397 * unconstrained sizes is too big or too small. 398 * </p> 399 * 400 * <p> 401 * The measure pass uses two classes to communicate dimensions. The 402 * {@link MeasureSpec} class is used by views to tell their parents how they 403 * want to be measured and positioned. The base LayoutParams class just 404 * describes how big the view wants to be for both width and height. For each 405 * dimension, it can specify one of: 406 * <ul> 407 * <li> an exact number 408 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 409 * (minus padding) 410 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 411 * enclose its content (plus padding). 412 * </ul> 413 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 414 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 415 * an X and Y value. 416 * </p> 417 * 418 * <p> 419 * MeasureSpecs are used to push requirements down the tree from parent to 420 * child. A MeasureSpec can be in one of three modes: 421 * <ul> 422 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 423 * of a child view. For example, a LinearLayout may call measure() on its child 424 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 425 * tall the child view wants to be given a width of 240 pixels. 426 * <li>EXACTLY: This is used by the parent to impose an exact size on the 427 * child. The child must use this size, and guarantee that all of its 428 * descendants will fit within this size. 429 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 430 * child. The child must gurantee that it and all of its descendants will fit 431 * within this size. 432 * </ul> 433 * </p> 434 * 435 * <p> 436 * To intiate a layout, call {@link #requestLayout}. This method is typically 437 * called by a view on itself when it believes that is can no longer fit within 438 * its current bounds. 439 * </p> 440 * 441 * <a name="Drawing"></a> 442 * <h3>Drawing</h3> 443 * <p> 444 * Drawing is handled by walking the tree and rendering each view that 445 * intersects the invalid region. Because the tree is traversed in-order, 446 * this means that parents will draw before (i.e., behind) their children, with 447 * siblings drawn in the order they appear in the tree. 448 * If you set a background drawable for a View, then the View will draw it for you 449 * before calling back to its <code>onDraw()</code> method. 450 * </p> 451 * 452 * <p> 453 * Note that the framework will not draw views that are not in the invalid region. 454 * </p> 455 * 456 * <p> 457 * To force a view to draw, call {@link #invalidate()}. 458 * </p> 459 * 460 * <a name="EventHandlingThreading"></a> 461 * <h3>Event Handling and Threading</h3> 462 * <p> 463 * The basic cycle of a view is as follows: 464 * <ol> 465 * <li>An event comes in and is dispatched to the appropriate view. The view 466 * handles the event and notifies any listeners.</li> 467 * <li>If in the course of processing the event, the view's bounds may need 468 * to be changed, the view will call {@link #requestLayout()}.</li> 469 * <li>Similarly, if in the course of processing the event the view's appearance 470 * may need to be changed, the view will call {@link #invalidate()}.</li> 471 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 472 * the framework will take care of measuring, laying out, and drawing the tree 473 * as appropriate.</li> 474 * </ol> 475 * </p> 476 * 477 * <p><em>Note: The entire view tree is single threaded. You must always be on 478 * the UI thread when calling any method on any view.</em> 479 * If you are doing work on other threads and want to update the state of a view 480 * from that thread, you should use a {@link Handler}. 481 * </p> 482 * 483 * <a name="FocusHandling"></a> 484 * <h3>Focus Handling</h3> 485 * <p> 486 * The framework will handle routine focus movement in response to user input. 487 * This includes changing the focus as views are removed or hidden, or as new 488 * views become available. Views indicate their willingness to take focus 489 * through the {@link #isFocusable} method. To change whether a view can take 490 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 491 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 492 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 493 * </p> 494 * <p> 495 * Focus movement is based on an algorithm which finds the nearest neighbor in a 496 * given direction. In rare cases, the default algorithm may not match the 497 * intended behavior of the developer. In these situations, you can provide 498 * explicit overrides by using these XML attributes in the layout file: 499 * <pre> 500 * nextFocusDown 501 * nextFocusLeft 502 * nextFocusRight 503 * nextFocusUp 504 * </pre> 505 * </p> 506 * 507 * 508 * <p> 509 * To get a particular view to take focus, call {@link #requestFocus()}. 510 * </p> 511 * 512 * <a name="TouchMode"></a> 513 * <h3>Touch Mode</h3> 514 * <p> 515 * When a user is navigating a user interface via directional keys such as a D-pad, it is 516 * necessary to give focus to actionable items such as buttons so the user can see 517 * what will take input. If the device has touch capabilities, however, and the user 518 * begins interacting with the interface by touching it, it is no longer necessary to 519 * always highlight, or give focus to, a particular view. This motivates a mode 520 * for interaction named 'touch mode'. 521 * </p> 522 * <p> 523 * For a touch capable device, once the user touches the screen, the device 524 * will enter touch mode. From this point onward, only views for which 525 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 526 * Other views that are touchable, like buttons, will not take focus when touched; they will 527 * only fire the on click listeners. 528 * </p> 529 * <p> 530 * Any time a user hits a directional key, such as a D-pad direction, the view device will 531 * exit touch mode, and find a view to take focus, so that the user may resume interacting 532 * with the user interface without touching the screen again. 533 * </p> 534 * <p> 535 * The touch mode state is maintained across {@link android.app.Activity}s. Call 536 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 537 * </p> 538 * 539 * <a name="Scrolling"></a> 540 * <h3>Scrolling</h3> 541 * <p> 542 * The framework provides basic support for views that wish to internally 543 * scroll their content. This includes keeping track of the X and Y scroll 544 * offset as well as mechanisms for drawing scrollbars. See 545 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 546 * {@link #awakenScrollBars()} for more details. 547 * </p> 548 * 549 * <a name="Tags"></a> 550 * <h3>Tags</h3> 551 * <p> 552 * Unlike IDs, tags are not used to identify views. Tags are essentially an 553 * extra piece of information that can be associated with a view. They are most 554 * often used as a convenience to store data related to views in the views 555 * themselves rather than by putting them in a separate structure. 556 * </p> 557 * 558 * <a name="Properties"></a> 559 * <h3>Properties</h3> 560 * <p> 561 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 562 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 563 * available both in the {@link Property} form as well as in similarly-named setter/getter 564 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 565 * be used to set persistent state associated with these rendering-related properties on the view. 566 * The properties and methods can also be used in conjunction with 567 * {@link android.animation.Animator Animator}-based animations, described more in the 568 * <a href="#Animation">Animation</a> section. 569 * </p> 570 * 571 * <a name="Animation"></a> 572 * <h3>Animation</h3> 573 * <p> 574 * Starting with Android 3.0, the preferred way of animating views is to use the 575 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 576 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 577 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 578 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 579 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 580 * makes animating these View properties particularly easy and efficient. 581 * </p> 582 * <p> 583 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 584 * You can attach an {@link Animation} object to a view using 585 * {@link #setAnimation(Animation)} or 586 * {@link #startAnimation(Animation)}. The animation can alter the scale, 587 * rotation, translation and alpha of a view over time. If the animation is 588 * attached to a view that has children, the animation will affect the entire 589 * subtree rooted by that node. When an animation is started, the framework will 590 * take care of redrawing the appropriate views until the animation completes. 591 * </p> 592 * 593 * <a name="Security"></a> 594 * <h3>Security</h3> 595 * <p> 596 * Sometimes it is essential that an application be able to verify that an action 597 * is being performed with the full knowledge and consent of the user, such as 598 * granting a permission request, making a purchase or clicking on an advertisement. 599 * Unfortunately, a malicious application could try to spoof the user into 600 * performing these actions, unaware, by concealing the intended purpose of the view. 601 * As a remedy, the framework offers a touch filtering mechanism that can be used to 602 * improve the security of views that provide access to sensitive functionality. 603 * </p><p> 604 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 605 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 606 * will discard touches that are received whenever the view's window is obscured by 607 * another visible window. As a result, the view will not receive touches whenever a 608 * toast, dialog or other window appears above the view's window. 609 * </p><p> 610 * For more fine-grained control over security, consider overriding the 611 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 612 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 613 * </p> 614 * 615 * @attr ref android.R.styleable#View_alpha 616 * @attr ref android.R.styleable#View_background 617 * @attr ref android.R.styleable#View_clickable 618 * @attr ref android.R.styleable#View_contentDescription 619 * @attr ref android.R.styleable#View_drawingCacheQuality 620 * @attr ref android.R.styleable#View_duplicateParentState 621 * @attr ref android.R.styleable#View_id 622 * @attr ref android.R.styleable#View_requiresFadingEdge 623 * @attr ref android.R.styleable#View_fadeScrollbars 624 * @attr ref android.R.styleable#View_fadingEdgeLength 625 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 626 * @attr ref android.R.styleable#View_fitsSystemWindows 627 * @attr ref android.R.styleable#View_isScrollContainer 628 * @attr ref android.R.styleable#View_focusable 629 * @attr ref android.R.styleable#View_focusableInTouchMode 630 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 631 * @attr ref android.R.styleable#View_keepScreenOn 632 * @attr ref android.R.styleable#View_layerType 633 * @attr ref android.R.styleable#View_layoutDirection 634 * @attr ref android.R.styleable#View_longClickable 635 * @attr ref android.R.styleable#View_minHeight 636 * @attr ref android.R.styleable#View_minWidth 637 * @attr ref android.R.styleable#View_nextFocusDown 638 * @attr ref android.R.styleable#View_nextFocusLeft 639 * @attr ref android.R.styleable#View_nextFocusRight 640 * @attr ref android.R.styleable#View_nextFocusUp 641 * @attr ref android.R.styleable#View_onClick 642 * @attr ref android.R.styleable#View_padding 643 * @attr ref android.R.styleable#View_paddingBottom 644 * @attr ref android.R.styleable#View_paddingLeft 645 * @attr ref android.R.styleable#View_paddingRight 646 * @attr ref android.R.styleable#View_paddingTop 647 * @attr ref android.R.styleable#View_paddingStart 648 * @attr ref android.R.styleable#View_paddingEnd 649 * @attr ref android.R.styleable#View_saveEnabled 650 * @attr ref android.R.styleable#View_rotation 651 * @attr ref android.R.styleable#View_rotationX 652 * @attr ref android.R.styleable#View_rotationY 653 * @attr ref android.R.styleable#View_scaleX 654 * @attr ref android.R.styleable#View_scaleY 655 * @attr ref android.R.styleable#View_scrollX 656 * @attr ref android.R.styleable#View_scrollY 657 * @attr ref android.R.styleable#View_scrollbarSize 658 * @attr ref android.R.styleable#View_scrollbarStyle 659 * @attr ref android.R.styleable#View_scrollbars 660 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 661 * @attr ref android.R.styleable#View_scrollbarFadeDuration 662 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 663 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 664 * @attr ref android.R.styleable#View_scrollbarThumbVertical 665 * @attr ref android.R.styleable#View_scrollbarTrackVertical 666 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 667 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 668 * @attr ref android.R.styleable#View_soundEffectsEnabled 669 * @attr ref android.R.styleable#View_tag 670 * @attr ref android.R.styleable#View_textAlignment 671 * @attr ref android.R.styleable#View_textDirection 672 * @attr ref android.R.styleable#View_transformPivotX 673 * @attr ref android.R.styleable#View_transformPivotY 674 * @attr ref android.R.styleable#View_translationX 675 * @attr ref android.R.styleable#View_translationY 676 * @attr ref android.R.styleable#View_translationZ 677 * @attr ref android.R.styleable#View_visibility 678 * 679 * @see android.view.ViewGroup 680 */ 681public class View implements Drawable.Callback, KeyEvent.Callback, 682 AccessibilityEventSource { 683 private static final boolean DBG = false; 684 685 /** 686 * The logging tag used by this class with android.util.Log. 687 */ 688 protected static final String VIEW_LOG_TAG = "View"; 689 690 /** 691 * When set to true, apps will draw debugging information about their layouts. 692 * 693 * @hide 694 */ 695 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 696 697 /** 698 * Used to mark a View that has no ID. 699 */ 700 public static final int NO_ID = -1; 701 702 /** 703 * Signals that compatibility booleans have been initialized according to 704 * target SDK versions. 705 */ 706 private static boolean sCompatibilityDone = false; 707 708 /** 709 * Use the old (broken) way of building MeasureSpecs. 710 */ 711 private static boolean sUseBrokenMakeMeasureSpec = false; 712 713 /** 714 * Ignore any optimizations using the measure cache. 715 */ 716 private static boolean sIgnoreMeasureCache = false; 717 718 /** 719 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 720 * calling setFlags. 721 */ 722 private static final int NOT_FOCUSABLE = 0x00000000; 723 724 /** 725 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 726 * setFlags. 727 */ 728 private static final int FOCUSABLE = 0x00000001; 729 730 /** 731 * Mask for use with setFlags indicating bits used for focus. 732 */ 733 private static final int FOCUSABLE_MASK = 0x00000001; 734 735 /** 736 * This view will adjust its padding to fit sytem windows (e.g. status bar) 737 */ 738 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 739 740 /** @hide */ 741 @IntDef({VISIBLE, INVISIBLE, GONE}) 742 @Retention(RetentionPolicy.SOURCE) 743 public @interface Visibility {} 744 745 /** 746 * This view is visible. 747 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 748 * android:visibility}. 749 */ 750 public static final int VISIBLE = 0x00000000; 751 752 /** 753 * This view is invisible, but it still takes up space for layout purposes. 754 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 755 * android:visibility}. 756 */ 757 public static final int INVISIBLE = 0x00000004; 758 759 /** 760 * This view is invisible, and it doesn't take any space for layout 761 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 762 * android:visibility}. 763 */ 764 public static final int GONE = 0x00000008; 765 766 /** 767 * Mask for use with setFlags indicating bits used for visibility. 768 * {@hide} 769 */ 770 static final int VISIBILITY_MASK = 0x0000000C; 771 772 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 773 774 /** 775 * This view is enabled. Interpretation varies by subclass. 776 * Use with ENABLED_MASK when calling setFlags. 777 * {@hide} 778 */ 779 static final int ENABLED = 0x00000000; 780 781 /** 782 * This view is disabled. Interpretation varies by subclass. 783 * Use with ENABLED_MASK when calling setFlags. 784 * {@hide} 785 */ 786 static final int DISABLED = 0x00000020; 787 788 /** 789 * Mask for use with setFlags indicating bits used for indicating whether 790 * this view is enabled 791 * {@hide} 792 */ 793 static final int ENABLED_MASK = 0x00000020; 794 795 /** 796 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 797 * called and further optimizations will be performed. It is okay to have 798 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 799 * {@hide} 800 */ 801 static final int WILL_NOT_DRAW = 0x00000080; 802 803 /** 804 * Mask for use with setFlags indicating bits used for indicating whether 805 * this view is will draw 806 * {@hide} 807 */ 808 static final int DRAW_MASK = 0x00000080; 809 810 /** 811 * <p>This view doesn't show scrollbars.</p> 812 * {@hide} 813 */ 814 static final int SCROLLBARS_NONE = 0x00000000; 815 816 /** 817 * <p>This view shows horizontal scrollbars.</p> 818 * {@hide} 819 */ 820 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 821 822 /** 823 * <p>This view shows vertical scrollbars.</p> 824 * {@hide} 825 */ 826 static final int SCROLLBARS_VERTICAL = 0x00000200; 827 828 /** 829 * <p>Mask for use with setFlags indicating bits used for indicating which 830 * scrollbars are enabled.</p> 831 * {@hide} 832 */ 833 static final int SCROLLBARS_MASK = 0x00000300; 834 835 /** 836 * Indicates that the view should filter touches when its window is obscured. 837 * Refer to the class comments for more information about this security feature. 838 * {@hide} 839 */ 840 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 841 842 /** 843 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 844 * that they are optional and should be skipped if the window has 845 * requested system UI flags that ignore those insets for layout. 846 */ 847 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 848 849 /** 850 * <p>This view doesn't show fading edges.</p> 851 * {@hide} 852 */ 853 static final int FADING_EDGE_NONE = 0x00000000; 854 855 /** 856 * <p>This view shows horizontal fading edges.</p> 857 * {@hide} 858 */ 859 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 860 861 /** 862 * <p>This view shows vertical fading edges.</p> 863 * {@hide} 864 */ 865 static final int FADING_EDGE_VERTICAL = 0x00002000; 866 867 /** 868 * <p>Mask for use with setFlags indicating bits used for indicating which 869 * fading edges are enabled.</p> 870 * {@hide} 871 */ 872 static final int FADING_EDGE_MASK = 0x00003000; 873 874 /** 875 * <p>Indicates this view can be clicked. When clickable, a View reacts 876 * to clicks by notifying the OnClickListener.<p> 877 * {@hide} 878 */ 879 static final int CLICKABLE = 0x00004000; 880 881 /** 882 * <p>Indicates this view is caching its drawing into a bitmap.</p> 883 * {@hide} 884 */ 885 static final int DRAWING_CACHE_ENABLED = 0x00008000; 886 887 /** 888 * <p>Indicates that no icicle should be saved for this view.<p> 889 * {@hide} 890 */ 891 static final int SAVE_DISABLED = 0x000010000; 892 893 /** 894 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 895 * property.</p> 896 * {@hide} 897 */ 898 static final int SAVE_DISABLED_MASK = 0x000010000; 899 900 /** 901 * <p>Indicates that no drawing cache should ever be created for this view.<p> 902 * {@hide} 903 */ 904 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 905 906 /** 907 * <p>Indicates this view can take / keep focus when int touch mode.</p> 908 * {@hide} 909 */ 910 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 911 912 /** @hide */ 913 @Retention(RetentionPolicy.SOURCE) 914 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 915 public @interface DrawingCacheQuality {} 916 917 /** 918 * <p>Enables low quality mode for the drawing cache.</p> 919 */ 920 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 921 922 /** 923 * <p>Enables high quality mode for the drawing cache.</p> 924 */ 925 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 926 927 /** 928 * <p>Enables automatic quality mode for the drawing cache.</p> 929 */ 930 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 931 932 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 933 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 934 }; 935 936 /** 937 * <p>Mask for use with setFlags indicating bits used for the cache 938 * quality property.</p> 939 * {@hide} 940 */ 941 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 942 943 /** 944 * <p> 945 * Indicates this view can be long clicked. When long clickable, a View 946 * reacts to long clicks by notifying the OnLongClickListener or showing a 947 * context menu. 948 * </p> 949 * {@hide} 950 */ 951 static final int LONG_CLICKABLE = 0x00200000; 952 953 /** 954 * <p>Indicates that this view gets its drawable states from its direct parent 955 * and ignores its original internal states.</p> 956 * 957 * @hide 958 */ 959 static final int DUPLICATE_PARENT_STATE = 0x00400000; 960 961 /** @hide */ 962 @IntDef({ 963 SCROLLBARS_INSIDE_OVERLAY, 964 SCROLLBARS_INSIDE_INSET, 965 SCROLLBARS_OUTSIDE_OVERLAY, 966 SCROLLBARS_OUTSIDE_INSET 967 }) 968 @Retention(RetentionPolicy.SOURCE) 969 public @interface ScrollBarStyle {} 970 971 /** 972 * The scrollbar style to display the scrollbars inside the content area, 973 * without increasing the padding. The scrollbars will be overlaid with 974 * translucency on the view's content. 975 */ 976 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 977 978 /** 979 * The scrollbar style to display the scrollbars inside the padded area, 980 * increasing the padding of the view. The scrollbars will not overlap the 981 * content area of the view. 982 */ 983 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 984 985 /** 986 * The scrollbar style to display the scrollbars at the edge of the view, 987 * without increasing the padding. The scrollbars will be overlaid with 988 * translucency. 989 */ 990 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 991 992 /** 993 * The scrollbar style to display the scrollbars at the edge of the view, 994 * increasing the padding of the view. The scrollbars will only overlap the 995 * background, if any. 996 */ 997 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 998 999 /** 1000 * Mask to check if the scrollbar style is overlay or inset. 1001 * {@hide} 1002 */ 1003 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1004 1005 /** 1006 * Mask to check if the scrollbar style is inside or outside. 1007 * {@hide} 1008 */ 1009 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1010 1011 /** 1012 * Mask for scrollbar style. 1013 * {@hide} 1014 */ 1015 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1016 1017 /** 1018 * View flag indicating that the screen should remain on while the 1019 * window containing this view is visible to the user. This effectively 1020 * takes care of automatically setting the WindowManager's 1021 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1022 */ 1023 public static final int KEEP_SCREEN_ON = 0x04000000; 1024 1025 /** 1026 * View flag indicating whether this view should have sound effects enabled 1027 * for events such as clicking and touching. 1028 */ 1029 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1030 1031 /** 1032 * View flag indicating whether this view should have haptic feedback 1033 * enabled for events such as long presses. 1034 */ 1035 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1036 1037 /** 1038 * <p>Indicates that the view hierarchy should stop saving state when 1039 * it reaches this view. If state saving is initiated immediately at 1040 * the view, it will be allowed. 1041 * {@hide} 1042 */ 1043 static final int PARENT_SAVE_DISABLED = 0x20000000; 1044 1045 /** 1046 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1047 * {@hide} 1048 */ 1049 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1050 1051 /** @hide */ 1052 @IntDef(flag = true, 1053 value = { 1054 FOCUSABLES_ALL, 1055 FOCUSABLES_TOUCH_MODE 1056 }) 1057 @Retention(RetentionPolicy.SOURCE) 1058 public @interface FocusableMode {} 1059 1060 /** 1061 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1062 * should add all focusable Views regardless if they are focusable in touch mode. 1063 */ 1064 public static final int FOCUSABLES_ALL = 0x00000000; 1065 1066 /** 1067 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1068 * should add only Views focusable in touch mode. 1069 */ 1070 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1071 1072 /** @hide */ 1073 @IntDef({ 1074 FOCUS_BACKWARD, 1075 FOCUS_FORWARD, 1076 FOCUS_LEFT, 1077 FOCUS_UP, 1078 FOCUS_RIGHT, 1079 FOCUS_DOWN 1080 }) 1081 @Retention(RetentionPolicy.SOURCE) 1082 public @interface FocusDirection {} 1083 1084 /** @hide */ 1085 @IntDef({ 1086 FOCUS_LEFT, 1087 FOCUS_UP, 1088 FOCUS_RIGHT, 1089 FOCUS_DOWN 1090 }) 1091 @Retention(RetentionPolicy.SOURCE) 1092 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1093 1094 /** 1095 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1096 * item. 1097 */ 1098 public static final int FOCUS_BACKWARD = 0x00000001; 1099 1100 /** 1101 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1102 * item. 1103 */ 1104 public static final int FOCUS_FORWARD = 0x00000002; 1105 1106 /** 1107 * Use with {@link #focusSearch(int)}. Move focus to the left. 1108 */ 1109 public static final int FOCUS_LEFT = 0x00000011; 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus up. 1113 */ 1114 public static final int FOCUS_UP = 0x00000021; 1115 1116 /** 1117 * Use with {@link #focusSearch(int)}. Move focus to the right. 1118 */ 1119 public static final int FOCUS_RIGHT = 0x00000042; 1120 1121 /** 1122 * Use with {@link #focusSearch(int)}. Move focus down. 1123 */ 1124 public static final int FOCUS_DOWN = 0x00000082; 1125 1126 /** 1127 * Bits of {@link #getMeasuredWidthAndState()} and 1128 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1129 */ 1130 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1131 1132 /** 1133 * Bits of {@link #getMeasuredWidthAndState()} and 1134 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1135 */ 1136 public static final int MEASURED_STATE_MASK = 0xff000000; 1137 1138 /** 1139 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1140 * for functions that combine both width and height into a single int, 1141 * such as {@link #getMeasuredState()} and the childState argument of 1142 * {@link #resolveSizeAndState(int, int, int)}. 1143 */ 1144 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1145 1146 /** 1147 * Bit of {@link #getMeasuredWidthAndState()} and 1148 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1149 * is smaller that the space the view would like to have. 1150 */ 1151 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1152 1153 /** 1154 * Base View state sets 1155 */ 1156 // Singles 1157 /** 1158 * Indicates the view has no states set. States are used with 1159 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1160 * view depending on its state. 1161 * 1162 * @see android.graphics.drawable.Drawable 1163 * @see #getDrawableState() 1164 */ 1165 protected static final int[] EMPTY_STATE_SET; 1166 /** 1167 * Indicates the view is enabled. States are used with 1168 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1169 * view depending on its state. 1170 * 1171 * @see android.graphics.drawable.Drawable 1172 * @see #getDrawableState() 1173 */ 1174 protected static final int[] ENABLED_STATE_SET; 1175 /** 1176 * Indicates the view is focused. States are used with 1177 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1178 * view depending on its state. 1179 * 1180 * @see android.graphics.drawable.Drawable 1181 * @see #getDrawableState() 1182 */ 1183 protected static final int[] FOCUSED_STATE_SET; 1184 /** 1185 * Indicates the view is selected. States are used with 1186 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1187 * view depending on its state. 1188 * 1189 * @see android.graphics.drawable.Drawable 1190 * @see #getDrawableState() 1191 */ 1192 protected static final int[] SELECTED_STATE_SET; 1193 /** 1194 * Indicates the view is pressed. States are used with 1195 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1196 * view depending on its state. 1197 * 1198 * @see android.graphics.drawable.Drawable 1199 * @see #getDrawableState() 1200 */ 1201 protected static final int[] PRESSED_STATE_SET; 1202 /** 1203 * Indicates the view's window has focus. States are used with 1204 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1205 * view depending on its state. 1206 * 1207 * @see android.graphics.drawable.Drawable 1208 * @see #getDrawableState() 1209 */ 1210 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1211 // Doubles 1212 /** 1213 * Indicates the view is enabled and has the focus. 1214 * 1215 * @see #ENABLED_STATE_SET 1216 * @see #FOCUSED_STATE_SET 1217 */ 1218 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1219 /** 1220 * Indicates the view is enabled and selected. 1221 * 1222 * @see #ENABLED_STATE_SET 1223 * @see #SELECTED_STATE_SET 1224 */ 1225 protected static final int[] ENABLED_SELECTED_STATE_SET; 1226 /** 1227 * Indicates the view is enabled and that its window has focus. 1228 * 1229 * @see #ENABLED_STATE_SET 1230 * @see #WINDOW_FOCUSED_STATE_SET 1231 */ 1232 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1233 /** 1234 * Indicates the view is focused and selected. 1235 * 1236 * @see #FOCUSED_STATE_SET 1237 * @see #SELECTED_STATE_SET 1238 */ 1239 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1240 /** 1241 * Indicates the view has the focus and that its window has the focus. 1242 * 1243 * @see #FOCUSED_STATE_SET 1244 * @see #WINDOW_FOCUSED_STATE_SET 1245 */ 1246 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1247 /** 1248 * Indicates the view is selected and that its window has the focus. 1249 * 1250 * @see #SELECTED_STATE_SET 1251 * @see #WINDOW_FOCUSED_STATE_SET 1252 */ 1253 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1254 // Triples 1255 /** 1256 * Indicates the view is enabled, focused and selected. 1257 * 1258 * @see #ENABLED_STATE_SET 1259 * @see #FOCUSED_STATE_SET 1260 * @see #SELECTED_STATE_SET 1261 */ 1262 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1263 /** 1264 * Indicates the view is enabled, focused and its window has the focus. 1265 * 1266 * @see #ENABLED_STATE_SET 1267 * @see #FOCUSED_STATE_SET 1268 * @see #WINDOW_FOCUSED_STATE_SET 1269 */ 1270 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1271 /** 1272 * Indicates the view is enabled, selected and its window has the focus. 1273 * 1274 * @see #ENABLED_STATE_SET 1275 * @see #SELECTED_STATE_SET 1276 * @see #WINDOW_FOCUSED_STATE_SET 1277 */ 1278 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1279 /** 1280 * Indicates the view is focused, selected and its window has the focus. 1281 * 1282 * @see #FOCUSED_STATE_SET 1283 * @see #SELECTED_STATE_SET 1284 * @see #WINDOW_FOCUSED_STATE_SET 1285 */ 1286 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1287 /** 1288 * Indicates the view is enabled, focused, selected and its window 1289 * has the focus. 1290 * 1291 * @see #ENABLED_STATE_SET 1292 * @see #FOCUSED_STATE_SET 1293 * @see #SELECTED_STATE_SET 1294 * @see #WINDOW_FOCUSED_STATE_SET 1295 */ 1296 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1297 /** 1298 * Indicates the view is pressed and its window has the focus. 1299 * 1300 * @see #PRESSED_STATE_SET 1301 * @see #WINDOW_FOCUSED_STATE_SET 1302 */ 1303 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1304 /** 1305 * Indicates the view is pressed and selected. 1306 * 1307 * @see #PRESSED_STATE_SET 1308 * @see #SELECTED_STATE_SET 1309 */ 1310 protected static final int[] PRESSED_SELECTED_STATE_SET; 1311 /** 1312 * Indicates the view is pressed, selected and its window has the focus. 1313 * 1314 * @see #PRESSED_STATE_SET 1315 * @see #SELECTED_STATE_SET 1316 * @see #WINDOW_FOCUSED_STATE_SET 1317 */ 1318 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1319 /** 1320 * Indicates the view is pressed and focused. 1321 * 1322 * @see #PRESSED_STATE_SET 1323 * @see #FOCUSED_STATE_SET 1324 */ 1325 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1326 /** 1327 * Indicates the view is pressed, focused and its window has the focus. 1328 * 1329 * @see #PRESSED_STATE_SET 1330 * @see #FOCUSED_STATE_SET 1331 * @see #WINDOW_FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1334 /** 1335 * Indicates the view is pressed, focused and selected. 1336 * 1337 * @see #PRESSED_STATE_SET 1338 * @see #SELECTED_STATE_SET 1339 * @see #FOCUSED_STATE_SET 1340 */ 1341 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1342 /** 1343 * Indicates the view is pressed, focused, selected and its window has the focus. 1344 * 1345 * @see #PRESSED_STATE_SET 1346 * @see #FOCUSED_STATE_SET 1347 * @see #SELECTED_STATE_SET 1348 * @see #WINDOW_FOCUSED_STATE_SET 1349 */ 1350 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1351 /** 1352 * Indicates the view is pressed and enabled. 1353 * 1354 * @see #PRESSED_STATE_SET 1355 * @see #ENABLED_STATE_SET 1356 */ 1357 protected static final int[] PRESSED_ENABLED_STATE_SET; 1358 /** 1359 * Indicates the view is pressed, enabled and its window has the focus. 1360 * 1361 * @see #PRESSED_STATE_SET 1362 * @see #ENABLED_STATE_SET 1363 * @see #WINDOW_FOCUSED_STATE_SET 1364 */ 1365 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1366 /** 1367 * Indicates the view is pressed, enabled and selected. 1368 * 1369 * @see #PRESSED_STATE_SET 1370 * @see #ENABLED_STATE_SET 1371 * @see #SELECTED_STATE_SET 1372 */ 1373 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1374 /** 1375 * Indicates the view is pressed, enabled, selected and its window has the 1376 * focus. 1377 * 1378 * @see #PRESSED_STATE_SET 1379 * @see #ENABLED_STATE_SET 1380 * @see #SELECTED_STATE_SET 1381 * @see #WINDOW_FOCUSED_STATE_SET 1382 */ 1383 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1384 /** 1385 * Indicates the view is pressed, enabled and focused. 1386 * 1387 * @see #PRESSED_STATE_SET 1388 * @see #ENABLED_STATE_SET 1389 * @see #FOCUSED_STATE_SET 1390 */ 1391 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1392 /** 1393 * Indicates the view is pressed, enabled, focused and its window has the 1394 * focus. 1395 * 1396 * @see #PRESSED_STATE_SET 1397 * @see #ENABLED_STATE_SET 1398 * @see #FOCUSED_STATE_SET 1399 * @see #WINDOW_FOCUSED_STATE_SET 1400 */ 1401 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1402 /** 1403 * Indicates the view is pressed, enabled, focused and selected. 1404 * 1405 * @see #PRESSED_STATE_SET 1406 * @see #ENABLED_STATE_SET 1407 * @see #SELECTED_STATE_SET 1408 * @see #FOCUSED_STATE_SET 1409 */ 1410 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1411 /** 1412 * Indicates the view is pressed, enabled, focused, selected and its window 1413 * has the focus. 1414 * 1415 * @see #PRESSED_STATE_SET 1416 * @see #ENABLED_STATE_SET 1417 * @see #SELECTED_STATE_SET 1418 * @see #FOCUSED_STATE_SET 1419 * @see #WINDOW_FOCUSED_STATE_SET 1420 */ 1421 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1422 1423 /** 1424 * The order here is very important to {@link #getDrawableState()} 1425 */ 1426 private static final int[][] VIEW_STATE_SETS; 1427 1428 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1429 static final int VIEW_STATE_SELECTED = 1 << 1; 1430 static final int VIEW_STATE_FOCUSED = 1 << 2; 1431 static final int VIEW_STATE_ENABLED = 1 << 3; 1432 static final int VIEW_STATE_PRESSED = 1 << 4; 1433 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1434 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1435 static final int VIEW_STATE_HOVERED = 1 << 7; 1436 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1437 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1438 1439 static final int[] VIEW_STATE_IDS = new int[] { 1440 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1441 R.attr.state_selected, VIEW_STATE_SELECTED, 1442 R.attr.state_focused, VIEW_STATE_FOCUSED, 1443 R.attr.state_enabled, VIEW_STATE_ENABLED, 1444 R.attr.state_pressed, VIEW_STATE_PRESSED, 1445 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1446 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1447 R.attr.state_hovered, VIEW_STATE_HOVERED, 1448 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1449 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1450 }; 1451 1452 static { 1453 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1454 throw new IllegalStateException( 1455 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1456 } 1457 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1458 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1459 int viewState = R.styleable.ViewDrawableStates[i]; 1460 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1461 if (VIEW_STATE_IDS[j] == viewState) { 1462 orderedIds[i * 2] = viewState; 1463 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1464 } 1465 } 1466 } 1467 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1468 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1469 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1470 int numBits = Integer.bitCount(i); 1471 int[] set = new int[numBits]; 1472 int pos = 0; 1473 for (int j = 0; j < orderedIds.length; j += 2) { 1474 if ((i & orderedIds[j+1]) != 0) { 1475 set[pos++] = orderedIds[j]; 1476 } 1477 } 1478 VIEW_STATE_SETS[i] = set; 1479 } 1480 1481 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1482 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1483 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1484 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1485 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1486 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1487 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1488 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1489 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1490 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1491 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1492 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1493 | VIEW_STATE_FOCUSED]; 1494 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1495 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1497 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1498 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1499 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1500 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1501 | VIEW_STATE_ENABLED]; 1502 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1503 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1504 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1506 | VIEW_STATE_ENABLED]; 1507 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1508 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1509 | VIEW_STATE_ENABLED]; 1510 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1512 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1513 1514 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1515 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1517 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1518 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1519 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1520 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1521 | VIEW_STATE_PRESSED]; 1522 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1523 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1524 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1525 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1526 | VIEW_STATE_PRESSED]; 1527 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1529 | VIEW_STATE_PRESSED]; 1530 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1532 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1533 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1534 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1535 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1537 | VIEW_STATE_PRESSED]; 1538 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1540 | VIEW_STATE_PRESSED]; 1541 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1543 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1544 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1546 | VIEW_STATE_PRESSED]; 1547 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1548 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1549 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1550 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1551 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1552 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1553 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1554 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1555 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1556 | VIEW_STATE_PRESSED]; 1557 } 1558 1559 /** 1560 * Accessibility event types that are dispatched for text population. 1561 */ 1562 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1563 AccessibilityEvent.TYPE_VIEW_CLICKED 1564 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1565 | AccessibilityEvent.TYPE_VIEW_SELECTED 1566 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1567 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1568 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1569 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1570 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1571 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1572 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1573 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1574 1575 /** 1576 * Temporary Rect currently for use in setBackground(). This will probably 1577 * be extended in the future to hold our own class with more than just 1578 * a Rect. :) 1579 */ 1580 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1581 1582 /** 1583 * Map used to store views' tags. 1584 */ 1585 private SparseArray<Object> mKeyedTags; 1586 1587 /** 1588 * The next available accessibility id. 1589 */ 1590 private static int sNextAccessibilityViewId; 1591 1592 /** 1593 * The animation currently associated with this view. 1594 * @hide 1595 */ 1596 protected Animation mCurrentAnimation = null; 1597 1598 /** 1599 * Width as measured during measure pass. 1600 * {@hide} 1601 */ 1602 @ViewDebug.ExportedProperty(category = "measurement") 1603 int mMeasuredWidth; 1604 1605 /** 1606 * Height as measured during measure pass. 1607 * {@hide} 1608 */ 1609 @ViewDebug.ExportedProperty(category = "measurement") 1610 int mMeasuredHeight; 1611 1612 /** 1613 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1614 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1615 * its display list. This flag, used only when hw accelerated, allows us to clear the 1616 * flag while retaining this information until it's needed (at getDisplayList() time and 1617 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1618 * 1619 * {@hide} 1620 */ 1621 boolean mRecreateDisplayList = false; 1622 1623 /** 1624 * The view's identifier. 1625 * {@hide} 1626 * 1627 * @see #setId(int) 1628 * @see #getId() 1629 */ 1630 @ViewDebug.ExportedProperty(resolveId = true) 1631 int mID = NO_ID; 1632 1633 /** 1634 * The stable ID of this view for accessibility purposes. 1635 */ 1636 int mAccessibilityViewId = NO_ID; 1637 1638 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1639 1640 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1641 1642 /** 1643 * The view's tag. 1644 * {@hide} 1645 * 1646 * @see #setTag(Object) 1647 * @see #getTag() 1648 */ 1649 protected Object mTag = null; 1650 1651 // for mPrivateFlags: 1652 /** {@hide} */ 1653 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1654 /** {@hide} */ 1655 static final int PFLAG_FOCUSED = 0x00000002; 1656 /** {@hide} */ 1657 static final int PFLAG_SELECTED = 0x00000004; 1658 /** {@hide} */ 1659 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1660 /** {@hide} */ 1661 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1662 /** {@hide} */ 1663 static final int PFLAG_DRAWN = 0x00000020; 1664 /** 1665 * When this flag is set, this view is running an animation on behalf of its 1666 * children and should therefore not cancel invalidate requests, even if they 1667 * lie outside of this view's bounds. 1668 * 1669 * {@hide} 1670 */ 1671 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1672 /** {@hide} */ 1673 static final int PFLAG_SKIP_DRAW = 0x00000080; 1674 /** {@hide} */ 1675 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1676 /** {@hide} */ 1677 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1678 /** {@hide} */ 1679 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1680 /** {@hide} */ 1681 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1682 /** {@hide} */ 1683 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1684 /** {@hide} */ 1685 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1686 1687 private static final int PFLAG_PRESSED = 0x00004000; 1688 1689 /** {@hide} */ 1690 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1691 /** 1692 * Flag used to indicate that this view should be drawn once more (and only once 1693 * more) after its animation has completed. 1694 * {@hide} 1695 */ 1696 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1697 1698 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1699 1700 /** 1701 * Indicates that the View returned true when onSetAlpha() was called and that 1702 * the alpha must be restored. 1703 * {@hide} 1704 */ 1705 static final int PFLAG_ALPHA_SET = 0x00040000; 1706 1707 /** 1708 * Set by {@link #setScrollContainer(boolean)}. 1709 */ 1710 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1711 1712 /** 1713 * Set by {@link #setScrollContainer(boolean)}. 1714 */ 1715 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1716 1717 /** 1718 * View flag indicating whether this view was invalidated (fully or partially.) 1719 * 1720 * @hide 1721 */ 1722 static final int PFLAG_DIRTY = 0x00200000; 1723 1724 /** 1725 * View flag indicating whether this view was invalidated by an opaque 1726 * invalidate request. 1727 * 1728 * @hide 1729 */ 1730 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1731 1732 /** 1733 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1734 * 1735 * @hide 1736 */ 1737 static final int PFLAG_DIRTY_MASK = 0x00600000; 1738 1739 /** 1740 * Indicates whether the background is opaque. 1741 * 1742 * @hide 1743 */ 1744 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1745 1746 /** 1747 * Indicates whether the scrollbars are opaque. 1748 * 1749 * @hide 1750 */ 1751 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1752 1753 /** 1754 * Indicates whether the view is opaque. 1755 * 1756 * @hide 1757 */ 1758 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1759 1760 /** 1761 * Indicates a prepressed state; 1762 * the short time between ACTION_DOWN and recognizing 1763 * a 'real' press. Prepressed is used to recognize quick taps 1764 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1765 * 1766 * @hide 1767 */ 1768 private static final int PFLAG_PREPRESSED = 0x02000000; 1769 1770 /** 1771 * Indicates whether the view is temporarily detached. 1772 * 1773 * @hide 1774 */ 1775 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1776 1777 /** 1778 * Indicates that we should awaken scroll bars once attached 1779 * 1780 * @hide 1781 */ 1782 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1783 1784 /** 1785 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1786 * @hide 1787 */ 1788 private static final int PFLAG_HOVERED = 0x10000000; 1789 1790 /** 1791 * Indicates that pivotX or pivotY were explicitly set and we should not assume the center 1792 * for transform operations 1793 * 1794 * @hide 1795 */ 1796 private static final int PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; 1797 1798 /** {@hide} */ 1799 static final int PFLAG_ACTIVATED = 0x40000000; 1800 1801 /** 1802 * Indicates that this view was specifically invalidated, not just dirtied because some 1803 * child view was invalidated. The flag is used to determine when we need to recreate 1804 * a view's display list (as opposed to just returning a reference to its existing 1805 * display list). 1806 * 1807 * @hide 1808 */ 1809 static final int PFLAG_INVALIDATED = 0x80000000; 1810 1811 /** 1812 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1813 * 1814 * |-------|-------|-------|-------| 1815 * 1 PFLAG2_DRAG_CAN_ACCEPT 1816 * 1 PFLAG2_DRAG_HOVERED 1817 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1818 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1819 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1820 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1821 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1822 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1823 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1824 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1825 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1826 * 111 PFLAG2_TEXT_DIRECTION_MASK 1827 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1828 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1829 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1830 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1831 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1832 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1833 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1834 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1835 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1836 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1837 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1838 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1839 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1840 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1841 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1842 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1843 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1844 * 1 PFLAG2_VIEW_QUICK_REJECTED 1845 * 1 PFLAG2_PADDING_RESOLVED 1846 * 1 PFLAG2_DRAWABLE_RESOLVED 1847 * 1 PFLAG2_HAS_TRANSIENT_STATE 1848 * |-------|-------|-------|-------| 1849 */ 1850 1851 /** 1852 * Indicates that this view has reported that it can accept the current drag's content. 1853 * Cleared when the drag operation concludes. 1854 * @hide 1855 */ 1856 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1857 1858 /** 1859 * Indicates that this view is currently directly under the drag location in a 1860 * drag-and-drop operation involving content that it can accept. Cleared when 1861 * the drag exits the view, or when the drag operation concludes. 1862 * @hide 1863 */ 1864 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1865 1866 /** @hide */ 1867 @IntDef({ 1868 LAYOUT_DIRECTION_LTR, 1869 LAYOUT_DIRECTION_RTL, 1870 LAYOUT_DIRECTION_INHERIT, 1871 LAYOUT_DIRECTION_LOCALE 1872 }) 1873 @Retention(RetentionPolicy.SOURCE) 1874 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1875 public @interface LayoutDir {} 1876 1877 /** @hide */ 1878 @IntDef({ 1879 LAYOUT_DIRECTION_LTR, 1880 LAYOUT_DIRECTION_RTL 1881 }) 1882 @Retention(RetentionPolicy.SOURCE) 1883 public @interface ResolvedLayoutDir {} 1884 1885 /** 1886 * Horizontal layout direction of this view is from Left to Right. 1887 * Use with {@link #setLayoutDirection}. 1888 */ 1889 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1890 1891 /** 1892 * Horizontal layout direction of this view is from Right to Left. 1893 * Use with {@link #setLayoutDirection}. 1894 */ 1895 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1896 1897 /** 1898 * Horizontal layout direction of this view is inherited from its parent. 1899 * Use with {@link #setLayoutDirection}. 1900 */ 1901 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1902 1903 /** 1904 * Horizontal layout direction of this view is from deduced from the default language 1905 * script for the locale. Use with {@link #setLayoutDirection}. 1906 */ 1907 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1908 1909 /** 1910 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1911 * @hide 1912 */ 1913 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1914 1915 /** 1916 * Mask for use with private flags indicating bits used for horizontal layout direction. 1917 * @hide 1918 */ 1919 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1920 1921 /** 1922 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1923 * right-to-left direction. 1924 * @hide 1925 */ 1926 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1927 1928 /** 1929 * Indicates whether the view horizontal layout direction has been resolved. 1930 * @hide 1931 */ 1932 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1933 1934 /** 1935 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1936 * @hide 1937 */ 1938 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1939 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1940 1941 /* 1942 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1943 * flag value. 1944 * @hide 1945 */ 1946 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1947 LAYOUT_DIRECTION_LTR, 1948 LAYOUT_DIRECTION_RTL, 1949 LAYOUT_DIRECTION_INHERIT, 1950 LAYOUT_DIRECTION_LOCALE 1951 }; 1952 1953 /** 1954 * Default horizontal layout direction. 1955 */ 1956 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1957 1958 /** 1959 * Default horizontal layout direction. 1960 * @hide 1961 */ 1962 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1963 1964 /** 1965 * Text direction is inherited thru {@link ViewGroup} 1966 */ 1967 public static final int TEXT_DIRECTION_INHERIT = 0; 1968 1969 /** 1970 * Text direction is using "first strong algorithm". The first strong directional character 1971 * determines the paragraph direction. If there is no strong directional character, the 1972 * paragraph direction is the view's resolved layout direction. 1973 */ 1974 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1975 1976 /** 1977 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1978 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1979 * If there are neither, the paragraph direction is the view's resolved layout direction. 1980 */ 1981 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1982 1983 /** 1984 * Text direction is forced to LTR. 1985 */ 1986 public static final int TEXT_DIRECTION_LTR = 3; 1987 1988 /** 1989 * Text direction is forced to RTL. 1990 */ 1991 public static final int TEXT_DIRECTION_RTL = 4; 1992 1993 /** 1994 * Text direction is coming from the system Locale. 1995 */ 1996 public static final int TEXT_DIRECTION_LOCALE = 5; 1997 1998 /** 1999 * Default text direction is inherited 2000 */ 2001 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2002 2003 /** 2004 * Default resolved text direction 2005 * @hide 2006 */ 2007 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2008 2009 /** 2010 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2011 * @hide 2012 */ 2013 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2014 2015 /** 2016 * Mask for use with private flags indicating bits used for text direction. 2017 * @hide 2018 */ 2019 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2020 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2021 2022 /** 2023 * Array of text direction flags for mapping attribute "textDirection" to correct 2024 * flag value. 2025 * @hide 2026 */ 2027 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2028 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2029 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2030 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2031 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2032 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2033 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2034 }; 2035 2036 /** 2037 * Indicates whether the view text direction has been resolved. 2038 * @hide 2039 */ 2040 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2041 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2042 2043 /** 2044 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2045 * @hide 2046 */ 2047 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2048 2049 /** 2050 * Mask for use with private flags indicating bits used for resolved text direction. 2051 * @hide 2052 */ 2053 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2054 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2055 2056 /** 2057 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2058 * @hide 2059 */ 2060 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2061 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2062 2063 /** @hide */ 2064 @IntDef({ 2065 TEXT_ALIGNMENT_INHERIT, 2066 TEXT_ALIGNMENT_GRAVITY, 2067 TEXT_ALIGNMENT_CENTER, 2068 TEXT_ALIGNMENT_TEXT_START, 2069 TEXT_ALIGNMENT_TEXT_END, 2070 TEXT_ALIGNMENT_VIEW_START, 2071 TEXT_ALIGNMENT_VIEW_END 2072 }) 2073 @Retention(RetentionPolicy.SOURCE) 2074 public @interface TextAlignment {} 2075 2076 /** 2077 * Default text alignment. The text alignment of this View is inherited from its parent. 2078 * Use with {@link #setTextAlignment(int)} 2079 */ 2080 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2081 2082 /** 2083 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2084 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2085 * 2086 * Use with {@link #setTextAlignment(int)} 2087 */ 2088 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2089 2090 /** 2091 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2092 * 2093 * Use with {@link #setTextAlignment(int)} 2094 */ 2095 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2096 2097 /** 2098 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2099 * 2100 * Use with {@link #setTextAlignment(int)} 2101 */ 2102 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2103 2104 /** 2105 * Center the paragraph, e.g. ALIGN_CENTER. 2106 * 2107 * Use with {@link #setTextAlignment(int)} 2108 */ 2109 public static final int TEXT_ALIGNMENT_CENTER = 4; 2110 2111 /** 2112 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2113 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2114 * 2115 * Use with {@link #setTextAlignment(int)} 2116 */ 2117 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2118 2119 /** 2120 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2121 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2122 * 2123 * Use with {@link #setTextAlignment(int)} 2124 */ 2125 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2126 2127 /** 2128 * Default text alignment is inherited 2129 */ 2130 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2131 2132 /** 2133 * Default resolved text alignment 2134 * @hide 2135 */ 2136 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2137 2138 /** 2139 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2140 * @hide 2141 */ 2142 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2143 2144 /** 2145 * Mask for use with private flags indicating bits used for text alignment. 2146 * @hide 2147 */ 2148 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2149 2150 /** 2151 * Array of text direction flags for mapping attribute "textAlignment" to correct 2152 * flag value. 2153 * @hide 2154 */ 2155 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2156 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2157 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2158 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2159 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2160 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2161 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2162 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2163 }; 2164 2165 /** 2166 * Indicates whether the view text alignment has been resolved. 2167 * @hide 2168 */ 2169 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2170 2171 /** 2172 * Bit shift to get the resolved text alignment. 2173 * @hide 2174 */ 2175 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2176 2177 /** 2178 * Mask for use with private flags indicating bits used for text alignment. 2179 * @hide 2180 */ 2181 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2182 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2183 2184 /** 2185 * Indicates whether if the view text alignment has been resolved to gravity 2186 */ 2187 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2188 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2189 2190 // Accessiblity constants for mPrivateFlags2 2191 2192 /** 2193 * Shift for the bits in {@link #mPrivateFlags2} related to the 2194 * "importantForAccessibility" attribute. 2195 */ 2196 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2197 2198 /** 2199 * Automatically determine whether a view is important for accessibility. 2200 */ 2201 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2202 2203 /** 2204 * The view is important for accessibility. 2205 */ 2206 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2207 2208 /** 2209 * The view is not important for accessibility. 2210 */ 2211 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2212 2213 /** 2214 * The view is not important for accessibility, nor are any of its 2215 * descendant views. 2216 */ 2217 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2218 2219 /** 2220 * The default whether the view is important for accessibility. 2221 */ 2222 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2223 2224 /** 2225 * Mask for obtainig the bits which specify how to determine 2226 * whether a view is important for accessibility. 2227 */ 2228 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2229 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2230 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2231 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2232 2233 /** 2234 * Shift for the bits in {@link #mPrivateFlags2} related to the 2235 * "accessibilityLiveRegion" attribute. 2236 */ 2237 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2238 2239 /** 2240 * Live region mode specifying that accessibility services should not 2241 * automatically announce changes to this view. This is the default live 2242 * region mode for most views. 2243 * <p> 2244 * Use with {@link #setAccessibilityLiveRegion(int)}. 2245 */ 2246 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2247 2248 /** 2249 * Live region mode specifying that accessibility services should announce 2250 * changes to this view. 2251 * <p> 2252 * Use with {@link #setAccessibilityLiveRegion(int)}. 2253 */ 2254 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2255 2256 /** 2257 * Live region mode specifying that accessibility services should interrupt 2258 * ongoing speech to immediately announce changes to this view. 2259 * <p> 2260 * Use with {@link #setAccessibilityLiveRegion(int)}. 2261 */ 2262 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2263 2264 /** 2265 * The default whether the view is important for accessibility. 2266 */ 2267 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2268 2269 /** 2270 * Mask for obtaining the bits which specify a view's accessibility live 2271 * region mode. 2272 */ 2273 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2274 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2275 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2276 2277 /** 2278 * Flag indicating whether a view has accessibility focus. 2279 */ 2280 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2281 2282 /** 2283 * Flag whether the accessibility state of the subtree rooted at this view changed. 2284 */ 2285 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2286 2287 /** 2288 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2289 * is used to check whether later changes to the view's transform should invalidate the 2290 * view to force the quickReject test to run again. 2291 */ 2292 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2293 2294 /** 2295 * Flag indicating that start/end padding has been resolved into left/right padding 2296 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2297 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2298 * during measurement. In some special cases this is required such as when an adapter-based 2299 * view measures prospective children without attaching them to a window. 2300 */ 2301 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2302 2303 /** 2304 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2305 */ 2306 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2307 2308 /** 2309 * Indicates that the view is tracking some sort of transient state 2310 * that the app should not need to be aware of, but that the framework 2311 * should take special care to preserve. 2312 */ 2313 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2314 2315 /** 2316 * Group of bits indicating that RTL properties resolution is done. 2317 */ 2318 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2319 PFLAG2_TEXT_DIRECTION_RESOLVED | 2320 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2321 PFLAG2_PADDING_RESOLVED | 2322 PFLAG2_DRAWABLE_RESOLVED; 2323 2324 // There are a couple of flags left in mPrivateFlags2 2325 2326 /* End of masks for mPrivateFlags2 */ 2327 2328 /** 2329 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2330 * 2331 * |-------|-------|-------|-------| 2332 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2333 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2334 * 1 PFLAG3_IS_LAID_OUT 2335 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2336 * 1 PFLAG3_CALLED_SUPER 2337 * 1 PFLAG3_PROJECT_BACKGROUND 2338 * |-------|-------|-------|-------| 2339 */ 2340 2341 /** 2342 * Flag indicating that view has a transform animation set on it. This is used to track whether 2343 * an animation is cleared between successive frames, in order to tell the associated 2344 * DisplayList to clear its animation matrix. 2345 */ 2346 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2347 2348 /** 2349 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2350 * animation is cleared between successive frames, in order to tell the associated 2351 * DisplayList to restore its alpha value. 2352 */ 2353 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2354 2355 /** 2356 * Flag indicating that the view has been through at least one layout since it 2357 * was last attached to a window. 2358 */ 2359 static final int PFLAG3_IS_LAID_OUT = 0x4; 2360 2361 /** 2362 * Flag indicating that a call to measure() was skipped and should be done 2363 * instead when layout() is invoked. 2364 */ 2365 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2366 2367 /** 2368 * Flag indicating that an overridden method correctly called down to 2369 * the superclass implementation as required by the API spec. 2370 */ 2371 static final int PFLAG3_CALLED_SUPER = 0x10; 2372 2373 /** 2374 * Flag indicating that the background of this view will be drawn into a 2375 * display list and projected onto the closest parent projection surface. 2376 */ 2377 static final int PFLAG3_PROJECT_BACKGROUND = 0x20; 2378 2379 /* End of masks for mPrivateFlags3 */ 2380 2381 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2382 2383 /** 2384 * Always allow a user to over-scroll this view, provided it is a 2385 * view that can scroll. 2386 * 2387 * @see #getOverScrollMode() 2388 * @see #setOverScrollMode(int) 2389 */ 2390 public static final int OVER_SCROLL_ALWAYS = 0; 2391 2392 /** 2393 * Allow a user to over-scroll this view only if the content is large 2394 * enough to meaningfully scroll, provided it is a view that can scroll. 2395 * 2396 * @see #getOverScrollMode() 2397 * @see #setOverScrollMode(int) 2398 */ 2399 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2400 2401 /** 2402 * Never allow a user to over-scroll this view. 2403 * 2404 * @see #getOverScrollMode() 2405 * @see #setOverScrollMode(int) 2406 */ 2407 public static final int OVER_SCROLL_NEVER = 2; 2408 2409 /** 2410 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2411 * requested the system UI (status bar) to be visible (the default). 2412 * 2413 * @see #setSystemUiVisibility(int) 2414 */ 2415 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2416 2417 /** 2418 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2419 * system UI to enter an unobtrusive "low profile" mode. 2420 * 2421 * <p>This is for use in games, book readers, video players, or any other 2422 * "immersive" application where the usual system chrome is deemed too distracting. 2423 * 2424 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2425 * 2426 * @see #setSystemUiVisibility(int) 2427 */ 2428 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2429 2430 /** 2431 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2432 * system navigation be temporarily hidden. 2433 * 2434 * <p>This is an even less obtrusive state than that called for by 2435 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2436 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2437 * those to disappear. This is useful (in conjunction with the 2438 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2439 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2440 * window flags) for displaying content using every last pixel on the display. 2441 * 2442 * <p>There is a limitation: because navigation controls are so important, the least user 2443 * interaction will cause them to reappear immediately. When this happens, both 2444 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2445 * so that both elements reappear at the same time. 2446 * 2447 * @see #setSystemUiVisibility(int) 2448 */ 2449 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2450 2451 /** 2452 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2453 * into the normal fullscreen mode so that its content can take over the screen 2454 * while still allowing the user to interact with the application. 2455 * 2456 * <p>This has the same visual effect as 2457 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2458 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2459 * meaning that non-critical screen decorations (such as the status bar) will be 2460 * hidden while the user is in the View's window, focusing the experience on 2461 * that content. Unlike the window flag, if you are using ActionBar in 2462 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2463 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2464 * hide the action bar. 2465 * 2466 * <p>This approach to going fullscreen is best used over the window flag when 2467 * it is a transient state -- that is, the application does this at certain 2468 * points in its user interaction where it wants to allow the user to focus 2469 * on content, but not as a continuous state. For situations where the application 2470 * would like to simply stay full screen the entire time (such as a game that 2471 * wants to take over the screen), the 2472 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2473 * is usually a better approach. The state set here will be removed by the system 2474 * in various situations (such as the user moving to another application) like 2475 * the other system UI states. 2476 * 2477 * <p>When using this flag, the application should provide some easy facility 2478 * for the user to go out of it. A common example would be in an e-book 2479 * reader, where tapping on the screen brings back whatever screen and UI 2480 * decorations that had been hidden while the user was immersed in reading 2481 * the book. 2482 * 2483 * @see #setSystemUiVisibility(int) 2484 */ 2485 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2486 2487 /** 2488 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2489 * flags, we would like a stable view of the content insets given to 2490 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2491 * will always represent the worst case that the application can expect 2492 * as a continuous state. In the stock Android UI this is the space for 2493 * the system bar, nav bar, and status bar, but not more transient elements 2494 * such as an input method. 2495 * 2496 * The stable layout your UI sees is based on the system UI modes you can 2497 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2498 * then you will get a stable layout for changes of the 2499 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2500 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2501 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2502 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2503 * with a stable layout. (Note that you should avoid using 2504 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2505 * 2506 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2507 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2508 * then a hidden status bar will be considered a "stable" state for purposes 2509 * here. This allows your UI to continually hide the status bar, while still 2510 * using the system UI flags to hide the action bar while still retaining 2511 * a stable layout. Note that changing the window fullscreen flag will never 2512 * provide a stable layout for a clean transition. 2513 * 2514 * <p>If you are using ActionBar in 2515 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2516 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2517 * insets it adds to those given to the application. 2518 */ 2519 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2520 2521 /** 2522 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2523 * to be layed out as if it has requested 2524 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2525 * allows it to avoid artifacts when switching in and out of that mode, at 2526 * the expense that some of its user interface may be covered by screen 2527 * decorations when they are shown. You can perform layout of your inner 2528 * UI elements to account for the navigation system UI through the 2529 * {@link #fitSystemWindows(Rect)} method. 2530 */ 2531 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2532 2533 /** 2534 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2535 * to be layed out as if it has requested 2536 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2537 * allows it to avoid artifacts when switching in and out of that mode, at 2538 * the expense that some of its user interface may be covered by screen 2539 * decorations when they are shown. You can perform layout of your inner 2540 * UI elements to account for non-fullscreen system UI through the 2541 * {@link #fitSystemWindows(Rect)} method. 2542 */ 2543 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2544 2545 /** 2546 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2547 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2548 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2549 * user interaction. 2550 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2551 * has an effect when used in combination with that flag.</p> 2552 */ 2553 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2554 2555 /** 2556 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2557 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2558 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2559 * experience while also hiding the system bars. If this flag is not set, 2560 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2561 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2562 * if the user swipes from the top of the screen. 2563 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2564 * system gestures, such as swiping from the top of the screen. These transient system bars 2565 * will overlay app’s content, may have some degree of transparency, and will automatically 2566 * hide after a short timeout. 2567 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2568 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2569 * with one or both of those flags.</p> 2570 */ 2571 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2572 2573 /** 2574 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2575 */ 2576 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2577 2578 /** 2579 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2580 */ 2581 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2582 2583 /** 2584 * @hide 2585 * 2586 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2587 * out of the public fields to keep the undefined bits out of the developer's way. 2588 * 2589 * Flag to make the status bar not expandable. Unless you also 2590 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2591 */ 2592 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2593 2594 /** 2595 * @hide 2596 * 2597 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2598 * out of the public fields to keep the undefined bits out of the developer's way. 2599 * 2600 * Flag to hide notification icons and scrolling ticker text. 2601 */ 2602 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2603 2604 /** 2605 * @hide 2606 * 2607 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2608 * out of the public fields to keep the undefined bits out of the developer's way. 2609 * 2610 * Flag to disable incoming notification alerts. This will not block 2611 * icons, but it will block sound, vibrating and other visual or aural notifications. 2612 */ 2613 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2614 2615 /** 2616 * @hide 2617 * 2618 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2619 * out of the public fields to keep the undefined bits out of the developer's way. 2620 * 2621 * Flag to hide only the scrolling ticker. Note that 2622 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2623 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2624 */ 2625 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2626 2627 /** 2628 * @hide 2629 * 2630 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2631 * out of the public fields to keep the undefined bits out of the developer's way. 2632 * 2633 * Flag to hide the center system info area. 2634 */ 2635 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2636 2637 /** 2638 * @hide 2639 * 2640 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2641 * out of the public fields to keep the undefined bits out of the developer's way. 2642 * 2643 * Flag to hide only the home button. Don't use this 2644 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2645 */ 2646 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2647 2648 /** 2649 * @hide 2650 * 2651 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2652 * out of the public fields to keep the undefined bits out of the developer's way. 2653 * 2654 * Flag to hide only the back button. Don't use this 2655 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2656 */ 2657 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2658 2659 /** 2660 * @hide 2661 * 2662 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2663 * out of the public fields to keep the undefined bits out of the developer's way. 2664 * 2665 * Flag to hide only the clock. You might use this if your activity has 2666 * its own clock making the status bar's clock redundant. 2667 */ 2668 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2669 2670 /** 2671 * @hide 2672 * 2673 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2674 * out of the public fields to keep the undefined bits out of the developer's way. 2675 * 2676 * Flag to hide only the recent apps button. Don't use this 2677 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2678 */ 2679 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2680 2681 /** 2682 * @hide 2683 * 2684 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2685 * out of the public fields to keep the undefined bits out of the developer's way. 2686 * 2687 * Flag to disable the global search gesture. Don't use this 2688 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2689 */ 2690 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2691 2692 /** 2693 * @hide 2694 * 2695 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2696 * out of the public fields to keep the undefined bits out of the developer's way. 2697 * 2698 * Flag to specify that the status bar is displayed in transient mode. 2699 */ 2700 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2701 2702 /** 2703 * @hide 2704 * 2705 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2706 * out of the public fields to keep the undefined bits out of the developer's way. 2707 * 2708 * Flag to specify that the navigation bar is displayed in transient mode. 2709 */ 2710 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2711 2712 /** 2713 * @hide 2714 * 2715 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2716 * out of the public fields to keep the undefined bits out of the developer's way. 2717 * 2718 * Flag to specify that the hidden status bar would like to be shown. 2719 */ 2720 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2721 2722 /** 2723 * @hide 2724 * 2725 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2726 * out of the public fields to keep the undefined bits out of the developer's way. 2727 * 2728 * Flag to specify that the hidden navigation bar would like to be shown. 2729 */ 2730 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2731 2732 /** 2733 * @hide 2734 * 2735 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2736 * out of the public fields to keep the undefined bits out of the developer's way. 2737 * 2738 * Flag to specify that the status bar is displayed in translucent mode. 2739 */ 2740 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2741 2742 /** 2743 * @hide 2744 * 2745 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2746 * out of the public fields to keep the undefined bits out of the developer's way. 2747 * 2748 * Flag to specify that the navigation bar is displayed in translucent mode. 2749 */ 2750 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2751 2752 /** 2753 * @hide 2754 */ 2755 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2756 2757 /** 2758 * These are the system UI flags that can be cleared by events outside 2759 * of an application. Currently this is just the ability to tap on the 2760 * screen while hiding the navigation bar to have it return. 2761 * @hide 2762 */ 2763 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2764 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2765 | SYSTEM_UI_FLAG_FULLSCREEN; 2766 2767 /** 2768 * Flags that can impact the layout in relation to system UI. 2769 */ 2770 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2771 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2772 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2773 2774 /** @hide */ 2775 @IntDef(flag = true, 2776 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2777 @Retention(RetentionPolicy.SOURCE) 2778 public @interface FindViewFlags {} 2779 2780 /** 2781 * Find views that render the specified text. 2782 * 2783 * @see #findViewsWithText(ArrayList, CharSequence, int) 2784 */ 2785 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2786 2787 /** 2788 * Find find views that contain the specified content description. 2789 * 2790 * @see #findViewsWithText(ArrayList, CharSequence, int) 2791 */ 2792 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2793 2794 /** 2795 * Find views that contain {@link AccessibilityNodeProvider}. Such 2796 * a View is a root of virtual view hierarchy and may contain the searched 2797 * text. If this flag is set Views with providers are automatically 2798 * added and it is a responsibility of the client to call the APIs of 2799 * the provider to determine whether the virtual tree rooted at this View 2800 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2801 * representing the virtual views with this text. 2802 * 2803 * @see #findViewsWithText(ArrayList, CharSequence, int) 2804 * 2805 * @hide 2806 */ 2807 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2808 2809 /** 2810 * The undefined cursor position. 2811 * 2812 * @hide 2813 */ 2814 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2815 2816 /** 2817 * Indicates that the screen has changed state and is now off. 2818 * 2819 * @see #onScreenStateChanged(int) 2820 */ 2821 public static final int SCREEN_STATE_OFF = 0x0; 2822 2823 /** 2824 * Indicates that the screen has changed state and is now on. 2825 * 2826 * @see #onScreenStateChanged(int) 2827 */ 2828 public static final int SCREEN_STATE_ON = 0x1; 2829 2830 /** 2831 * Controls the over-scroll mode for this view. 2832 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2833 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2834 * and {@link #OVER_SCROLL_NEVER}. 2835 */ 2836 private int mOverScrollMode; 2837 2838 /** 2839 * The parent this view is attached to. 2840 * {@hide} 2841 * 2842 * @see #getParent() 2843 */ 2844 protected ViewParent mParent; 2845 2846 /** 2847 * {@hide} 2848 */ 2849 AttachInfo mAttachInfo; 2850 2851 /** 2852 * {@hide} 2853 */ 2854 @ViewDebug.ExportedProperty(flagMapping = { 2855 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2856 name = "FORCE_LAYOUT"), 2857 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2858 name = "LAYOUT_REQUIRED"), 2859 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2860 name = "DRAWING_CACHE_INVALID", outputIf = false), 2861 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2862 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2863 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2864 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2865 }) 2866 int mPrivateFlags; 2867 int mPrivateFlags2; 2868 int mPrivateFlags3; 2869 2870 /** 2871 * This view's request for the visibility of the status bar. 2872 * @hide 2873 */ 2874 @ViewDebug.ExportedProperty(flagMapping = { 2875 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2876 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2877 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2878 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2879 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2880 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2881 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2882 equals = SYSTEM_UI_FLAG_VISIBLE, 2883 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2884 }) 2885 int mSystemUiVisibility; 2886 2887 /** 2888 * Reference count for transient state. 2889 * @see #setHasTransientState(boolean) 2890 */ 2891 int mTransientStateCount = 0; 2892 2893 /** 2894 * Count of how many windows this view has been attached to. 2895 */ 2896 int mWindowAttachCount; 2897 2898 /** 2899 * The layout parameters associated with this view and used by the parent 2900 * {@link android.view.ViewGroup} to determine how this view should be 2901 * laid out. 2902 * {@hide} 2903 */ 2904 protected ViewGroup.LayoutParams mLayoutParams; 2905 2906 /** 2907 * The view flags hold various views states. 2908 * {@hide} 2909 */ 2910 @ViewDebug.ExportedProperty 2911 int mViewFlags; 2912 2913 static class TransformationInfo { 2914 /** 2915 * The transform matrix for the View. This transform is calculated internally 2916 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2917 * is used by default. Do *not* use this variable directly; instead call 2918 * getMatrix(), which will automatically recalculate the matrix if necessary 2919 * to get the correct matrix based on the latest rotation and scale properties. 2920 */ 2921 private final Matrix mMatrix = new Matrix(); 2922 2923 /** 2924 * The transform matrix for the View. This transform is calculated internally 2925 * based on the rotation, scaleX, and scaleY properties. The identity matrix 2926 * is used by default. Do *not* use this variable directly; instead call 2927 * getInverseMatrix(), which will automatically recalculate the matrix if necessary 2928 * to get the correct matrix based on the latest rotation and scale properties. 2929 */ 2930 private Matrix mInverseMatrix; 2931 2932 /** 2933 * An internal variable that tracks whether we need to recalculate the 2934 * transform matrix, based on whether the rotation or scaleX/Y properties 2935 * have changed since the matrix was last calculated. 2936 */ 2937 boolean mMatrixDirty = false; 2938 2939 /** 2940 * An internal variable that tracks whether we need to recalculate the 2941 * transform matrix, based on whether the rotation or scaleX/Y properties 2942 * have changed since the matrix was last calculated. 2943 */ 2944 private boolean mInverseMatrixDirty = true; 2945 2946 /** 2947 * A variable that tracks whether we need to recalculate the 2948 * transform matrix, based on whether the rotation or scaleX/Y properties 2949 * have changed since the matrix was last calculated. This variable 2950 * is only valid after a call to updateMatrix() or to a function that 2951 * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). 2952 */ 2953 private boolean mMatrixIsIdentity = true; 2954 2955 /** 2956 * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. 2957 */ 2958 private Camera mCamera = null; 2959 2960 /** 2961 * This matrix is used when computing the matrix for 3D rotations. 2962 */ 2963 private Matrix matrix3D = null; 2964 2965 /** 2966 * These prev values are used to recalculate a centered pivot point when necessary. The 2967 * pivot point is only used in matrix operations (when rotation, scale, or translation are 2968 * set), so thes values are only used then as well. 2969 */ 2970 private int mPrevWidth = -1; 2971 private int mPrevHeight = -1; 2972 2973 /** 2974 * The degrees rotation around the vertical axis through the pivot point. 2975 */ 2976 @ViewDebug.ExportedProperty 2977 float mRotationY = 0f; 2978 2979 /** 2980 * The degrees rotation around the horizontal axis through the pivot point. 2981 */ 2982 @ViewDebug.ExportedProperty 2983 float mRotationX = 0f; 2984 2985 /** 2986 * The degrees rotation around the pivot point. 2987 */ 2988 @ViewDebug.ExportedProperty 2989 float mRotation = 0f; 2990 2991 /** 2992 * The amount of translation of the object away from its left property (post-layout). 2993 */ 2994 @ViewDebug.ExportedProperty 2995 float mTranslationX = 0f; 2996 2997 /** 2998 * The amount of translation of the object away from its top property (post-layout). 2999 */ 3000 @ViewDebug.ExportedProperty 3001 float mTranslationY = 0f; 3002 3003 @ViewDebug.ExportedProperty 3004 float mTranslationZ = 0f; 3005 3006 /** 3007 * The amount of scale in the x direction around the pivot point. A 3008 * value of 1 means no scaling is applied. 3009 */ 3010 @ViewDebug.ExportedProperty 3011 float mScaleX = 1f; 3012 3013 /** 3014 * The amount of scale in the y direction around the pivot point. A 3015 * value of 1 means no scaling is applied. 3016 */ 3017 @ViewDebug.ExportedProperty 3018 float mScaleY = 1f; 3019 3020 /** 3021 * The x location of the point around which the view is rotated and scaled. 3022 */ 3023 @ViewDebug.ExportedProperty 3024 float mPivotX = 0f; 3025 3026 /** 3027 * The y location of the point around which the view is rotated and scaled. 3028 */ 3029 @ViewDebug.ExportedProperty 3030 float mPivotY = 0f; 3031 3032 /** 3033 * The opacity of the View. This is a value from 0 to 1, where 0 means 3034 * completely transparent and 1 means completely opaque. 3035 */ 3036 @ViewDebug.ExportedProperty 3037 float mAlpha = 1f; 3038 3039 /** 3040 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3041 * property only used by transitions, which is composited with the other alpha 3042 * values to calculate the final visual alpha value. 3043 */ 3044 float mTransitionAlpha = 1f; 3045 } 3046 3047 TransformationInfo mTransformationInfo; 3048 3049 /** 3050 * Current clip bounds. to which all drawing of this view are constrained. 3051 */ 3052 private Rect mClipBounds = null; 3053 3054 private boolean mLastIsOpaque; 3055 3056 /** 3057 * Convenience value to check for float values that are close enough to zero to be considered 3058 * zero. 3059 */ 3060 private static final float NONZERO_EPSILON = .001f; 3061 3062 /** 3063 * The distance in pixels from the left edge of this view's parent 3064 * to the left edge of this view. 3065 * {@hide} 3066 */ 3067 @ViewDebug.ExportedProperty(category = "layout") 3068 protected int mLeft; 3069 /** 3070 * The distance in pixels from the left edge of this view's parent 3071 * to the right edge of this view. 3072 * {@hide} 3073 */ 3074 @ViewDebug.ExportedProperty(category = "layout") 3075 protected int mRight; 3076 /** 3077 * The distance in pixels from the top edge of this view's parent 3078 * to the top edge of this view. 3079 * {@hide} 3080 */ 3081 @ViewDebug.ExportedProperty(category = "layout") 3082 protected int mTop; 3083 /** 3084 * The distance in pixels from the top edge of this view's parent 3085 * to the bottom edge of this view. 3086 * {@hide} 3087 */ 3088 @ViewDebug.ExportedProperty(category = "layout") 3089 protected int mBottom; 3090 3091 /** 3092 * The offset, in pixels, by which the content of this view is scrolled 3093 * horizontally. 3094 * {@hide} 3095 */ 3096 @ViewDebug.ExportedProperty(category = "scrolling") 3097 protected int mScrollX; 3098 /** 3099 * The offset, in pixels, by which the content of this view is scrolled 3100 * vertically. 3101 * {@hide} 3102 */ 3103 @ViewDebug.ExportedProperty(category = "scrolling") 3104 protected int mScrollY; 3105 3106 /** 3107 * The left padding in pixels, that is the distance in pixels between the 3108 * left edge of this view and the left edge of its content. 3109 * {@hide} 3110 */ 3111 @ViewDebug.ExportedProperty(category = "padding") 3112 protected int mPaddingLeft = 0; 3113 /** 3114 * The right padding in pixels, that is the distance in pixels between the 3115 * right edge of this view and the right edge of its content. 3116 * {@hide} 3117 */ 3118 @ViewDebug.ExportedProperty(category = "padding") 3119 protected int mPaddingRight = 0; 3120 /** 3121 * The top padding in pixels, that is the distance in pixels between the 3122 * top edge of this view and the top edge of its content. 3123 * {@hide} 3124 */ 3125 @ViewDebug.ExportedProperty(category = "padding") 3126 protected int mPaddingTop; 3127 /** 3128 * The bottom padding in pixels, that is the distance in pixels between the 3129 * bottom edge of this view and the bottom edge of its content. 3130 * {@hide} 3131 */ 3132 @ViewDebug.ExportedProperty(category = "padding") 3133 protected int mPaddingBottom; 3134 3135 /** 3136 * The layout insets in pixels, that is the distance in pixels between the 3137 * visible edges of this view its bounds. 3138 */ 3139 private Insets mLayoutInsets; 3140 3141 /** 3142 * Briefly describes the view and is primarily used for accessibility support. 3143 */ 3144 private CharSequence mContentDescription; 3145 3146 /** 3147 * Specifies the id of a view for which this view serves as a label for 3148 * accessibility purposes. 3149 */ 3150 private int mLabelForId = View.NO_ID; 3151 3152 /** 3153 * Predicate for matching labeled view id with its label for 3154 * accessibility purposes. 3155 */ 3156 private MatchLabelForPredicate mMatchLabelForPredicate; 3157 3158 /** 3159 * Predicate for matching a view by its id. 3160 */ 3161 private MatchIdPredicate mMatchIdPredicate; 3162 3163 /** 3164 * Cache the paddingRight set by the user to append to the scrollbar's size. 3165 * 3166 * @hide 3167 */ 3168 @ViewDebug.ExportedProperty(category = "padding") 3169 protected int mUserPaddingRight; 3170 3171 /** 3172 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3173 * 3174 * @hide 3175 */ 3176 @ViewDebug.ExportedProperty(category = "padding") 3177 protected int mUserPaddingBottom; 3178 3179 /** 3180 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3181 * 3182 * @hide 3183 */ 3184 @ViewDebug.ExportedProperty(category = "padding") 3185 protected int mUserPaddingLeft; 3186 3187 /** 3188 * Cache the paddingStart set by the user to append to the scrollbar's size. 3189 * 3190 */ 3191 @ViewDebug.ExportedProperty(category = "padding") 3192 int mUserPaddingStart; 3193 3194 /** 3195 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3196 * 3197 */ 3198 @ViewDebug.ExportedProperty(category = "padding") 3199 int mUserPaddingEnd; 3200 3201 /** 3202 * Cache initial left padding. 3203 * 3204 * @hide 3205 */ 3206 int mUserPaddingLeftInitial; 3207 3208 /** 3209 * Cache initial right padding. 3210 * 3211 * @hide 3212 */ 3213 int mUserPaddingRightInitial; 3214 3215 /** 3216 * Default undefined padding 3217 */ 3218 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3219 3220 /** 3221 * Cache if a left padding has been defined 3222 */ 3223 private boolean mLeftPaddingDefined = false; 3224 3225 /** 3226 * Cache if a right padding has been defined 3227 */ 3228 private boolean mRightPaddingDefined = false; 3229 3230 /** 3231 * @hide 3232 */ 3233 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3234 /** 3235 * @hide 3236 */ 3237 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3238 3239 private LongSparseLongArray mMeasureCache; 3240 3241 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3242 private Drawable mBackground; 3243 3244 /** 3245 * Display list used for backgrounds. 3246 * <p> 3247 * When non-null and valid, this is expected to contain an up-to-date copy 3248 * of the background drawable. It is cleared on temporary detach and reset 3249 * on cleanup. 3250 */ 3251 private DisplayList mBackgroundDisplayList; 3252 3253 private int mBackgroundResource; 3254 private boolean mBackgroundSizeChanged; 3255 3256 static class ListenerInfo { 3257 /** 3258 * Listener used to dispatch focus change events. 3259 * This field should be made private, so it is hidden from the SDK. 3260 * {@hide} 3261 */ 3262 protected OnFocusChangeListener mOnFocusChangeListener; 3263 3264 /** 3265 * Listeners for layout change events. 3266 */ 3267 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3268 3269 /** 3270 * Listeners for attach events. 3271 */ 3272 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3273 3274 /** 3275 * Listener used to dispatch click events. 3276 * This field should be made private, so it is hidden from the SDK. 3277 * {@hide} 3278 */ 3279 public OnClickListener mOnClickListener; 3280 3281 /** 3282 * Listener used to dispatch long click events. 3283 * This field should be made private, so it is hidden from the SDK. 3284 * {@hide} 3285 */ 3286 protected OnLongClickListener mOnLongClickListener; 3287 3288 /** 3289 * Listener used to build the context menu. 3290 * This field should be made private, so it is hidden from the SDK. 3291 * {@hide} 3292 */ 3293 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3294 3295 private OnKeyListener mOnKeyListener; 3296 3297 private OnTouchListener mOnTouchListener; 3298 3299 private OnHoverListener mOnHoverListener; 3300 3301 private OnGenericMotionListener mOnGenericMotionListener; 3302 3303 private OnDragListener mOnDragListener; 3304 3305 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3306 } 3307 3308 ListenerInfo mListenerInfo; 3309 3310 /** 3311 * The application environment this view lives in. 3312 * This field should be made private, so it is hidden from the SDK. 3313 * {@hide} 3314 */ 3315 protected Context mContext; 3316 3317 private final Resources mResources; 3318 3319 private ScrollabilityCache mScrollCache; 3320 3321 private int[] mDrawableState = null; 3322 3323 /** 3324 * Stores the outline of the view, passed down to the DisplayList level for shadow shape. 3325 */ 3326 private Path mOutline; 3327 3328 /** 3329 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3330 * the user may specify which view to go to next. 3331 */ 3332 private int mNextFocusLeftId = View.NO_ID; 3333 3334 /** 3335 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3336 * the user may specify which view to go to next. 3337 */ 3338 private int mNextFocusRightId = View.NO_ID; 3339 3340 /** 3341 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3342 * the user may specify which view to go to next. 3343 */ 3344 private int mNextFocusUpId = View.NO_ID; 3345 3346 /** 3347 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3348 * the user may specify which view to go to next. 3349 */ 3350 private int mNextFocusDownId = View.NO_ID; 3351 3352 /** 3353 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3354 * the user may specify which view to go to next. 3355 */ 3356 int mNextFocusForwardId = View.NO_ID; 3357 3358 private CheckForLongPress mPendingCheckForLongPress; 3359 private CheckForTap mPendingCheckForTap = null; 3360 private PerformClick mPerformClick; 3361 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3362 3363 private UnsetPressedState mUnsetPressedState; 3364 3365 /** 3366 * Whether the long press's action has been invoked. The tap's action is invoked on the 3367 * up event while a long press is invoked as soon as the long press duration is reached, so 3368 * a long press could be performed before the tap is checked, in which case the tap's action 3369 * should not be invoked. 3370 */ 3371 private boolean mHasPerformedLongPress; 3372 3373 /** 3374 * The minimum height of the view. We'll try our best to have the height 3375 * of this view to at least this amount. 3376 */ 3377 @ViewDebug.ExportedProperty(category = "measurement") 3378 private int mMinHeight; 3379 3380 /** 3381 * The minimum width of the view. We'll try our best to have the width 3382 * of this view to at least this amount. 3383 */ 3384 @ViewDebug.ExportedProperty(category = "measurement") 3385 private int mMinWidth; 3386 3387 /** 3388 * The delegate to handle touch events that are physically in this view 3389 * but should be handled by another view. 3390 */ 3391 private TouchDelegate mTouchDelegate = null; 3392 3393 /** 3394 * Solid color to use as a background when creating the drawing cache. Enables 3395 * the cache to use 16 bit bitmaps instead of 32 bit. 3396 */ 3397 private int mDrawingCacheBackgroundColor = 0; 3398 3399 /** 3400 * Special tree observer used when mAttachInfo is null. 3401 */ 3402 private ViewTreeObserver mFloatingTreeObserver; 3403 3404 /** 3405 * Cache the touch slop from the context that created the view. 3406 */ 3407 private int mTouchSlop; 3408 3409 /** 3410 * Object that handles automatic animation of view properties. 3411 */ 3412 private ViewPropertyAnimator mAnimator = null; 3413 3414 /** 3415 * Flag indicating that a drag can cross window boundaries. When 3416 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3417 * with this flag set, all visible applications will be able to participate 3418 * in the drag operation and receive the dragged content. 3419 * 3420 * @hide 3421 */ 3422 public static final int DRAG_FLAG_GLOBAL = 1; 3423 3424 /** 3425 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3426 */ 3427 private float mVerticalScrollFactor; 3428 3429 /** 3430 * Position of the vertical scroll bar. 3431 */ 3432 private int mVerticalScrollbarPosition; 3433 3434 /** 3435 * Position the scroll bar at the default position as determined by the system. 3436 */ 3437 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3438 3439 /** 3440 * Position the scroll bar along the left edge. 3441 */ 3442 public static final int SCROLLBAR_POSITION_LEFT = 1; 3443 3444 /** 3445 * Position the scroll bar along the right edge. 3446 */ 3447 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3448 3449 /** 3450 * Indicates that the view does not have a layer. 3451 * 3452 * @see #getLayerType() 3453 * @see #setLayerType(int, android.graphics.Paint) 3454 * @see #LAYER_TYPE_SOFTWARE 3455 * @see #LAYER_TYPE_HARDWARE 3456 */ 3457 public static final int LAYER_TYPE_NONE = 0; 3458 3459 /** 3460 * <p>Indicates that the view has a software layer. A software layer is backed 3461 * by a bitmap and causes the view to be rendered using Android's software 3462 * rendering pipeline, even if hardware acceleration is enabled.</p> 3463 * 3464 * <p>Software layers have various usages:</p> 3465 * <p>When the application is not using hardware acceleration, a software layer 3466 * is useful to apply a specific color filter and/or blending mode and/or 3467 * translucency to a view and all its children.</p> 3468 * <p>When the application is using hardware acceleration, a software layer 3469 * is useful to render drawing primitives not supported by the hardware 3470 * accelerated pipeline. It can also be used to cache a complex view tree 3471 * into a texture and reduce the complexity of drawing operations. For instance, 3472 * when animating a complex view tree with a translation, a software layer can 3473 * be used to render the view tree only once.</p> 3474 * <p>Software layers should be avoided when the affected view tree updates 3475 * often. Every update will require to re-render the software layer, which can 3476 * potentially be slow (particularly when hardware acceleration is turned on 3477 * since the layer will have to be uploaded into a hardware texture after every 3478 * update.)</p> 3479 * 3480 * @see #getLayerType() 3481 * @see #setLayerType(int, android.graphics.Paint) 3482 * @see #LAYER_TYPE_NONE 3483 * @see #LAYER_TYPE_HARDWARE 3484 */ 3485 public static final int LAYER_TYPE_SOFTWARE = 1; 3486 3487 /** 3488 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3489 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3490 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3491 * rendering pipeline, but only if hardware acceleration is turned on for the 3492 * view hierarchy. When hardware acceleration is turned off, hardware layers 3493 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3494 * 3495 * <p>A hardware layer is useful to apply a specific color filter and/or 3496 * blending mode and/or translucency to a view and all its children.</p> 3497 * <p>A hardware layer can be used to cache a complex view tree into a 3498 * texture and reduce the complexity of drawing operations. For instance, 3499 * when animating a complex view tree with a translation, a hardware layer can 3500 * be used to render the view tree only once.</p> 3501 * <p>A hardware layer can also be used to increase the rendering quality when 3502 * rotation transformations are applied on a view. It can also be used to 3503 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3504 * 3505 * @see #getLayerType() 3506 * @see #setLayerType(int, android.graphics.Paint) 3507 * @see #LAYER_TYPE_NONE 3508 * @see #LAYER_TYPE_SOFTWARE 3509 */ 3510 public static final int LAYER_TYPE_HARDWARE = 2; 3511 3512 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3513 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3514 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3515 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3516 }) 3517 int mLayerType = LAYER_TYPE_NONE; 3518 Paint mLayerPaint; 3519 Rect mLocalDirtyRect; 3520 private HardwareLayer mHardwareLayer; 3521 3522 /** 3523 * Set to true when drawing cache is enabled and cannot be created. 3524 * 3525 * @hide 3526 */ 3527 public boolean mCachingFailed; 3528 private Bitmap mDrawingCache; 3529 private Bitmap mUnscaledDrawingCache; 3530 3531 /** 3532 * Display list used for the View content. 3533 * <p> 3534 * When non-null and valid, this is expected to contain an up-to-date copy 3535 * of the View content. It is cleared on temporary detach and reset on 3536 * cleanup. 3537 */ 3538 DisplayList mDisplayList; 3539 3540 /** 3541 * Set to true when the view is sending hover accessibility events because it 3542 * is the innermost hovered view. 3543 */ 3544 private boolean mSendingHoverAccessibilityEvents; 3545 3546 /** 3547 * Delegate for injecting accessibility functionality. 3548 */ 3549 AccessibilityDelegate mAccessibilityDelegate; 3550 3551 /** 3552 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3553 * and add/remove objects to/from the overlay directly through the Overlay methods. 3554 */ 3555 ViewOverlay mOverlay; 3556 3557 /** 3558 * Consistency verifier for debugging purposes. 3559 * @hide 3560 */ 3561 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3562 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3563 new InputEventConsistencyVerifier(this, 0) : null; 3564 3565 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3566 3567 /** 3568 * Simple constructor to use when creating a view from code. 3569 * 3570 * @param context The Context the view is running in, through which it can 3571 * access the current theme, resources, etc. 3572 */ 3573 public View(Context context) { 3574 mContext = context; 3575 mResources = context != null ? context.getResources() : null; 3576 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3577 // Set some flags defaults 3578 mPrivateFlags2 = 3579 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3580 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3581 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3582 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3583 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3584 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3585 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3586 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3587 mUserPaddingStart = UNDEFINED_PADDING; 3588 mUserPaddingEnd = UNDEFINED_PADDING; 3589 3590 if (!sCompatibilityDone && context != null) { 3591 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3592 3593 // Older apps may need this compatibility hack for measurement. 3594 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3595 3596 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3597 // of whether a layout was requested on that View. 3598 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3599 3600 sCompatibilityDone = true; 3601 } 3602 } 3603 3604 /** 3605 * Constructor that is called when inflating a view from XML. This is called 3606 * when a view is being constructed from an XML file, supplying attributes 3607 * that were specified in the XML file. This version uses a default style of 3608 * 0, so the only attribute values applied are those in the Context's Theme 3609 * and the given AttributeSet. 3610 * 3611 * <p> 3612 * The method onFinishInflate() will be called after all children have been 3613 * added. 3614 * 3615 * @param context The Context the view is running in, through which it can 3616 * access the current theme, resources, etc. 3617 * @param attrs The attributes of the XML tag that is inflating the view. 3618 * @see #View(Context, AttributeSet, int) 3619 */ 3620 public View(Context context, AttributeSet attrs) { 3621 this(context, attrs, 0); 3622 } 3623 3624 /** 3625 * Perform inflation from XML and apply a class-specific base style from a 3626 * theme attribute. This constructor of View allows subclasses to use their 3627 * own base style when they are inflating. For example, a Button class's 3628 * constructor would call this version of the super class constructor and 3629 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3630 * allows the theme's button style to modify all of the base view attributes 3631 * (in particular its background) as well as the Button class's attributes. 3632 * 3633 * @param context The Context the view is running in, through which it can 3634 * access the current theme, resources, etc. 3635 * @param attrs The attributes of the XML tag that is inflating the view. 3636 * @param defStyleAttr An attribute in the current theme that contains a 3637 * reference to a style resource that supplies default values for 3638 * the view. Can be 0 to not look for defaults. 3639 * @see #View(Context, AttributeSet) 3640 */ 3641 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3642 this(context, attrs, defStyleAttr, 0); 3643 } 3644 3645 /** 3646 * Perform inflation from XML and apply a class-specific base style from a 3647 * theme attribute or style resource. This constructor of View allows 3648 * subclasses to use their own base style when they are inflating. 3649 * <p> 3650 * When determining the final value of a particular attribute, there are 3651 * four inputs that come into play: 3652 * <ol> 3653 * <li>Any attribute values in the given AttributeSet. 3654 * <li>The style resource specified in the AttributeSet (named "style"). 3655 * <li>The default style specified by <var>defStyleAttr</var>. 3656 * <li>The default style specified by <var>defStyleRes</var>. 3657 * <li>The base values in this theme. 3658 * </ol> 3659 * <p> 3660 * Each of these inputs is considered in-order, with the first listed taking 3661 * precedence over the following ones. In other words, if in the 3662 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3663 * , then the button's text will <em>always</em> be black, regardless of 3664 * what is specified in any of the styles. 3665 * 3666 * @param context The Context the view is running in, through which it can 3667 * access the current theme, resources, etc. 3668 * @param attrs The attributes of the XML tag that is inflating the view. 3669 * @param defStyleAttr An attribute in the current theme that contains a 3670 * reference to a style resource that supplies default values for 3671 * the view. Can be 0 to not look for defaults. 3672 * @param defStyleRes A resource identifier of a style resource that 3673 * supplies default values for the view, used only if 3674 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3675 * to not look for defaults. 3676 * @see #View(Context, AttributeSet, int) 3677 */ 3678 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3679 this(context); 3680 3681 final TypedArray a = context.obtainStyledAttributes( 3682 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3683 3684 Drawable background = null; 3685 3686 int leftPadding = -1; 3687 int topPadding = -1; 3688 int rightPadding = -1; 3689 int bottomPadding = -1; 3690 int startPadding = UNDEFINED_PADDING; 3691 int endPadding = UNDEFINED_PADDING; 3692 3693 int padding = -1; 3694 3695 int viewFlagValues = 0; 3696 int viewFlagMasks = 0; 3697 3698 boolean setScrollContainer = false; 3699 3700 int x = 0; 3701 int y = 0; 3702 3703 float tx = 0; 3704 float ty = 0; 3705 float tz = 0; 3706 float rotation = 0; 3707 float rotationX = 0; 3708 float rotationY = 0; 3709 float sx = 1f; 3710 float sy = 1f; 3711 boolean transformSet = false; 3712 3713 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3714 int overScrollMode = mOverScrollMode; 3715 boolean initializeScrollbars = false; 3716 3717 boolean startPaddingDefined = false; 3718 boolean endPaddingDefined = false; 3719 boolean leftPaddingDefined = false; 3720 boolean rightPaddingDefined = false; 3721 3722 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3723 3724 final int N = a.getIndexCount(); 3725 for (int i = 0; i < N; i++) { 3726 int attr = a.getIndex(i); 3727 switch (attr) { 3728 case com.android.internal.R.styleable.View_background: 3729 background = a.getDrawable(attr); 3730 break; 3731 case com.android.internal.R.styleable.View_padding: 3732 padding = a.getDimensionPixelSize(attr, -1); 3733 mUserPaddingLeftInitial = padding; 3734 mUserPaddingRightInitial = padding; 3735 leftPaddingDefined = true; 3736 rightPaddingDefined = true; 3737 break; 3738 case com.android.internal.R.styleable.View_paddingLeft: 3739 leftPadding = a.getDimensionPixelSize(attr, -1); 3740 mUserPaddingLeftInitial = leftPadding; 3741 leftPaddingDefined = true; 3742 break; 3743 case com.android.internal.R.styleable.View_paddingTop: 3744 topPadding = a.getDimensionPixelSize(attr, -1); 3745 break; 3746 case com.android.internal.R.styleable.View_paddingRight: 3747 rightPadding = a.getDimensionPixelSize(attr, -1); 3748 mUserPaddingRightInitial = rightPadding; 3749 rightPaddingDefined = true; 3750 break; 3751 case com.android.internal.R.styleable.View_paddingBottom: 3752 bottomPadding = a.getDimensionPixelSize(attr, -1); 3753 break; 3754 case com.android.internal.R.styleable.View_paddingStart: 3755 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3756 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3757 break; 3758 case com.android.internal.R.styleable.View_paddingEnd: 3759 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3760 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3761 break; 3762 case com.android.internal.R.styleable.View_scrollX: 3763 x = a.getDimensionPixelOffset(attr, 0); 3764 break; 3765 case com.android.internal.R.styleable.View_scrollY: 3766 y = a.getDimensionPixelOffset(attr, 0); 3767 break; 3768 case com.android.internal.R.styleable.View_alpha: 3769 setAlpha(a.getFloat(attr, 1f)); 3770 break; 3771 case com.android.internal.R.styleable.View_transformPivotX: 3772 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3773 break; 3774 case com.android.internal.R.styleable.View_transformPivotY: 3775 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3776 break; 3777 case com.android.internal.R.styleable.View_translationX: 3778 tx = a.getDimensionPixelOffset(attr, 0); 3779 transformSet = true; 3780 break; 3781 case com.android.internal.R.styleable.View_translationY: 3782 ty = a.getDimensionPixelOffset(attr, 0); 3783 transformSet = true; 3784 break; 3785 case com.android.internal.R.styleable.View_translationZ: 3786 tz = a.getDimensionPixelOffset(attr, 0); 3787 transformSet = true; 3788 break; 3789 case com.android.internal.R.styleable.View_rotation: 3790 rotation = a.getFloat(attr, 0); 3791 transformSet = true; 3792 break; 3793 case com.android.internal.R.styleable.View_rotationX: 3794 rotationX = a.getFloat(attr, 0); 3795 transformSet = true; 3796 break; 3797 case com.android.internal.R.styleable.View_rotationY: 3798 rotationY = a.getFloat(attr, 0); 3799 transformSet = true; 3800 break; 3801 case com.android.internal.R.styleable.View_scaleX: 3802 sx = a.getFloat(attr, 1f); 3803 transformSet = true; 3804 break; 3805 case com.android.internal.R.styleable.View_scaleY: 3806 sy = a.getFloat(attr, 1f); 3807 transformSet = true; 3808 break; 3809 case com.android.internal.R.styleable.View_id: 3810 mID = a.getResourceId(attr, NO_ID); 3811 break; 3812 case com.android.internal.R.styleable.View_tag: 3813 mTag = a.getText(attr); 3814 break; 3815 case com.android.internal.R.styleable.View_fitsSystemWindows: 3816 if (a.getBoolean(attr, false)) { 3817 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3818 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3819 } 3820 break; 3821 case com.android.internal.R.styleable.View_focusable: 3822 if (a.getBoolean(attr, false)) { 3823 viewFlagValues |= FOCUSABLE; 3824 viewFlagMasks |= FOCUSABLE_MASK; 3825 } 3826 break; 3827 case com.android.internal.R.styleable.View_focusableInTouchMode: 3828 if (a.getBoolean(attr, false)) { 3829 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3830 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3831 } 3832 break; 3833 case com.android.internal.R.styleable.View_clickable: 3834 if (a.getBoolean(attr, false)) { 3835 viewFlagValues |= CLICKABLE; 3836 viewFlagMasks |= CLICKABLE; 3837 } 3838 break; 3839 case com.android.internal.R.styleable.View_longClickable: 3840 if (a.getBoolean(attr, false)) { 3841 viewFlagValues |= LONG_CLICKABLE; 3842 viewFlagMasks |= LONG_CLICKABLE; 3843 } 3844 break; 3845 case com.android.internal.R.styleable.View_saveEnabled: 3846 if (!a.getBoolean(attr, true)) { 3847 viewFlagValues |= SAVE_DISABLED; 3848 viewFlagMasks |= SAVE_DISABLED_MASK; 3849 } 3850 break; 3851 case com.android.internal.R.styleable.View_duplicateParentState: 3852 if (a.getBoolean(attr, false)) { 3853 viewFlagValues |= DUPLICATE_PARENT_STATE; 3854 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3855 } 3856 break; 3857 case com.android.internal.R.styleable.View_visibility: 3858 final int visibility = a.getInt(attr, 0); 3859 if (visibility != 0) { 3860 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3861 viewFlagMasks |= VISIBILITY_MASK; 3862 } 3863 break; 3864 case com.android.internal.R.styleable.View_layoutDirection: 3865 // Clear any layout direction flags (included resolved bits) already set 3866 mPrivateFlags2 &= 3867 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3868 // Set the layout direction flags depending on the value of the attribute 3869 final int layoutDirection = a.getInt(attr, -1); 3870 final int value = (layoutDirection != -1) ? 3871 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3872 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3873 break; 3874 case com.android.internal.R.styleable.View_drawingCacheQuality: 3875 final int cacheQuality = a.getInt(attr, 0); 3876 if (cacheQuality != 0) { 3877 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3878 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3879 } 3880 break; 3881 case com.android.internal.R.styleable.View_contentDescription: 3882 setContentDescription(a.getString(attr)); 3883 break; 3884 case com.android.internal.R.styleable.View_labelFor: 3885 setLabelFor(a.getResourceId(attr, NO_ID)); 3886 break; 3887 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3888 if (!a.getBoolean(attr, true)) { 3889 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3890 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3891 } 3892 break; 3893 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3894 if (!a.getBoolean(attr, true)) { 3895 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3896 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3897 } 3898 break; 3899 case R.styleable.View_scrollbars: 3900 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3901 if (scrollbars != SCROLLBARS_NONE) { 3902 viewFlagValues |= scrollbars; 3903 viewFlagMasks |= SCROLLBARS_MASK; 3904 initializeScrollbars = true; 3905 } 3906 break; 3907 //noinspection deprecation 3908 case R.styleable.View_fadingEdge: 3909 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3910 // Ignore the attribute starting with ICS 3911 break; 3912 } 3913 // With builds < ICS, fall through and apply fading edges 3914 case R.styleable.View_requiresFadingEdge: 3915 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3916 if (fadingEdge != FADING_EDGE_NONE) { 3917 viewFlagValues |= fadingEdge; 3918 viewFlagMasks |= FADING_EDGE_MASK; 3919 initializeFadingEdge(a); 3920 } 3921 break; 3922 case R.styleable.View_scrollbarStyle: 3923 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3924 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3925 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3926 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3927 } 3928 break; 3929 case R.styleable.View_isScrollContainer: 3930 setScrollContainer = true; 3931 if (a.getBoolean(attr, false)) { 3932 setScrollContainer(true); 3933 } 3934 break; 3935 case com.android.internal.R.styleable.View_keepScreenOn: 3936 if (a.getBoolean(attr, false)) { 3937 viewFlagValues |= KEEP_SCREEN_ON; 3938 viewFlagMasks |= KEEP_SCREEN_ON; 3939 } 3940 break; 3941 case R.styleable.View_filterTouchesWhenObscured: 3942 if (a.getBoolean(attr, false)) { 3943 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3944 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3945 } 3946 break; 3947 case R.styleable.View_nextFocusLeft: 3948 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3949 break; 3950 case R.styleable.View_nextFocusRight: 3951 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3952 break; 3953 case R.styleable.View_nextFocusUp: 3954 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3955 break; 3956 case R.styleable.View_nextFocusDown: 3957 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3958 break; 3959 case R.styleable.View_nextFocusForward: 3960 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3961 break; 3962 case R.styleable.View_minWidth: 3963 mMinWidth = a.getDimensionPixelSize(attr, 0); 3964 break; 3965 case R.styleable.View_minHeight: 3966 mMinHeight = a.getDimensionPixelSize(attr, 0); 3967 break; 3968 case R.styleable.View_onClick: 3969 if (context.isRestricted()) { 3970 throw new IllegalStateException("The android:onClick attribute cannot " 3971 + "be used within a restricted context"); 3972 } 3973 3974 final String handlerName = a.getString(attr); 3975 if (handlerName != null) { 3976 setOnClickListener(new OnClickListener() { 3977 private Method mHandler; 3978 3979 public void onClick(View v) { 3980 if (mHandler == null) { 3981 try { 3982 mHandler = getContext().getClass().getMethod(handlerName, 3983 View.class); 3984 } catch (NoSuchMethodException e) { 3985 int id = getId(); 3986 String idText = id == NO_ID ? "" : " with id '" 3987 + getContext().getResources().getResourceEntryName( 3988 id) + "'"; 3989 throw new IllegalStateException("Could not find a method " + 3990 handlerName + "(View) in the activity " 3991 + getContext().getClass() + " for onClick handler" 3992 + " on view " + View.this.getClass() + idText, e); 3993 } 3994 } 3995 3996 try { 3997 mHandler.invoke(getContext(), View.this); 3998 } catch (IllegalAccessException e) { 3999 throw new IllegalStateException("Could not execute non " 4000 + "public method of the activity", e); 4001 } catch (InvocationTargetException e) { 4002 throw new IllegalStateException("Could not execute " 4003 + "method of the activity", e); 4004 } 4005 } 4006 }); 4007 } 4008 break; 4009 case R.styleable.View_overScrollMode: 4010 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4011 break; 4012 case R.styleable.View_verticalScrollbarPosition: 4013 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4014 break; 4015 case R.styleable.View_layerType: 4016 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4017 break; 4018 case R.styleable.View_textDirection: 4019 // Clear any text direction flag already set 4020 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4021 // Set the text direction flags depending on the value of the attribute 4022 final int textDirection = a.getInt(attr, -1); 4023 if (textDirection != -1) { 4024 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4025 } 4026 break; 4027 case R.styleable.View_textAlignment: 4028 // Clear any text alignment flag already set 4029 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4030 // Set the text alignment flag depending on the value of the attribute 4031 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4032 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4033 break; 4034 case R.styleable.View_importantForAccessibility: 4035 setImportantForAccessibility(a.getInt(attr, 4036 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4037 break; 4038 case R.styleable.View_accessibilityLiveRegion: 4039 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4040 break; 4041 } 4042 } 4043 4044 setOverScrollMode(overScrollMode); 4045 4046 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4047 // the resolved layout direction). Those cached values will be used later during padding 4048 // resolution. 4049 mUserPaddingStart = startPadding; 4050 mUserPaddingEnd = endPadding; 4051 4052 if (background != null) { 4053 setBackground(background); 4054 } 4055 4056 // setBackground above will record that padding is currently provided by the background. 4057 // If we have padding specified via xml, record that here instead and use it. 4058 mLeftPaddingDefined = leftPaddingDefined; 4059 mRightPaddingDefined = rightPaddingDefined; 4060 4061 if (padding >= 0) { 4062 leftPadding = padding; 4063 topPadding = padding; 4064 rightPadding = padding; 4065 bottomPadding = padding; 4066 mUserPaddingLeftInitial = padding; 4067 mUserPaddingRightInitial = padding; 4068 } 4069 4070 if (isRtlCompatibilityMode()) { 4071 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4072 // left / right padding are used if defined (meaning here nothing to do). If they are not 4073 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4074 // start / end and resolve them as left / right (layout direction is not taken into account). 4075 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4076 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4077 // defined. 4078 if (!mLeftPaddingDefined && startPaddingDefined) { 4079 leftPadding = startPadding; 4080 } 4081 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4082 if (!mRightPaddingDefined && endPaddingDefined) { 4083 rightPadding = endPadding; 4084 } 4085 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4086 } else { 4087 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4088 // values defined. Otherwise, left /right values are used. 4089 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4090 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4091 // defined. 4092 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4093 4094 if (mLeftPaddingDefined && !hasRelativePadding) { 4095 mUserPaddingLeftInitial = leftPadding; 4096 } 4097 if (mRightPaddingDefined && !hasRelativePadding) { 4098 mUserPaddingRightInitial = rightPadding; 4099 } 4100 } 4101 4102 internalSetPadding( 4103 mUserPaddingLeftInitial, 4104 topPadding >= 0 ? topPadding : mPaddingTop, 4105 mUserPaddingRightInitial, 4106 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4107 4108 if (viewFlagMasks != 0) { 4109 setFlags(viewFlagValues, viewFlagMasks); 4110 } 4111 4112 if (initializeScrollbars) { 4113 initializeScrollbars(a); 4114 } 4115 4116 a.recycle(); 4117 4118 // Needs to be called after mViewFlags is set 4119 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4120 recomputePadding(); 4121 } 4122 4123 if (x != 0 || y != 0) { 4124 scrollTo(x, y); 4125 } 4126 4127 if (transformSet) { 4128 setTranslationX(tx); 4129 setTranslationY(ty); 4130 setTranslationZ(tz); 4131 setRotation(rotation); 4132 setRotationX(rotationX); 4133 setRotationY(rotationY); 4134 setScaleX(sx); 4135 setScaleY(sy); 4136 } 4137 4138 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4139 setScrollContainer(true); 4140 } 4141 4142 computeOpaqueFlags(); 4143 } 4144 4145 /** 4146 * Non-public constructor for use in testing 4147 */ 4148 View() { 4149 mResources = null; 4150 } 4151 4152 public String toString() { 4153 StringBuilder out = new StringBuilder(128); 4154 out.append(getClass().getName()); 4155 out.append('{'); 4156 out.append(Integer.toHexString(System.identityHashCode(this))); 4157 out.append(' '); 4158 switch (mViewFlags&VISIBILITY_MASK) { 4159 case VISIBLE: out.append('V'); break; 4160 case INVISIBLE: out.append('I'); break; 4161 case GONE: out.append('G'); break; 4162 default: out.append('.'); break; 4163 } 4164 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4165 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4166 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4167 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4168 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4169 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4170 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4171 out.append(' '); 4172 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4173 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4174 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4175 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4176 out.append('p'); 4177 } else { 4178 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4179 } 4180 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4181 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4182 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4183 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4184 out.append(' '); 4185 out.append(mLeft); 4186 out.append(','); 4187 out.append(mTop); 4188 out.append('-'); 4189 out.append(mRight); 4190 out.append(','); 4191 out.append(mBottom); 4192 final int id = getId(); 4193 if (id != NO_ID) { 4194 out.append(" #"); 4195 out.append(Integer.toHexString(id)); 4196 final Resources r = mResources; 4197 if (id != 0 && r != null) { 4198 try { 4199 String pkgname; 4200 switch (id&0xff000000) { 4201 case 0x7f000000: 4202 pkgname="app"; 4203 break; 4204 case 0x01000000: 4205 pkgname="android"; 4206 break; 4207 default: 4208 pkgname = r.getResourcePackageName(id); 4209 break; 4210 } 4211 String typename = r.getResourceTypeName(id); 4212 String entryname = r.getResourceEntryName(id); 4213 out.append(" "); 4214 out.append(pkgname); 4215 out.append(":"); 4216 out.append(typename); 4217 out.append("/"); 4218 out.append(entryname); 4219 } catch (Resources.NotFoundException e) { 4220 } 4221 } 4222 } 4223 out.append("}"); 4224 return out.toString(); 4225 } 4226 4227 /** 4228 * <p> 4229 * Initializes the fading edges from a given set of styled attributes. This 4230 * method should be called by subclasses that need fading edges and when an 4231 * instance of these subclasses is created programmatically rather than 4232 * being inflated from XML. This method is automatically called when the XML 4233 * is inflated. 4234 * </p> 4235 * 4236 * @param a the styled attributes set to initialize the fading edges from 4237 */ 4238 protected void initializeFadingEdge(TypedArray a) { 4239 initScrollCache(); 4240 4241 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4242 R.styleable.View_fadingEdgeLength, 4243 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4244 } 4245 4246 /** 4247 * Returns the size of the vertical faded edges used to indicate that more 4248 * content in this view is visible. 4249 * 4250 * @return The size in pixels of the vertical faded edge or 0 if vertical 4251 * faded edges are not enabled for this view. 4252 * @attr ref android.R.styleable#View_fadingEdgeLength 4253 */ 4254 public int getVerticalFadingEdgeLength() { 4255 if (isVerticalFadingEdgeEnabled()) { 4256 ScrollabilityCache cache = mScrollCache; 4257 if (cache != null) { 4258 return cache.fadingEdgeLength; 4259 } 4260 } 4261 return 0; 4262 } 4263 4264 /** 4265 * Set the size of the faded edge used to indicate that more content in this 4266 * view is available. Will not change whether the fading edge is enabled; use 4267 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4268 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4269 * for the vertical or horizontal fading edges. 4270 * 4271 * @param length The size in pixels of the faded edge used to indicate that more 4272 * content in this view is visible. 4273 */ 4274 public void setFadingEdgeLength(int length) { 4275 initScrollCache(); 4276 mScrollCache.fadingEdgeLength = length; 4277 } 4278 4279 /** 4280 * Returns the size of the horizontal faded edges used to indicate that more 4281 * content in this view is visible. 4282 * 4283 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4284 * faded edges are not enabled for this view. 4285 * @attr ref android.R.styleable#View_fadingEdgeLength 4286 */ 4287 public int getHorizontalFadingEdgeLength() { 4288 if (isHorizontalFadingEdgeEnabled()) { 4289 ScrollabilityCache cache = mScrollCache; 4290 if (cache != null) { 4291 return cache.fadingEdgeLength; 4292 } 4293 } 4294 return 0; 4295 } 4296 4297 /** 4298 * Returns the width of the vertical scrollbar. 4299 * 4300 * @return The width in pixels of the vertical scrollbar or 0 if there 4301 * is no vertical scrollbar. 4302 */ 4303 public int getVerticalScrollbarWidth() { 4304 ScrollabilityCache cache = mScrollCache; 4305 if (cache != null) { 4306 ScrollBarDrawable scrollBar = cache.scrollBar; 4307 if (scrollBar != null) { 4308 int size = scrollBar.getSize(true); 4309 if (size <= 0) { 4310 size = cache.scrollBarSize; 4311 } 4312 return size; 4313 } 4314 return 0; 4315 } 4316 return 0; 4317 } 4318 4319 /** 4320 * Returns the height of the horizontal scrollbar. 4321 * 4322 * @return The height in pixels of the horizontal scrollbar or 0 if 4323 * there is no horizontal scrollbar. 4324 */ 4325 protected int getHorizontalScrollbarHeight() { 4326 ScrollabilityCache cache = mScrollCache; 4327 if (cache != null) { 4328 ScrollBarDrawable scrollBar = cache.scrollBar; 4329 if (scrollBar != null) { 4330 int size = scrollBar.getSize(false); 4331 if (size <= 0) { 4332 size = cache.scrollBarSize; 4333 } 4334 return size; 4335 } 4336 return 0; 4337 } 4338 return 0; 4339 } 4340 4341 /** 4342 * <p> 4343 * Initializes the scrollbars from a given set of styled attributes. This 4344 * method should be called by subclasses that need scrollbars and when an 4345 * instance of these subclasses is created programmatically rather than 4346 * being inflated from XML. This method is automatically called when the XML 4347 * is inflated. 4348 * </p> 4349 * 4350 * @param a the styled attributes set to initialize the scrollbars from 4351 */ 4352 protected void initializeScrollbars(TypedArray a) { 4353 initScrollCache(); 4354 4355 final ScrollabilityCache scrollabilityCache = mScrollCache; 4356 4357 if (scrollabilityCache.scrollBar == null) { 4358 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4359 } 4360 4361 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4362 4363 if (!fadeScrollbars) { 4364 scrollabilityCache.state = ScrollabilityCache.ON; 4365 } 4366 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4367 4368 4369 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4370 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4371 .getScrollBarFadeDuration()); 4372 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4373 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4374 ViewConfiguration.getScrollDefaultDelay()); 4375 4376 4377 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4378 com.android.internal.R.styleable.View_scrollbarSize, 4379 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4380 4381 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4382 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4383 4384 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4385 if (thumb != null) { 4386 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4387 } 4388 4389 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4390 false); 4391 if (alwaysDraw) { 4392 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4393 } 4394 4395 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4396 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4397 4398 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4399 if (thumb != null) { 4400 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4401 } 4402 4403 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4404 false); 4405 if (alwaysDraw) { 4406 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4407 } 4408 4409 // Apply layout direction to the new Drawables if needed 4410 final int layoutDirection = getLayoutDirection(); 4411 if (track != null) { 4412 track.setLayoutDirection(layoutDirection); 4413 } 4414 if (thumb != null) { 4415 thumb.setLayoutDirection(layoutDirection); 4416 } 4417 4418 // Re-apply user/background padding so that scrollbar(s) get added 4419 resolvePadding(); 4420 } 4421 4422 /** 4423 * <p> 4424 * Initalizes the scrollability cache if necessary. 4425 * </p> 4426 */ 4427 private void initScrollCache() { 4428 if (mScrollCache == null) { 4429 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4430 } 4431 } 4432 4433 private ScrollabilityCache getScrollCache() { 4434 initScrollCache(); 4435 return mScrollCache; 4436 } 4437 4438 /** 4439 * Set the position of the vertical scroll bar. Should be one of 4440 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4441 * {@link #SCROLLBAR_POSITION_RIGHT}. 4442 * 4443 * @param position Where the vertical scroll bar should be positioned. 4444 */ 4445 public void setVerticalScrollbarPosition(int position) { 4446 if (mVerticalScrollbarPosition != position) { 4447 mVerticalScrollbarPosition = position; 4448 computeOpaqueFlags(); 4449 resolvePadding(); 4450 } 4451 } 4452 4453 /** 4454 * @return The position where the vertical scroll bar will show, if applicable. 4455 * @see #setVerticalScrollbarPosition(int) 4456 */ 4457 public int getVerticalScrollbarPosition() { 4458 return mVerticalScrollbarPosition; 4459 } 4460 4461 ListenerInfo getListenerInfo() { 4462 if (mListenerInfo != null) { 4463 return mListenerInfo; 4464 } 4465 mListenerInfo = new ListenerInfo(); 4466 return mListenerInfo; 4467 } 4468 4469 /** 4470 * Register a callback to be invoked when focus of this view changed. 4471 * 4472 * @param l The callback that will run. 4473 */ 4474 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4475 getListenerInfo().mOnFocusChangeListener = l; 4476 } 4477 4478 /** 4479 * Add a listener that will be called when the bounds of the view change due to 4480 * layout processing. 4481 * 4482 * @param listener The listener that will be called when layout bounds change. 4483 */ 4484 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4485 ListenerInfo li = getListenerInfo(); 4486 if (li.mOnLayoutChangeListeners == null) { 4487 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4488 } 4489 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4490 li.mOnLayoutChangeListeners.add(listener); 4491 } 4492 } 4493 4494 /** 4495 * Remove a listener for layout changes. 4496 * 4497 * @param listener The listener for layout bounds change. 4498 */ 4499 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4500 ListenerInfo li = mListenerInfo; 4501 if (li == null || li.mOnLayoutChangeListeners == null) { 4502 return; 4503 } 4504 li.mOnLayoutChangeListeners.remove(listener); 4505 } 4506 4507 /** 4508 * Add a listener for attach state changes. 4509 * 4510 * This listener will be called whenever this view is attached or detached 4511 * from a window. Remove the listener using 4512 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4513 * 4514 * @param listener Listener to attach 4515 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4516 */ 4517 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4518 ListenerInfo li = getListenerInfo(); 4519 if (li.mOnAttachStateChangeListeners == null) { 4520 li.mOnAttachStateChangeListeners 4521 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4522 } 4523 li.mOnAttachStateChangeListeners.add(listener); 4524 } 4525 4526 /** 4527 * Remove a listener for attach state changes. The listener will receive no further 4528 * notification of window attach/detach events. 4529 * 4530 * @param listener Listener to remove 4531 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4532 */ 4533 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4534 ListenerInfo li = mListenerInfo; 4535 if (li == null || li.mOnAttachStateChangeListeners == null) { 4536 return; 4537 } 4538 li.mOnAttachStateChangeListeners.remove(listener); 4539 } 4540 4541 /** 4542 * Returns the focus-change callback registered for this view. 4543 * 4544 * @return The callback, or null if one is not registered. 4545 */ 4546 public OnFocusChangeListener getOnFocusChangeListener() { 4547 ListenerInfo li = mListenerInfo; 4548 return li != null ? li.mOnFocusChangeListener : null; 4549 } 4550 4551 /** 4552 * Register a callback to be invoked when this view is clicked. If this view is not 4553 * clickable, it becomes clickable. 4554 * 4555 * @param l The callback that will run 4556 * 4557 * @see #setClickable(boolean) 4558 */ 4559 public void setOnClickListener(OnClickListener l) { 4560 if (!isClickable()) { 4561 setClickable(true); 4562 } 4563 getListenerInfo().mOnClickListener = l; 4564 } 4565 4566 /** 4567 * Return whether this view has an attached OnClickListener. Returns 4568 * true if there is a listener, false if there is none. 4569 */ 4570 public boolean hasOnClickListeners() { 4571 ListenerInfo li = mListenerInfo; 4572 return (li != null && li.mOnClickListener != null); 4573 } 4574 4575 /** 4576 * Register a callback to be invoked when this view is clicked and held. If this view is not 4577 * long clickable, it becomes long clickable. 4578 * 4579 * @param l The callback that will run 4580 * 4581 * @see #setLongClickable(boolean) 4582 */ 4583 public void setOnLongClickListener(OnLongClickListener l) { 4584 if (!isLongClickable()) { 4585 setLongClickable(true); 4586 } 4587 getListenerInfo().mOnLongClickListener = l; 4588 } 4589 4590 /** 4591 * Register a callback to be invoked when the context menu for this view is 4592 * being built. If this view is not long clickable, it becomes long clickable. 4593 * 4594 * @param l The callback that will run 4595 * 4596 */ 4597 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4598 if (!isLongClickable()) { 4599 setLongClickable(true); 4600 } 4601 getListenerInfo().mOnCreateContextMenuListener = l; 4602 } 4603 4604 /** 4605 * Call this view's OnClickListener, if it is defined. Performs all normal 4606 * actions associated with clicking: reporting accessibility event, playing 4607 * a sound, etc. 4608 * 4609 * @return True there was an assigned OnClickListener that was called, false 4610 * otherwise is returned. 4611 */ 4612 public boolean performClick() { 4613 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4614 4615 ListenerInfo li = mListenerInfo; 4616 if (li != null && li.mOnClickListener != null) { 4617 playSoundEffect(SoundEffectConstants.CLICK); 4618 li.mOnClickListener.onClick(this); 4619 return true; 4620 } 4621 4622 return false; 4623 } 4624 4625 /** 4626 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4627 * this only calls the listener, and does not do any associated clicking 4628 * actions like reporting an accessibility event. 4629 * 4630 * @return True there was an assigned OnClickListener that was called, false 4631 * otherwise is returned. 4632 */ 4633 public boolean callOnClick() { 4634 ListenerInfo li = mListenerInfo; 4635 if (li != null && li.mOnClickListener != null) { 4636 li.mOnClickListener.onClick(this); 4637 return true; 4638 } 4639 return false; 4640 } 4641 4642 /** 4643 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4644 * OnLongClickListener did not consume the event. 4645 * 4646 * @return True if one of the above receivers consumed the event, false otherwise. 4647 */ 4648 public boolean performLongClick() { 4649 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4650 4651 boolean handled = false; 4652 ListenerInfo li = mListenerInfo; 4653 if (li != null && li.mOnLongClickListener != null) { 4654 handled = li.mOnLongClickListener.onLongClick(View.this); 4655 } 4656 if (!handled) { 4657 handled = showContextMenu(); 4658 } 4659 if (handled) { 4660 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4661 } 4662 return handled; 4663 } 4664 4665 /** 4666 * Performs button-related actions during a touch down event. 4667 * 4668 * @param event The event. 4669 * @return True if the down was consumed. 4670 * 4671 * @hide 4672 */ 4673 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4674 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4675 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4676 return true; 4677 } 4678 } 4679 return false; 4680 } 4681 4682 /** 4683 * Bring up the context menu for this view. 4684 * 4685 * @return Whether a context menu was displayed. 4686 */ 4687 public boolean showContextMenu() { 4688 return getParent().showContextMenuForChild(this); 4689 } 4690 4691 /** 4692 * Bring up the context menu for this view, referring to the item under the specified point. 4693 * 4694 * @param x The referenced x coordinate. 4695 * @param y The referenced y coordinate. 4696 * @param metaState The keyboard modifiers that were pressed. 4697 * @return Whether a context menu was displayed. 4698 * 4699 * @hide 4700 */ 4701 public boolean showContextMenu(float x, float y, int metaState) { 4702 return showContextMenu(); 4703 } 4704 4705 /** 4706 * Start an action mode. 4707 * 4708 * @param callback Callback that will control the lifecycle of the action mode 4709 * @return The new action mode if it is started, null otherwise 4710 * 4711 * @see ActionMode 4712 */ 4713 public ActionMode startActionMode(ActionMode.Callback callback) { 4714 ViewParent parent = getParent(); 4715 if (parent == null) return null; 4716 return parent.startActionModeForChild(this, callback); 4717 } 4718 4719 /** 4720 * Register a callback to be invoked when a hardware key is pressed in this view. 4721 * Key presses in software input methods will generally not trigger the methods of 4722 * this listener. 4723 * @param l the key listener to attach to this view 4724 */ 4725 public void setOnKeyListener(OnKeyListener l) { 4726 getListenerInfo().mOnKeyListener = l; 4727 } 4728 4729 /** 4730 * Register a callback to be invoked when a touch event is sent to this view. 4731 * @param l the touch listener to attach to this view 4732 */ 4733 public void setOnTouchListener(OnTouchListener l) { 4734 getListenerInfo().mOnTouchListener = l; 4735 } 4736 4737 /** 4738 * Register a callback to be invoked when a generic motion event is sent to this view. 4739 * @param l the generic motion listener to attach to this view 4740 */ 4741 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4742 getListenerInfo().mOnGenericMotionListener = l; 4743 } 4744 4745 /** 4746 * Register a callback to be invoked when a hover event is sent to this view. 4747 * @param l the hover listener to attach to this view 4748 */ 4749 public void setOnHoverListener(OnHoverListener l) { 4750 getListenerInfo().mOnHoverListener = l; 4751 } 4752 4753 /** 4754 * Register a drag event listener callback object for this View. The parameter is 4755 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4756 * View, the system calls the 4757 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4758 * @param l An implementation of {@link android.view.View.OnDragListener}. 4759 */ 4760 public void setOnDragListener(OnDragListener l) { 4761 getListenerInfo().mOnDragListener = l; 4762 } 4763 4764 /** 4765 * Give this view focus. This will cause 4766 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4767 * 4768 * Note: this does not check whether this {@link View} should get focus, it just 4769 * gives it focus no matter what. It should only be called internally by framework 4770 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4771 * 4772 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4773 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4774 * focus moved when requestFocus() is called. It may not always 4775 * apply, in which case use the default View.FOCUS_DOWN. 4776 * @param previouslyFocusedRect The rectangle of the view that had focus 4777 * prior in this View's coordinate system. 4778 */ 4779 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4780 if (DBG) { 4781 System.out.println(this + " requestFocus()"); 4782 } 4783 4784 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4785 mPrivateFlags |= PFLAG_FOCUSED; 4786 4787 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4788 4789 if (mParent != null) { 4790 mParent.requestChildFocus(this, this); 4791 } 4792 4793 if (mAttachInfo != null) { 4794 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4795 } 4796 4797 manageFocusHotspot(true, oldFocus); 4798 onFocusChanged(true, direction, previouslyFocusedRect); 4799 refreshDrawableState(); 4800 } 4801 } 4802 4803 /** 4804 * Forwards focus information to the background drawable, if necessary. When 4805 * the view is gaining focus, <code>v</code> is the previous focus holder. 4806 * When the view is losing focus, <code>v</code> is the next focus holder. 4807 * 4808 * @param focused whether this view is focused 4809 * @param v previous or the next focus holder, or null if none 4810 */ 4811 private void manageFocusHotspot(boolean focused, View v) { 4812 if (mBackground != null && mBackground.supportsHotspots()) { 4813 final Rect r = new Rect(); 4814 if (v != null) { 4815 v.getBoundsOnScreen(r); 4816 final int[] location = new int[2]; 4817 getLocationOnScreen(location); 4818 r.offset(-location[0], -location[1]); 4819 } else { 4820 r.set(mLeft, mTop, mRight, mBottom); 4821 } 4822 4823 final float x = r.exactCenterX(); 4824 final float y = r.exactCenterY(); 4825 mBackground.setHotspot(Drawable.HOTSPOT_FOCUS, x, y); 4826 4827 if (!focused) { 4828 mBackground.removeHotspot(Drawable.HOTSPOT_FOCUS); 4829 } 4830 } 4831 } 4832 4833 /** 4834 * Request that a rectangle of this view be visible on the screen, 4835 * scrolling if necessary just enough. 4836 * 4837 * <p>A View should call this if it maintains some notion of which part 4838 * of its content is interesting. For example, a text editing view 4839 * should call this when its cursor moves. 4840 * 4841 * @param rectangle The rectangle. 4842 * @return Whether any parent scrolled. 4843 */ 4844 public boolean requestRectangleOnScreen(Rect rectangle) { 4845 return requestRectangleOnScreen(rectangle, false); 4846 } 4847 4848 /** 4849 * Request that a rectangle of this view be visible on the screen, 4850 * scrolling if necessary just enough. 4851 * 4852 * <p>A View should call this if it maintains some notion of which part 4853 * of its content is interesting. For example, a text editing view 4854 * should call this when its cursor moves. 4855 * 4856 * <p>When <code>immediate</code> is set to true, scrolling will not be 4857 * animated. 4858 * 4859 * @param rectangle The rectangle. 4860 * @param immediate True to forbid animated scrolling, false otherwise 4861 * @return Whether any parent scrolled. 4862 */ 4863 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4864 if (mParent == null) { 4865 return false; 4866 } 4867 4868 View child = this; 4869 4870 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4871 position.set(rectangle); 4872 4873 ViewParent parent = mParent; 4874 boolean scrolled = false; 4875 while (parent != null) { 4876 rectangle.set((int) position.left, (int) position.top, 4877 (int) position.right, (int) position.bottom); 4878 4879 scrolled |= parent.requestChildRectangleOnScreen(child, 4880 rectangle, immediate); 4881 4882 if (!child.hasIdentityMatrix()) { 4883 child.getMatrix().mapRect(position); 4884 } 4885 4886 position.offset(child.mLeft, child.mTop); 4887 4888 if (!(parent instanceof View)) { 4889 break; 4890 } 4891 4892 View parentView = (View) parent; 4893 4894 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4895 4896 child = parentView; 4897 parent = child.getParent(); 4898 } 4899 4900 return scrolled; 4901 } 4902 4903 /** 4904 * Called when this view wants to give up focus. If focus is cleared 4905 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4906 * <p> 4907 * <strong>Note:</strong> When a View clears focus the framework is trying 4908 * to give focus to the first focusable View from the top. Hence, if this 4909 * View is the first from the top that can take focus, then all callbacks 4910 * related to clearing focus will be invoked after wich the framework will 4911 * give focus to this view. 4912 * </p> 4913 */ 4914 public void clearFocus() { 4915 if (DBG) { 4916 System.out.println(this + " clearFocus()"); 4917 } 4918 4919 clearFocusInternal(null, true, true); 4920 } 4921 4922 /** 4923 * Clears focus from the view, optionally propagating the change up through 4924 * the parent hierarchy and requesting that the root view place new focus. 4925 * 4926 * @param propagate whether to propagate the change up through the parent 4927 * hierarchy 4928 * @param refocus when propagate is true, specifies whether to request the 4929 * root view place new focus 4930 */ 4931 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4932 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4933 mPrivateFlags &= ~PFLAG_FOCUSED; 4934 4935 if (hasFocus()) { 4936 manageFocusHotspot(false, focused); 4937 } 4938 4939 if (propagate && mParent != null) { 4940 mParent.clearChildFocus(this); 4941 } 4942 4943 onFocusChanged(false, 0, null); 4944 4945 refreshDrawableState(); 4946 4947 if (propagate && (!refocus || !rootViewRequestFocus())) { 4948 notifyGlobalFocusCleared(this); 4949 } 4950 } 4951 } 4952 4953 void notifyGlobalFocusCleared(View oldFocus) { 4954 if (oldFocus != null && mAttachInfo != null) { 4955 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4956 } 4957 } 4958 4959 boolean rootViewRequestFocus() { 4960 final View root = getRootView(); 4961 return root != null && root.requestFocus(); 4962 } 4963 4964 /** 4965 * Called internally by the view system when a new view is getting focus. 4966 * This is what clears the old focus. 4967 * <p> 4968 * <b>NOTE:</b> The parent view's focused child must be updated manually 4969 * after calling this method. Otherwise, the view hierarchy may be left in 4970 * an inconstent state. 4971 */ 4972 void unFocus(View focused) { 4973 if (DBG) { 4974 System.out.println(this + " unFocus()"); 4975 } 4976 4977 clearFocusInternal(focused, false, false); 4978 } 4979 4980 /** 4981 * Returns true if this view has focus iteself, or is the ancestor of the 4982 * view that has focus. 4983 * 4984 * @return True if this view has or contains focus, false otherwise. 4985 */ 4986 @ViewDebug.ExportedProperty(category = "focus") 4987 public boolean hasFocus() { 4988 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4989 } 4990 4991 /** 4992 * Returns true if this view is focusable or if it contains a reachable View 4993 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4994 * is a View whose parents do not block descendants focus. 4995 * 4996 * Only {@link #VISIBLE} views are considered focusable. 4997 * 4998 * @return True if the view is focusable or if the view contains a focusable 4999 * View, false otherwise. 5000 * 5001 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5002 */ 5003 public boolean hasFocusable() { 5004 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5005 } 5006 5007 /** 5008 * Called by the view system when the focus state of this view changes. 5009 * When the focus change event is caused by directional navigation, direction 5010 * and previouslyFocusedRect provide insight into where the focus is coming from. 5011 * When overriding, be sure to call up through to the super class so that 5012 * the standard focus handling will occur. 5013 * 5014 * @param gainFocus True if the View has focus; false otherwise. 5015 * @param direction The direction focus has moved when requestFocus() 5016 * is called to give this view focus. Values are 5017 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5018 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5019 * It may not always apply, in which case use the default. 5020 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5021 * system, of the previously focused view. If applicable, this will be 5022 * passed in as finer grained information about where the focus is coming 5023 * from (in addition to direction). Will be <code>null</code> otherwise. 5024 */ 5025 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5026 @Nullable Rect previouslyFocusedRect) { 5027 if (gainFocus) { 5028 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5029 } else { 5030 notifyViewAccessibilityStateChangedIfNeeded( 5031 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5032 } 5033 5034 InputMethodManager imm = InputMethodManager.peekInstance(); 5035 if (!gainFocus) { 5036 if (isPressed()) { 5037 setPressed(false); 5038 } 5039 if (imm != null && mAttachInfo != null 5040 && mAttachInfo.mHasWindowFocus) { 5041 imm.focusOut(this); 5042 } 5043 onFocusLost(); 5044 } else if (imm != null && mAttachInfo != null 5045 && mAttachInfo.mHasWindowFocus) { 5046 imm.focusIn(this); 5047 } 5048 5049 invalidate(true); 5050 ListenerInfo li = mListenerInfo; 5051 if (li != null && li.mOnFocusChangeListener != null) { 5052 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5053 } 5054 5055 if (mAttachInfo != null) { 5056 mAttachInfo.mKeyDispatchState.reset(this); 5057 } 5058 } 5059 5060 /** 5061 * Sends an accessibility event of the given type. If accessibility is 5062 * not enabled this method has no effect. The default implementation calls 5063 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5064 * to populate information about the event source (this View), then calls 5065 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5066 * populate the text content of the event source including its descendants, 5067 * and last calls 5068 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5069 * on its parent to resuest sending of the event to interested parties. 5070 * <p> 5071 * If an {@link AccessibilityDelegate} has been specified via calling 5072 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5073 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5074 * responsible for handling this call. 5075 * </p> 5076 * 5077 * @param eventType The type of the event to send, as defined by several types from 5078 * {@link android.view.accessibility.AccessibilityEvent}, such as 5079 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5080 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5081 * 5082 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5083 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5084 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5085 * @see AccessibilityDelegate 5086 */ 5087 public void sendAccessibilityEvent(int eventType) { 5088 // Excluded views do not send accessibility events. 5089 if (!includeForAccessibility()) { 5090 return; 5091 } 5092 if (mAccessibilityDelegate != null) { 5093 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5094 } else { 5095 sendAccessibilityEventInternal(eventType); 5096 } 5097 } 5098 5099 /** 5100 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5101 * {@link AccessibilityEvent} to make an announcement which is related to some 5102 * sort of a context change for which none of the events representing UI transitions 5103 * is a good fit. For example, announcing a new page in a book. If accessibility 5104 * is not enabled this method does nothing. 5105 * 5106 * @param text The announcement text. 5107 */ 5108 public void announceForAccessibility(CharSequence text) { 5109 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null 5110 && isImportantForAccessibility()) { 5111 AccessibilityEvent event = AccessibilityEvent.obtain( 5112 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5113 onInitializeAccessibilityEvent(event); 5114 event.getText().add(text); 5115 event.setContentDescription(null); 5116 mParent.requestSendAccessibilityEvent(this, event); 5117 } 5118 } 5119 5120 /** 5121 * @see #sendAccessibilityEvent(int) 5122 * 5123 * Note: Called from the default {@link AccessibilityDelegate}. 5124 */ 5125 void sendAccessibilityEventInternal(int eventType) { 5126 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5127 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5128 } 5129 } 5130 5131 /** 5132 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5133 * takes as an argument an empty {@link AccessibilityEvent} and does not 5134 * perform a check whether accessibility is enabled. 5135 * <p> 5136 * If an {@link AccessibilityDelegate} has been specified via calling 5137 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5138 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5139 * is responsible for handling this call. 5140 * </p> 5141 * 5142 * @param event The event to send. 5143 * 5144 * @see #sendAccessibilityEvent(int) 5145 */ 5146 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5147 if (mAccessibilityDelegate != null) { 5148 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5149 } else { 5150 sendAccessibilityEventUncheckedInternal(event); 5151 } 5152 } 5153 5154 /** 5155 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5156 * 5157 * Note: Called from the default {@link AccessibilityDelegate}. 5158 */ 5159 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5160 if (!isShown() || !isImportantForAccessibility()) { 5161 return; 5162 } 5163 onInitializeAccessibilityEvent(event); 5164 // Only a subset of accessibility events populates text content. 5165 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5166 dispatchPopulateAccessibilityEvent(event); 5167 } 5168 // In the beginning we called #isShown(), so we know that getParent() is not null. 5169 getParent().requestSendAccessibilityEvent(this, event); 5170 } 5171 5172 /** 5173 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5174 * to its children for adding their text content to the event. Note that the 5175 * event text is populated in a separate dispatch path since we add to the 5176 * event not only the text of the source but also the text of all its descendants. 5177 * A typical implementation will call 5178 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5179 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5180 * on each child. Override this method if custom population of the event text 5181 * content is required. 5182 * <p> 5183 * If an {@link AccessibilityDelegate} has been specified via calling 5184 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5185 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5186 * is responsible for handling this call. 5187 * </p> 5188 * <p> 5189 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5190 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5191 * </p> 5192 * 5193 * @param event The event. 5194 * 5195 * @return True if the event population was completed. 5196 */ 5197 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5198 if (mAccessibilityDelegate != null) { 5199 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5200 } else { 5201 return dispatchPopulateAccessibilityEventInternal(event); 5202 } 5203 } 5204 5205 /** 5206 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5207 * 5208 * Note: Called from the default {@link AccessibilityDelegate}. 5209 */ 5210 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5211 onPopulateAccessibilityEvent(event); 5212 return false; 5213 } 5214 5215 /** 5216 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5217 * giving a chance to this View to populate the accessibility event with its 5218 * text content. While this method is free to modify event 5219 * attributes other than text content, doing so should normally be performed in 5220 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5221 * <p> 5222 * Example: Adding formatted date string to an accessibility event in addition 5223 * to the text added by the super implementation: 5224 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5225 * super.onPopulateAccessibilityEvent(event); 5226 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5227 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5228 * mCurrentDate.getTimeInMillis(), flags); 5229 * event.getText().add(selectedDateUtterance); 5230 * }</pre> 5231 * <p> 5232 * If an {@link AccessibilityDelegate} has been specified via calling 5233 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5234 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5235 * is responsible for handling this call. 5236 * </p> 5237 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5238 * information to the event, in case the default implementation has basic information to add. 5239 * </p> 5240 * 5241 * @param event The accessibility event which to populate. 5242 * 5243 * @see #sendAccessibilityEvent(int) 5244 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5245 */ 5246 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5247 if (mAccessibilityDelegate != null) { 5248 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5249 } else { 5250 onPopulateAccessibilityEventInternal(event); 5251 } 5252 } 5253 5254 /** 5255 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5256 * 5257 * Note: Called from the default {@link AccessibilityDelegate}. 5258 */ 5259 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5260 } 5261 5262 /** 5263 * Initializes an {@link AccessibilityEvent} with information about 5264 * this View which is the event source. In other words, the source of 5265 * an accessibility event is the view whose state change triggered firing 5266 * the event. 5267 * <p> 5268 * Example: Setting the password property of an event in addition 5269 * to properties set by the super implementation: 5270 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5271 * super.onInitializeAccessibilityEvent(event); 5272 * event.setPassword(true); 5273 * }</pre> 5274 * <p> 5275 * If an {@link AccessibilityDelegate} has been specified via calling 5276 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5277 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5278 * is responsible for handling this call. 5279 * </p> 5280 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5281 * information to the event, in case the default implementation has basic information to add. 5282 * </p> 5283 * @param event The event to initialize. 5284 * 5285 * @see #sendAccessibilityEvent(int) 5286 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5287 */ 5288 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5289 if (mAccessibilityDelegate != null) { 5290 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5291 } else { 5292 onInitializeAccessibilityEventInternal(event); 5293 } 5294 } 5295 5296 /** 5297 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5298 * 5299 * Note: Called from the default {@link AccessibilityDelegate}. 5300 */ 5301 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5302 event.setSource(this); 5303 event.setClassName(View.class.getName()); 5304 event.setPackageName(getContext().getPackageName()); 5305 event.setEnabled(isEnabled()); 5306 event.setContentDescription(mContentDescription); 5307 5308 switch (event.getEventType()) { 5309 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5310 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5311 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5312 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5313 event.setItemCount(focusablesTempList.size()); 5314 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5315 if (mAttachInfo != null) { 5316 focusablesTempList.clear(); 5317 } 5318 } break; 5319 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5320 CharSequence text = getIterableTextForAccessibility(); 5321 if (text != null && text.length() > 0) { 5322 event.setFromIndex(getAccessibilitySelectionStart()); 5323 event.setToIndex(getAccessibilitySelectionEnd()); 5324 event.setItemCount(text.length()); 5325 } 5326 } break; 5327 } 5328 } 5329 5330 /** 5331 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5332 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5333 * This method is responsible for obtaining an accessibility node info from a 5334 * pool of reusable instances and calling 5335 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5336 * initialize the former. 5337 * <p> 5338 * Note: The client is responsible for recycling the obtained instance by calling 5339 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5340 * </p> 5341 * 5342 * @return A populated {@link AccessibilityNodeInfo}. 5343 * 5344 * @see AccessibilityNodeInfo 5345 */ 5346 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5347 if (mAccessibilityDelegate != null) { 5348 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5349 } else { 5350 return createAccessibilityNodeInfoInternal(); 5351 } 5352 } 5353 5354 /** 5355 * @see #createAccessibilityNodeInfo() 5356 */ 5357 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5358 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5359 if (provider != null) { 5360 return provider.createAccessibilityNodeInfo(View.NO_ID); 5361 } else { 5362 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5363 onInitializeAccessibilityNodeInfo(info); 5364 return info; 5365 } 5366 } 5367 5368 /** 5369 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5370 * The base implementation sets: 5371 * <ul> 5372 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5373 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5374 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5375 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5376 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5377 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5378 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5379 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5380 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5381 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5382 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5383 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5384 * </ul> 5385 * <p> 5386 * Subclasses should override this method, call the super implementation, 5387 * and set additional attributes. 5388 * </p> 5389 * <p> 5390 * If an {@link AccessibilityDelegate} has been specified via calling 5391 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5392 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5393 * is responsible for handling this call. 5394 * </p> 5395 * 5396 * @param info The instance to initialize. 5397 */ 5398 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5399 if (mAccessibilityDelegate != null) { 5400 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5401 } else { 5402 onInitializeAccessibilityNodeInfoInternal(info); 5403 } 5404 } 5405 5406 /** 5407 * Gets the location of this view in screen coordintates. 5408 * 5409 * @param outRect The output location 5410 */ 5411 void getBoundsOnScreen(Rect outRect) { 5412 if (mAttachInfo == null) { 5413 return; 5414 } 5415 5416 RectF position = mAttachInfo.mTmpTransformRect; 5417 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5418 5419 if (!hasIdentityMatrix()) { 5420 getMatrix().mapRect(position); 5421 } 5422 5423 position.offset(mLeft, mTop); 5424 5425 ViewParent parent = mParent; 5426 while (parent instanceof View) { 5427 View parentView = (View) parent; 5428 5429 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5430 5431 if (!parentView.hasIdentityMatrix()) { 5432 parentView.getMatrix().mapRect(position); 5433 } 5434 5435 position.offset(parentView.mLeft, parentView.mTop); 5436 5437 parent = parentView.mParent; 5438 } 5439 5440 if (parent instanceof ViewRootImpl) { 5441 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5442 position.offset(0, -viewRootImpl.mCurScrollY); 5443 } 5444 5445 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5446 5447 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5448 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5449 } 5450 5451 /** 5452 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5453 * 5454 * Note: Called from the default {@link AccessibilityDelegate}. 5455 */ 5456 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5457 Rect bounds = mAttachInfo.mTmpInvalRect; 5458 5459 getDrawingRect(bounds); 5460 info.setBoundsInParent(bounds); 5461 5462 getBoundsOnScreen(bounds); 5463 info.setBoundsInScreen(bounds); 5464 5465 ViewParent parent = getParentForAccessibility(); 5466 if (parent instanceof View) { 5467 info.setParent((View) parent); 5468 } 5469 5470 if (mID != View.NO_ID) { 5471 View rootView = getRootView(); 5472 if (rootView == null) { 5473 rootView = this; 5474 } 5475 View label = rootView.findLabelForView(this, mID); 5476 if (label != null) { 5477 info.setLabeledBy(label); 5478 } 5479 5480 if ((mAttachInfo.mAccessibilityFetchFlags 5481 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5482 && Resources.resourceHasPackage(mID)) { 5483 try { 5484 String viewId = getResources().getResourceName(mID); 5485 info.setViewIdResourceName(viewId); 5486 } catch (Resources.NotFoundException nfe) { 5487 /* ignore */ 5488 } 5489 } 5490 } 5491 5492 if (mLabelForId != View.NO_ID) { 5493 View rootView = getRootView(); 5494 if (rootView == null) { 5495 rootView = this; 5496 } 5497 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5498 if (labeled != null) { 5499 info.setLabelFor(labeled); 5500 } 5501 } 5502 5503 info.setVisibleToUser(isVisibleToUser()); 5504 5505 info.setPackageName(mContext.getPackageName()); 5506 info.setClassName(View.class.getName()); 5507 info.setContentDescription(getContentDescription()); 5508 5509 info.setEnabled(isEnabled()); 5510 info.setClickable(isClickable()); 5511 info.setFocusable(isFocusable()); 5512 info.setFocused(isFocused()); 5513 info.setAccessibilityFocused(isAccessibilityFocused()); 5514 info.setSelected(isSelected()); 5515 info.setLongClickable(isLongClickable()); 5516 info.setLiveRegion(getAccessibilityLiveRegion()); 5517 5518 // TODO: These make sense only if we are in an AdapterView but all 5519 // views can be selected. Maybe from accessibility perspective 5520 // we should report as selectable view in an AdapterView. 5521 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5522 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5523 5524 if (isFocusable()) { 5525 if (isFocused()) { 5526 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5527 } else { 5528 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5529 } 5530 } 5531 5532 if (!isAccessibilityFocused()) { 5533 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5534 } else { 5535 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5536 } 5537 5538 if (isClickable() && isEnabled()) { 5539 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5540 } 5541 5542 if (isLongClickable() && isEnabled()) { 5543 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5544 } 5545 5546 CharSequence text = getIterableTextForAccessibility(); 5547 if (text != null && text.length() > 0) { 5548 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5549 5550 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5551 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5552 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5553 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5554 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5555 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5556 } 5557 } 5558 5559 private View findLabelForView(View view, int labeledId) { 5560 if (mMatchLabelForPredicate == null) { 5561 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5562 } 5563 mMatchLabelForPredicate.mLabeledId = labeledId; 5564 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5565 } 5566 5567 /** 5568 * Computes whether this view is visible to the user. Such a view is 5569 * attached, visible, all its predecessors are visible, it is not clipped 5570 * entirely by its predecessors, and has an alpha greater than zero. 5571 * 5572 * @return Whether the view is visible on the screen. 5573 * 5574 * @hide 5575 */ 5576 protected boolean isVisibleToUser() { 5577 return isVisibleToUser(null); 5578 } 5579 5580 /** 5581 * Computes whether the given portion of this view is visible to the user. 5582 * Such a view is attached, visible, all its predecessors are visible, 5583 * has an alpha greater than zero, and the specified portion is not 5584 * clipped entirely by its predecessors. 5585 * 5586 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5587 * <code>null</code>, and the entire view will be tested in this case. 5588 * When <code>true</code> is returned by the function, the actual visible 5589 * region will be stored in this parameter; that is, if boundInView is fully 5590 * contained within the view, no modification will be made, otherwise regions 5591 * outside of the visible area of the view will be clipped. 5592 * 5593 * @return Whether the specified portion of the view is visible on the screen. 5594 * 5595 * @hide 5596 */ 5597 protected boolean isVisibleToUser(Rect boundInView) { 5598 if (mAttachInfo != null) { 5599 // Attached to invisible window means this view is not visible. 5600 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5601 return false; 5602 } 5603 // An invisible predecessor or one with alpha zero means 5604 // that this view is not visible to the user. 5605 Object current = this; 5606 while (current instanceof View) { 5607 View view = (View) current; 5608 // We have attach info so this view is attached and there is no 5609 // need to check whether we reach to ViewRootImpl on the way up. 5610 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5611 view.getVisibility() != VISIBLE) { 5612 return false; 5613 } 5614 current = view.mParent; 5615 } 5616 // Check if the view is entirely covered by its predecessors. 5617 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5618 Point offset = mAttachInfo.mPoint; 5619 if (!getGlobalVisibleRect(visibleRect, offset)) { 5620 return false; 5621 } 5622 // Check if the visible portion intersects the rectangle of interest. 5623 if (boundInView != null) { 5624 visibleRect.offset(-offset.x, -offset.y); 5625 return boundInView.intersect(visibleRect); 5626 } 5627 return true; 5628 } 5629 return false; 5630 } 5631 5632 /** 5633 * Returns the delegate for implementing accessibility support via 5634 * composition. For more details see {@link AccessibilityDelegate}. 5635 * 5636 * @return The delegate, or null if none set. 5637 * 5638 * @hide 5639 */ 5640 public AccessibilityDelegate getAccessibilityDelegate() { 5641 return mAccessibilityDelegate; 5642 } 5643 5644 /** 5645 * Sets a delegate for implementing accessibility support via composition as 5646 * opposed to inheritance. The delegate's primary use is for implementing 5647 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5648 * 5649 * @param delegate The delegate instance. 5650 * 5651 * @see AccessibilityDelegate 5652 */ 5653 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5654 mAccessibilityDelegate = delegate; 5655 } 5656 5657 /** 5658 * Gets the provider for managing a virtual view hierarchy rooted at this View 5659 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5660 * that explore the window content. 5661 * <p> 5662 * If this method returns an instance, this instance is responsible for managing 5663 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5664 * View including the one representing the View itself. Similarly the returned 5665 * instance is responsible for performing accessibility actions on any virtual 5666 * view or the root view itself. 5667 * </p> 5668 * <p> 5669 * If an {@link AccessibilityDelegate} has been specified via calling 5670 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5671 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5672 * is responsible for handling this call. 5673 * </p> 5674 * 5675 * @return The provider. 5676 * 5677 * @see AccessibilityNodeProvider 5678 */ 5679 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5680 if (mAccessibilityDelegate != null) { 5681 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5682 } else { 5683 return null; 5684 } 5685 } 5686 5687 /** 5688 * Gets the unique identifier of this view on the screen for accessibility purposes. 5689 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5690 * 5691 * @return The view accessibility id. 5692 * 5693 * @hide 5694 */ 5695 public int getAccessibilityViewId() { 5696 if (mAccessibilityViewId == NO_ID) { 5697 mAccessibilityViewId = sNextAccessibilityViewId++; 5698 } 5699 return mAccessibilityViewId; 5700 } 5701 5702 /** 5703 * Gets the unique identifier of the window in which this View reseides. 5704 * 5705 * @return The window accessibility id. 5706 * 5707 * @hide 5708 */ 5709 public int getAccessibilityWindowId() { 5710 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId : NO_ID; 5711 } 5712 5713 /** 5714 * Gets the {@link View} description. It briefly describes the view and is 5715 * primarily used for accessibility support. Set this property to enable 5716 * better accessibility support for your application. This is especially 5717 * true for views that do not have textual representation (For example, 5718 * ImageButton). 5719 * 5720 * @return The content description. 5721 * 5722 * @attr ref android.R.styleable#View_contentDescription 5723 */ 5724 @ViewDebug.ExportedProperty(category = "accessibility") 5725 public CharSequence getContentDescription() { 5726 return mContentDescription; 5727 } 5728 5729 /** 5730 * Sets the {@link View} description. It briefly describes the view and is 5731 * primarily used for accessibility support. Set this property to enable 5732 * better accessibility support for your application. This is especially 5733 * true for views that do not have textual representation (For example, 5734 * ImageButton). 5735 * 5736 * @param contentDescription The content description. 5737 * 5738 * @attr ref android.R.styleable#View_contentDescription 5739 */ 5740 @RemotableViewMethod 5741 public void setContentDescription(CharSequence contentDescription) { 5742 if (mContentDescription == null) { 5743 if (contentDescription == null) { 5744 return; 5745 } 5746 } else if (mContentDescription.equals(contentDescription)) { 5747 return; 5748 } 5749 mContentDescription = contentDescription; 5750 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5751 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5752 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5753 notifySubtreeAccessibilityStateChangedIfNeeded(); 5754 } else { 5755 notifyViewAccessibilityStateChangedIfNeeded( 5756 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5757 } 5758 } 5759 5760 /** 5761 * Gets the id of a view for which this view serves as a label for 5762 * accessibility purposes. 5763 * 5764 * @return The labeled view id. 5765 */ 5766 @ViewDebug.ExportedProperty(category = "accessibility") 5767 public int getLabelFor() { 5768 return mLabelForId; 5769 } 5770 5771 /** 5772 * Sets the id of a view for which this view serves as a label for 5773 * accessibility purposes. 5774 * 5775 * @param id The labeled view id. 5776 */ 5777 @RemotableViewMethod 5778 public void setLabelFor(int id) { 5779 mLabelForId = id; 5780 if (mLabelForId != View.NO_ID 5781 && mID == View.NO_ID) { 5782 mID = generateViewId(); 5783 } 5784 } 5785 5786 /** 5787 * Invoked whenever this view loses focus, either by losing window focus or by losing 5788 * focus within its window. This method can be used to clear any state tied to the 5789 * focus. For instance, if a button is held pressed with the trackball and the window 5790 * loses focus, this method can be used to cancel the press. 5791 * 5792 * Subclasses of View overriding this method should always call super.onFocusLost(). 5793 * 5794 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5795 * @see #onWindowFocusChanged(boolean) 5796 * 5797 * @hide pending API council approval 5798 */ 5799 protected void onFocusLost() { 5800 resetPressedState(); 5801 } 5802 5803 private void resetPressedState() { 5804 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5805 return; 5806 } 5807 5808 if (isPressed()) { 5809 setPressed(false); 5810 5811 if (!mHasPerformedLongPress) { 5812 removeLongPressCallback(); 5813 } 5814 } 5815 } 5816 5817 /** 5818 * Returns true if this view has focus 5819 * 5820 * @return True if this view has focus, false otherwise. 5821 */ 5822 @ViewDebug.ExportedProperty(category = "focus") 5823 public boolean isFocused() { 5824 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5825 } 5826 5827 /** 5828 * Find the view in the hierarchy rooted at this view that currently has 5829 * focus. 5830 * 5831 * @return The view that currently has focus, or null if no focused view can 5832 * be found. 5833 */ 5834 public View findFocus() { 5835 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5836 } 5837 5838 /** 5839 * Indicates whether this view is one of the set of scrollable containers in 5840 * its window. 5841 * 5842 * @return whether this view is one of the set of scrollable containers in 5843 * its window 5844 * 5845 * @attr ref android.R.styleable#View_isScrollContainer 5846 */ 5847 public boolean isScrollContainer() { 5848 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5849 } 5850 5851 /** 5852 * Change whether this view is one of the set of scrollable containers in 5853 * its window. This will be used to determine whether the window can 5854 * resize or must pan when a soft input area is open -- scrollable 5855 * containers allow the window to use resize mode since the container 5856 * will appropriately shrink. 5857 * 5858 * @attr ref android.R.styleable#View_isScrollContainer 5859 */ 5860 public void setScrollContainer(boolean isScrollContainer) { 5861 if (isScrollContainer) { 5862 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5863 mAttachInfo.mScrollContainers.add(this); 5864 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5865 } 5866 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5867 } else { 5868 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5869 mAttachInfo.mScrollContainers.remove(this); 5870 } 5871 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5872 } 5873 } 5874 5875 /** 5876 * Returns the quality of the drawing cache. 5877 * 5878 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5879 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5880 * 5881 * @see #setDrawingCacheQuality(int) 5882 * @see #setDrawingCacheEnabled(boolean) 5883 * @see #isDrawingCacheEnabled() 5884 * 5885 * @attr ref android.R.styleable#View_drawingCacheQuality 5886 */ 5887 @DrawingCacheQuality 5888 public int getDrawingCacheQuality() { 5889 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5890 } 5891 5892 /** 5893 * Set the drawing cache quality of this view. This value is used only when the 5894 * drawing cache is enabled 5895 * 5896 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5897 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5898 * 5899 * @see #getDrawingCacheQuality() 5900 * @see #setDrawingCacheEnabled(boolean) 5901 * @see #isDrawingCacheEnabled() 5902 * 5903 * @attr ref android.R.styleable#View_drawingCacheQuality 5904 */ 5905 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5906 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5907 } 5908 5909 /** 5910 * Returns whether the screen should remain on, corresponding to the current 5911 * value of {@link #KEEP_SCREEN_ON}. 5912 * 5913 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5914 * 5915 * @see #setKeepScreenOn(boolean) 5916 * 5917 * @attr ref android.R.styleable#View_keepScreenOn 5918 */ 5919 public boolean getKeepScreenOn() { 5920 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5921 } 5922 5923 /** 5924 * Controls whether the screen should remain on, modifying the 5925 * value of {@link #KEEP_SCREEN_ON}. 5926 * 5927 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5928 * 5929 * @see #getKeepScreenOn() 5930 * 5931 * @attr ref android.R.styleable#View_keepScreenOn 5932 */ 5933 public void setKeepScreenOn(boolean keepScreenOn) { 5934 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5935 } 5936 5937 /** 5938 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5939 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5940 * 5941 * @attr ref android.R.styleable#View_nextFocusLeft 5942 */ 5943 public int getNextFocusLeftId() { 5944 return mNextFocusLeftId; 5945 } 5946 5947 /** 5948 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5949 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5950 * decide automatically. 5951 * 5952 * @attr ref android.R.styleable#View_nextFocusLeft 5953 */ 5954 public void setNextFocusLeftId(int nextFocusLeftId) { 5955 mNextFocusLeftId = nextFocusLeftId; 5956 } 5957 5958 /** 5959 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5960 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5961 * 5962 * @attr ref android.R.styleable#View_nextFocusRight 5963 */ 5964 public int getNextFocusRightId() { 5965 return mNextFocusRightId; 5966 } 5967 5968 /** 5969 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5970 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5971 * decide automatically. 5972 * 5973 * @attr ref android.R.styleable#View_nextFocusRight 5974 */ 5975 public void setNextFocusRightId(int nextFocusRightId) { 5976 mNextFocusRightId = nextFocusRightId; 5977 } 5978 5979 /** 5980 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5981 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5982 * 5983 * @attr ref android.R.styleable#View_nextFocusUp 5984 */ 5985 public int getNextFocusUpId() { 5986 return mNextFocusUpId; 5987 } 5988 5989 /** 5990 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5991 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5992 * decide automatically. 5993 * 5994 * @attr ref android.R.styleable#View_nextFocusUp 5995 */ 5996 public void setNextFocusUpId(int nextFocusUpId) { 5997 mNextFocusUpId = nextFocusUpId; 5998 } 5999 6000 /** 6001 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6002 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6003 * 6004 * @attr ref android.R.styleable#View_nextFocusDown 6005 */ 6006 public int getNextFocusDownId() { 6007 return mNextFocusDownId; 6008 } 6009 6010 /** 6011 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6012 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6013 * decide automatically. 6014 * 6015 * @attr ref android.R.styleable#View_nextFocusDown 6016 */ 6017 public void setNextFocusDownId(int nextFocusDownId) { 6018 mNextFocusDownId = nextFocusDownId; 6019 } 6020 6021 /** 6022 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6023 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6024 * 6025 * @attr ref android.R.styleable#View_nextFocusForward 6026 */ 6027 public int getNextFocusForwardId() { 6028 return mNextFocusForwardId; 6029 } 6030 6031 /** 6032 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6033 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6034 * decide automatically. 6035 * 6036 * @attr ref android.R.styleable#View_nextFocusForward 6037 */ 6038 public void setNextFocusForwardId(int nextFocusForwardId) { 6039 mNextFocusForwardId = nextFocusForwardId; 6040 } 6041 6042 /** 6043 * Returns the visibility of this view and all of its ancestors 6044 * 6045 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6046 */ 6047 public boolean isShown() { 6048 View current = this; 6049 //noinspection ConstantConditions 6050 do { 6051 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6052 return false; 6053 } 6054 ViewParent parent = current.mParent; 6055 if (parent == null) { 6056 return false; // We are not attached to the view root 6057 } 6058 if (!(parent instanceof View)) { 6059 return true; 6060 } 6061 current = (View) parent; 6062 } while (current != null); 6063 6064 return false; 6065 } 6066 6067 /** 6068 * Called by the view hierarchy when the content insets for a window have 6069 * changed, to allow it to adjust its content to fit within those windows. 6070 * The content insets tell you the space that the status bar, input method, 6071 * and other system windows infringe on the application's window. 6072 * 6073 * <p>You do not normally need to deal with this function, since the default 6074 * window decoration given to applications takes care of applying it to the 6075 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6076 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6077 * and your content can be placed under those system elements. You can then 6078 * use this method within your view hierarchy if you have parts of your UI 6079 * which you would like to ensure are not being covered. 6080 * 6081 * <p>The default implementation of this method simply applies the content 6082 * insets to the view's padding, consuming that content (modifying the 6083 * insets to be 0), and returning true. This behavior is off by default, but can 6084 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6085 * 6086 * <p>This function's traversal down the hierarchy is depth-first. The same content 6087 * insets object is propagated down the hierarchy, so any changes made to it will 6088 * be seen by all following views (including potentially ones above in 6089 * the hierarchy since this is a depth-first traversal). The first view 6090 * that returns true will abort the entire traversal. 6091 * 6092 * <p>The default implementation works well for a situation where it is 6093 * used with a container that covers the entire window, allowing it to 6094 * apply the appropriate insets to its content on all edges. If you need 6095 * a more complicated layout (such as two different views fitting system 6096 * windows, one on the top of the window, and one on the bottom), 6097 * you can override the method and handle the insets however you would like. 6098 * Note that the insets provided by the framework are always relative to the 6099 * far edges of the window, not accounting for the location of the called view 6100 * within that window. (In fact when this method is called you do not yet know 6101 * where the layout will place the view, as it is done before layout happens.) 6102 * 6103 * <p>Note: unlike many View methods, there is no dispatch phase to this 6104 * call. If you are overriding it in a ViewGroup and want to allow the 6105 * call to continue to your children, you must be sure to call the super 6106 * implementation. 6107 * 6108 * <p>Here is a sample layout that makes use of fitting system windows 6109 * to have controls for a video view placed inside of the window decorations 6110 * that it hides and shows. This can be used with code like the second 6111 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6112 * 6113 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6114 * 6115 * @param insets Current content insets of the window. Prior to 6116 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6117 * the insets or else you and Android will be unhappy. 6118 * 6119 * @return {@code true} if this view applied the insets and it should not 6120 * continue propagating further down the hierarchy, {@code false} otherwise. 6121 * @see #getFitsSystemWindows() 6122 * @see #setFitsSystemWindows(boolean) 6123 * @see #setSystemUiVisibility(int) 6124 */ 6125 protected boolean fitSystemWindows(Rect insets) { 6126 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6127 mUserPaddingStart = UNDEFINED_PADDING; 6128 mUserPaddingEnd = UNDEFINED_PADDING; 6129 Rect localInsets = sThreadLocal.get(); 6130 if (localInsets == null) { 6131 localInsets = new Rect(); 6132 sThreadLocal.set(localInsets); 6133 } 6134 boolean res = computeFitSystemWindows(insets, localInsets); 6135 mUserPaddingLeftInitial = localInsets.left; 6136 mUserPaddingRightInitial = localInsets.right; 6137 internalSetPadding(localInsets.left, localInsets.top, 6138 localInsets.right, localInsets.bottom); 6139 return res; 6140 } 6141 return false; 6142 } 6143 6144 /** 6145 * @hide Compute the insets that should be consumed by this view and the ones 6146 * that should propagate to those under it. 6147 */ 6148 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6149 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6150 || mAttachInfo == null 6151 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6152 && !mAttachInfo.mOverscanRequested)) { 6153 outLocalInsets.set(inoutInsets); 6154 inoutInsets.set(0, 0, 0, 0); 6155 return true; 6156 } else { 6157 // The application wants to take care of fitting system window for 6158 // the content... however we still need to take care of any overscan here. 6159 final Rect overscan = mAttachInfo.mOverscanInsets; 6160 outLocalInsets.set(overscan); 6161 inoutInsets.left -= overscan.left; 6162 inoutInsets.top -= overscan.top; 6163 inoutInsets.right -= overscan.right; 6164 inoutInsets.bottom -= overscan.bottom; 6165 return false; 6166 } 6167 } 6168 6169 /** 6170 * Sets whether or not this view should account for system screen decorations 6171 * such as the status bar and inset its content; that is, controlling whether 6172 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6173 * executed. See that method for more details. 6174 * 6175 * <p>Note that if you are providing your own implementation of 6176 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6177 * flag to true -- your implementation will be overriding the default 6178 * implementation that checks this flag. 6179 * 6180 * @param fitSystemWindows If true, then the default implementation of 6181 * {@link #fitSystemWindows(Rect)} will be executed. 6182 * 6183 * @attr ref android.R.styleable#View_fitsSystemWindows 6184 * @see #getFitsSystemWindows() 6185 * @see #fitSystemWindows(Rect) 6186 * @see #setSystemUiVisibility(int) 6187 */ 6188 public void setFitsSystemWindows(boolean fitSystemWindows) { 6189 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6190 } 6191 6192 /** 6193 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6194 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6195 * will be executed. 6196 * 6197 * @return {@code true} if the default implementation of 6198 * {@link #fitSystemWindows(Rect)} will be executed. 6199 * 6200 * @attr ref android.R.styleable#View_fitsSystemWindows 6201 * @see #setFitsSystemWindows(boolean) 6202 * @see #fitSystemWindows(Rect) 6203 * @see #setSystemUiVisibility(int) 6204 */ 6205 public boolean getFitsSystemWindows() { 6206 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6207 } 6208 6209 /** @hide */ 6210 public boolean fitsSystemWindows() { 6211 return getFitsSystemWindows(); 6212 } 6213 6214 /** 6215 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6216 */ 6217 public void requestFitSystemWindows() { 6218 if (mParent != null) { 6219 mParent.requestFitSystemWindows(); 6220 } 6221 } 6222 6223 /** 6224 * For use by PhoneWindow to make its own system window fitting optional. 6225 * @hide 6226 */ 6227 public void makeOptionalFitsSystemWindows() { 6228 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6229 } 6230 6231 /** 6232 * Returns the visibility status for this view. 6233 * 6234 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6235 * @attr ref android.R.styleable#View_visibility 6236 */ 6237 @ViewDebug.ExportedProperty(mapping = { 6238 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6239 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6240 @ViewDebug.IntToString(from = GONE, to = "GONE") 6241 }) 6242 @Visibility 6243 public int getVisibility() { 6244 return mViewFlags & VISIBILITY_MASK; 6245 } 6246 6247 /** 6248 * Set the enabled state of this view. 6249 * 6250 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6251 * @attr ref android.R.styleable#View_visibility 6252 */ 6253 @RemotableViewMethod 6254 public void setVisibility(@Visibility int visibility) { 6255 setFlags(visibility, VISIBILITY_MASK); 6256 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6257 } 6258 6259 /** 6260 * Returns the enabled status for this view. The interpretation of the 6261 * enabled state varies by subclass. 6262 * 6263 * @return True if this view is enabled, false otherwise. 6264 */ 6265 @ViewDebug.ExportedProperty 6266 public boolean isEnabled() { 6267 return (mViewFlags & ENABLED_MASK) == ENABLED; 6268 } 6269 6270 /** 6271 * Set the enabled state of this view. The interpretation of the enabled 6272 * state varies by subclass. 6273 * 6274 * @param enabled True if this view is enabled, false otherwise. 6275 */ 6276 @RemotableViewMethod 6277 public void setEnabled(boolean enabled) { 6278 if (enabled == isEnabled()) return; 6279 6280 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6281 6282 /* 6283 * The View most likely has to change its appearance, so refresh 6284 * the drawable state. 6285 */ 6286 refreshDrawableState(); 6287 6288 // Invalidate too, since the default behavior for views is to be 6289 // be drawn at 50% alpha rather than to change the drawable. 6290 invalidate(true); 6291 6292 if (!enabled) { 6293 cancelPendingInputEvents(); 6294 } 6295 } 6296 6297 /** 6298 * Set whether this view can receive the focus. 6299 * 6300 * Setting this to false will also ensure that this view is not focusable 6301 * in touch mode. 6302 * 6303 * @param focusable If true, this view can receive the focus. 6304 * 6305 * @see #setFocusableInTouchMode(boolean) 6306 * @attr ref android.R.styleable#View_focusable 6307 */ 6308 public void setFocusable(boolean focusable) { 6309 if (!focusable) { 6310 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6311 } 6312 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6313 } 6314 6315 /** 6316 * Set whether this view can receive focus while in touch mode. 6317 * 6318 * Setting this to true will also ensure that this view is focusable. 6319 * 6320 * @param focusableInTouchMode If true, this view can receive the focus while 6321 * in touch mode. 6322 * 6323 * @see #setFocusable(boolean) 6324 * @attr ref android.R.styleable#View_focusableInTouchMode 6325 */ 6326 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6327 // Focusable in touch mode should always be set before the focusable flag 6328 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6329 // which, in touch mode, will not successfully request focus on this view 6330 // because the focusable in touch mode flag is not set 6331 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6332 if (focusableInTouchMode) { 6333 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6334 } 6335 } 6336 6337 /** 6338 * Set whether this view should have sound effects enabled for events such as 6339 * clicking and touching. 6340 * 6341 * <p>You may wish to disable sound effects for a view if you already play sounds, 6342 * for instance, a dial key that plays dtmf tones. 6343 * 6344 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6345 * @see #isSoundEffectsEnabled() 6346 * @see #playSoundEffect(int) 6347 * @attr ref android.R.styleable#View_soundEffectsEnabled 6348 */ 6349 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6350 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6351 } 6352 6353 /** 6354 * @return whether this view should have sound effects enabled for events such as 6355 * clicking and touching. 6356 * 6357 * @see #setSoundEffectsEnabled(boolean) 6358 * @see #playSoundEffect(int) 6359 * @attr ref android.R.styleable#View_soundEffectsEnabled 6360 */ 6361 @ViewDebug.ExportedProperty 6362 public boolean isSoundEffectsEnabled() { 6363 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6364 } 6365 6366 /** 6367 * Set whether this view should have haptic feedback for events such as 6368 * long presses. 6369 * 6370 * <p>You may wish to disable haptic feedback if your view already controls 6371 * its own haptic feedback. 6372 * 6373 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6374 * @see #isHapticFeedbackEnabled() 6375 * @see #performHapticFeedback(int) 6376 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6377 */ 6378 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6379 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6380 } 6381 6382 /** 6383 * @return whether this view should have haptic feedback enabled for events 6384 * long presses. 6385 * 6386 * @see #setHapticFeedbackEnabled(boolean) 6387 * @see #performHapticFeedback(int) 6388 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6389 */ 6390 @ViewDebug.ExportedProperty 6391 public boolean isHapticFeedbackEnabled() { 6392 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6393 } 6394 6395 /** 6396 * Returns the layout direction for this view. 6397 * 6398 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6399 * {@link #LAYOUT_DIRECTION_RTL}, 6400 * {@link #LAYOUT_DIRECTION_INHERIT} or 6401 * {@link #LAYOUT_DIRECTION_LOCALE}. 6402 * 6403 * @attr ref android.R.styleable#View_layoutDirection 6404 * 6405 * @hide 6406 */ 6407 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6408 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6409 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6410 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6411 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6412 }) 6413 @LayoutDir 6414 public int getRawLayoutDirection() { 6415 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6416 } 6417 6418 /** 6419 * Set the layout direction for this view. This will propagate a reset of layout direction 6420 * resolution to the view's children and resolve layout direction for this view. 6421 * 6422 * @param layoutDirection the layout direction to set. Should be one of: 6423 * 6424 * {@link #LAYOUT_DIRECTION_LTR}, 6425 * {@link #LAYOUT_DIRECTION_RTL}, 6426 * {@link #LAYOUT_DIRECTION_INHERIT}, 6427 * {@link #LAYOUT_DIRECTION_LOCALE}. 6428 * 6429 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6430 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6431 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6432 * 6433 * @attr ref android.R.styleable#View_layoutDirection 6434 */ 6435 @RemotableViewMethod 6436 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6437 if (getRawLayoutDirection() != layoutDirection) { 6438 // Reset the current layout direction and the resolved one 6439 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6440 resetRtlProperties(); 6441 // Set the new layout direction (filtered) 6442 mPrivateFlags2 |= 6443 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6444 // We need to resolve all RTL properties as they all depend on layout direction 6445 resolveRtlPropertiesIfNeeded(); 6446 requestLayout(); 6447 invalidate(true); 6448 } 6449 } 6450 6451 /** 6452 * Returns the resolved layout direction for this view. 6453 * 6454 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6455 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6456 * 6457 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6458 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6459 * 6460 * @attr ref android.R.styleable#View_layoutDirection 6461 */ 6462 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6463 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6464 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6465 }) 6466 @ResolvedLayoutDir 6467 public int getLayoutDirection() { 6468 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6469 if (targetSdkVersion < JELLY_BEAN_MR1) { 6470 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6471 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6472 } 6473 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6474 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6475 } 6476 6477 /** 6478 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6479 * layout attribute and/or the inherited value from the parent 6480 * 6481 * @return true if the layout is right-to-left. 6482 * 6483 * @hide 6484 */ 6485 @ViewDebug.ExportedProperty(category = "layout") 6486 public boolean isLayoutRtl() { 6487 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6488 } 6489 6490 /** 6491 * Indicates whether the view is currently tracking transient state that the 6492 * app should not need to concern itself with saving and restoring, but that 6493 * the framework should take special note to preserve when possible. 6494 * 6495 * <p>A view with transient state cannot be trivially rebound from an external 6496 * data source, such as an adapter binding item views in a list. This may be 6497 * because the view is performing an animation, tracking user selection 6498 * of content, or similar.</p> 6499 * 6500 * @return true if the view has transient state 6501 */ 6502 @ViewDebug.ExportedProperty(category = "layout") 6503 public boolean hasTransientState() { 6504 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6505 } 6506 6507 /** 6508 * Set whether this view is currently tracking transient state that the 6509 * framework should attempt to preserve when possible. This flag is reference counted, 6510 * so every call to setHasTransientState(true) should be paired with a later call 6511 * to setHasTransientState(false). 6512 * 6513 * <p>A view with transient state cannot be trivially rebound from an external 6514 * data source, such as an adapter binding item views in a list. This may be 6515 * because the view is performing an animation, tracking user selection 6516 * of content, or similar.</p> 6517 * 6518 * @param hasTransientState true if this view has transient state 6519 */ 6520 public void setHasTransientState(boolean hasTransientState) { 6521 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6522 mTransientStateCount - 1; 6523 if (mTransientStateCount < 0) { 6524 mTransientStateCount = 0; 6525 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6526 "unmatched pair of setHasTransientState calls"); 6527 } else if ((hasTransientState && mTransientStateCount == 1) || 6528 (!hasTransientState && mTransientStateCount == 0)) { 6529 // update flag if we've just incremented up from 0 or decremented down to 0 6530 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6531 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6532 if (mParent != null) { 6533 try { 6534 mParent.childHasTransientStateChanged(this, hasTransientState); 6535 } catch (AbstractMethodError e) { 6536 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6537 " does not fully implement ViewParent", e); 6538 } 6539 } 6540 } 6541 } 6542 6543 /** 6544 * Returns true if this view is currently attached to a window. 6545 */ 6546 public boolean isAttachedToWindow() { 6547 return mAttachInfo != null; 6548 } 6549 6550 /** 6551 * Returns true if this view has been through at least one layout since it 6552 * was last attached to or detached from a window. 6553 */ 6554 public boolean isLaidOut() { 6555 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6556 } 6557 6558 /** 6559 * If this view doesn't do any drawing on its own, set this flag to 6560 * allow further optimizations. By default, this flag is not set on 6561 * View, but could be set on some View subclasses such as ViewGroup. 6562 * 6563 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6564 * you should clear this flag. 6565 * 6566 * @param willNotDraw whether or not this View draw on its own 6567 */ 6568 public void setWillNotDraw(boolean willNotDraw) { 6569 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6570 } 6571 6572 /** 6573 * Returns whether or not this View draws on its own. 6574 * 6575 * @return true if this view has nothing to draw, false otherwise 6576 */ 6577 @ViewDebug.ExportedProperty(category = "drawing") 6578 public boolean willNotDraw() { 6579 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6580 } 6581 6582 /** 6583 * When a View's drawing cache is enabled, drawing is redirected to an 6584 * offscreen bitmap. Some views, like an ImageView, must be able to 6585 * bypass this mechanism if they already draw a single bitmap, to avoid 6586 * unnecessary usage of the memory. 6587 * 6588 * @param willNotCacheDrawing true if this view does not cache its 6589 * drawing, false otherwise 6590 */ 6591 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6592 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6593 } 6594 6595 /** 6596 * Returns whether or not this View can cache its drawing or not. 6597 * 6598 * @return true if this view does not cache its drawing, false otherwise 6599 */ 6600 @ViewDebug.ExportedProperty(category = "drawing") 6601 public boolean willNotCacheDrawing() { 6602 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6603 } 6604 6605 /** 6606 * Indicates whether this view reacts to click events or not. 6607 * 6608 * @return true if the view is clickable, false otherwise 6609 * 6610 * @see #setClickable(boolean) 6611 * @attr ref android.R.styleable#View_clickable 6612 */ 6613 @ViewDebug.ExportedProperty 6614 public boolean isClickable() { 6615 return (mViewFlags & CLICKABLE) == CLICKABLE; 6616 } 6617 6618 /** 6619 * Enables or disables click events for this view. When a view 6620 * is clickable it will change its state to "pressed" on every click. 6621 * Subclasses should set the view clickable to visually react to 6622 * user's clicks. 6623 * 6624 * @param clickable true to make the view clickable, false otherwise 6625 * 6626 * @see #isClickable() 6627 * @attr ref android.R.styleable#View_clickable 6628 */ 6629 public void setClickable(boolean clickable) { 6630 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6631 } 6632 6633 /** 6634 * Indicates whether this view reacts to long click events or not. 6635 * 6636 * @return true if the view is long clickable, false otherwise 6637 * 6638 * @see #setLongClickable(boolean) 6639 * @attr ref android.R.styleable#View_longClickable 6640 */ 6641 public boolean isLongClickable() { 6642 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6643 } 6644 6645 /** 6646 * Enables or disables long click events for this view. When a view is long 6647 * clickable it reacts to the user holding down the button for a longer 6648 * duration than a tap. This event can either launch the listener or a 6649 * context menu. 6650 * 6651 * @param longClickable true to make the view long clickable, false otherwise 6652 * @see #isLongClickable() 6653 * @attr ref android.R.styleable#View_longClickable 6654 */ 6655 public void setLongClickable(boolean longClickable) { 6656 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6657 } 6658 6659 /** 6660 * Sets the pressed state for this view. 6661 * 6662 * @see #isClickable() 6663 * @see #setClickable(boolean) 6664 * 6665 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6666 * the View's internal state from a previously set "pressed" state. 6667 */ 6668 public void setPressed(boolean pressed) { 6669 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6670 6671 if (pressed) { 6672 mPrivateFlags |= PFLAG_PRESSED; 6673 } else { 6674 mPrivateFlags &= ~PFLAG_PRESSED; 6675 } 6676 6677 if (needsRefresh) { 6678 refreshDrawableState(); 6679 } 6680 dispatchSetPressed(pressed); 6681 } 6682 6683 /** 6684 * Dispatch setPressed to all of this View's children. 6685 * 6686 * @see #setPressed(boolean) 6687 * 6688 * @param pressed The new pressed state 6689 */ 6690 protected void dispatchSetPressed(boolean pressed) { 6691 } 6692 6693 /** 6694 * Indicates whether the view is currently in pressed state. Unless 6695 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6696 * the pressed state. 6697 * 6698 * @see #setPressed(boolean) 6699 * @see #isClickable() 6700 * @see #setClickable(boolean) 6701 * 6702 * @return true if the view is currently pressed, false otherwise 6703 */ 6704 public boolean isPressed() { 6705 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6706 } 6707 6708 /** 6709 * Indicates whether this view will save its state (that is, 6710 * whether its {@link #onSaveInstanceState} method will be called). 6711 * 6712 * @return Returns true if the view state saving is enabled, else false. 6713 * 6714 * @see #setSaveEnabled(boolean) 6715 * @attr ref android.R.styleable#View_saveEnabled 6716 */ 6717 public boolean isSaveEnabled() { 6718 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6719 } 6720 6721 /** 6722 * Controls whether the saving of this view's state is 6723 * enabled (that is, whether its {@link #onSaveInstanceState} method 6724 * will be called). Note that even if freezing is enabled, the 6725 * view still must have an id assigned to it (via {@link #setId(int)}) 6726 * for its state to be saved. This flag can only disable the 6727 * saving of this view; any child views may still have their state saved. 6728 * 6729 * @param enabled Set to false to <em>disable</em> state saving, or true 6730 * (the default) to allow it. 6731 * 6732 * @see #isSaveEnabled() 6733 * @see #setId(int) 6734 * @see #onSaveInstanceState() 6735 * @attr ref android.R.styleable#View_saveEnabled 6736 */ 6737 public void setSaveEnabled(boolean enabled) { 6738 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6739 } 6740 6741 /** 6742 * Gets whether the framework should discard touches when the view's 6743 * window is obscured by another visible window. 6744 * Refer to the {@link View} security documentation for more details. 6745 * 6746 * @return True if touch filtering is enabled. 6747 * 6748 * @see #setFilterTouchesWhenObscured(boolean) 6749 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6750 */ 6751 @ViewDebug.ExportedProperty 6752 public boolean getFilterTouchesWhenObscured() { 6753 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6754 } 6755 6756 /** 6757 * Sets whether the framework should discard touches when the view's 6758 * window is obscured by another visible window. 6759 * Refer to the {@link View} security documentation for more details. 6760 * 6761 * @param enabled True if touch filtering should be enabled. 6762 * 6763 * @see #getFilterTouchesWhenObscured 6764 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6765 */ 6766 public void setFilterTouchesWhenObscured(boolean enabled) { 6767 setFlags(enabled ? 0 : FILTER_TOUCHES_WHEN_OBSCURED, 6768 FILTER_TOUCHES_WHEN_OBSCURED); 6769 } 6770 6771 /** 6772 * Indicates whether the entire hierarchy under this view will save its 6773 * state when a state saving traversal occurs from its parent. The default 6774 * is true; if false, these views will not be saved unless 6775 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6776 * 6777 * @return Returns true if the view state saving from parent is enabled, else false. 6778 * 6779 * @see #setSaveFromParentEnabled(boolean) 6780 */ 6781 public boolean isSaveFromParentEnabled() { 6782 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6783 } 6784 6785 /** 6786 * Controls whether the entire hierarchy under this view will save its 6787 * state when a state saving traversal occurs from its parent. The default 6788 * is true; if false, these views will not be saved unless 6789 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6790 * 6791 * @param enabled Set to false to <em>disable</em> state saving, or true 6792 * (the default) to allow it. 6793 * 6794 * @see #isSaveFromParentEnabled() 6795 * @see #setId(int) 6796 * @see #onSaveInstanceState() 6797 */ 6798 public void setSaveFromParentEnabled(boolean enabled) { 6799 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6800 } 6801 6802 6803 /** 6804 * Returns whether this View is able to take focus. 6805 * 6806 * @return True if this view can take focus, or false otherwise. 6807 * @attr ref android.R.styleable#View_focusable 6808 */ 6809 @ViewDebug.ExportedProperty(category = "focus") 6810 public final boolean isFocusable() { 6811 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6812 } 6813 6814 /** 6815 * When a view is focusable, it may not want to take focus when in touch mode. 6816 * For example, a button would like focus when the user is navigating via a D-pad 6817 * so that the user can click on it, but once the user starts touching the screen, 6818 * the button shouldn't take focus 6819 * @return Whether the view is focusable in touch mode. 6820 * @attr ref android.R.styleable#View_focusableInTouchMode 6821 */ 6822 @ViewDebug.ExportedProperty 6823 public final boolean isFocusableInTouchMode() { 6824 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6825 } 6826 6827 /** 6828 * Find the nearest view in the specified direction that can take focus. 6829 * This does not actually give focus to that view. 6830 * 6831 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6832 * 6833 * @return The nearest focusable in the specified direction, or null if none 6834 * can be found. 6835 */ 6836 public View focusSearch(@FocusRealDirection int direction) { 6837 if (mParent != null) { 6838 return mParent.focusSearch(this, direction); 6839 } else { 6840 return null; 6841 } 6842 } 6843 6844 /** 6845 * This method is the last chance for the focused view and its ancestors to 6846 * respond to an arrow key. This is called when the focused view did not 6847 * consume the key internally, nor could the view system find a new view in 6848 * the requested direction to give focus to. 6849 * 6850 * @param focused The currently focused view. 6851 * @param direction The direction focus wants to move. One of FOCUS_UP, 6852 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6853 * @return True if the this view consumed this unhandled move. 6854 */ 6855 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6856 return false; 6857 } 6858 6859 /** 6860 * If a user manually specified the next view id for a particular direction, 6861 * use the root to look up the view. 6862 * @param root The root view of the hierarchy containing this view. 6863 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6864 * or FOCUS_BACKWARD. 6865 * @return The user specified next view, or null if there is none. 6866 */ 6867 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6868 switch (direction) { 6869 case FOCUS_LEFT: 6870 if (mNextFocusLeftId == View.NO_ID) return null; 6871 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6872 case FOCUS_RIGHT: 6873 if (mNextFocusRightId == View.NO_ID) return null; 6874 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6875 case FOCUS_UP: 6876 if (mNextFocusUpId == View.NO_ID) return null; 6877 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6878 case FOCUS_DOWN: 6879 if (mNextFocusDownId == View.NO_ID) return null; 6880 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6881 case FOCUS_FORWARD: 6882 if (mNextFocusForwardId == View.NO_ID) return null; 6883 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6884 case FOCUS_BACKWARD: { 6885 if (mID == View.NO_ID) return null; 6886 final int id = mID; 6887 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6888 @Override 6889 public boolean apply(View t) { 6890 return t.mNextFocusForwardId == id; 6891 } 6892 }); 6893 } 6894 } 6895 return null; 6896 } 6897 6898 private View findViewInsideOutShouldExist(View root, int id) { 6899 if (mMatchIdPredicate == null) { 6900 mMatchIdPredicate = new MatchIdPredicate(); 6901 } 6902 mMatchIdPredicate.mId = id; 6903 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6904 if (result == null) { 6905 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6906 } 6907 return result; 6908 } 6909 6910 /** 6911 * Find and return all focusable views that are descendants of this view, 6912 * possibly including this view if it is focusable itself. 6913 * 6914 * @param direction The direction of the focus 6915 * @return A list of focusable views 6916 */ 6917 public ArrayList<View> getFocusables(@FocusDirection int direction) { 6918 ArrayList<View> result = new ArrayList<View>(24); 6919 addFocusables(result, direction); 6920 return result; 6921 } 6922 6923 /** 6924 * Add any focusable views that are descendants of this view (possibly 6925 * including this view if it is focusable itself) to views. If we are in touch mode, 6926 * only add views that are also focusable in touch mode. 6927 * 6928 * @param views Focusable views found so far 6929 * @param direction The direction of the focus 6930 */ 6931 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 6932 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6933 } 6934 6935 /** 6936 * Adds any focusable views that are descendants of this view (possibly 6937 * including this view if it is focusable itself) to views. This method 6938 * adds all focusable views regardless if we are in touch mode or 6939 * only views focusable in touch mode if we are in touch mode or 6940 * only views that can take accessibility focus if accessibility is enabeld 6941 * depending on the focusable mode paramater. 6942 * 6943 * @param views Focusable views found so far or null if all we are interested is 6944 * the number of focusables. 6945 * @param direction The direction of the focus. 6946 * @param focusableMode The type of focusables to be added. 6947 * 6948 * @see #FOCUSABLES_ALL 6949 * @see #FOCUSABLES_TOUCH_MODE 6950 */ 6951 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 6952 @FocusableMode int focusableMode) { 6953 if (views == null) { 6954 return; 6955 } 6956 if (!isFocusable()) { 6957 return; 6958 } 6959 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6960 && isInTouchMode() && !isFocusableInTouchMode()) { 6961 return; 6962 } 6963 views.add(this); 6964 } 6965 6966 /** 6967 * Finds the Views that contain given text. The containment is case insensitive. 6968 * The search is performed by either the text that the View renders or the content 6969 * description that describes the view for accessibility purposes and the view does 6970 * not render or both. Clients can specify how the search is to be performed via 6971 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 6972 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 6973 * 6974 * @param outViews The output list of matching Views. 6975 * @param searched The text to match against. 6976 * 6977 * @see #FIND_VIEWS_WITH_TEXT 6978 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 6979 * @see #setContentDescription(CharSequence) 6980 */ 6981 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 6982 @FindViewFlags int flags) { 6983 if (getAccessibilityNodeProvider() != null) { 6984 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 6985 outViews.add(this); 6986 } 6987 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 6988 && (searched != null && searched.length() > 0) 6989 && (mContentDescription != null && mContentDescription.length() > 0)) { 6990 String searchedLowerCase = searched.toString().toLowerCase(); 6991 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 6992 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 6993 outViews.add(this); 6994 } 6995 } 6996 } 6997 6998 /** 6999 * Find and return all touchable views that are descendants of this view, 7000 * possibly including this view if it is touchable itself. 7001 * 7002 * @return A list of touchable views 7003 */ 7004 public ArrayList<View> getTouchables() { 7005 ArrayList<View> result = new ArrayList<View>(); 7006 addTouchables(result); 7007 return result; 7008 } 7009 7010 /** 7011 * Add any touchable views that are descendants of this view (possibly 7012 * including this view if it is touchable itself) to views. 7013 * 7014 * @param views Touchable views found so far 7015 */ 7016 public void addTouchables(ArrayList<View> views) { 7017 final int viewFlags = mViewFlags; 7018 7019 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7020 && (viewFlags & ENABLED_MASK) == ENABLED) { 7021 views.add(this); 7022 } 7023 } 7024 7025 /** 7026 * Returns whether this View is accessibility focused. 7027 * 7028 * @return True if this View is accessibility focused. 7029 */ 7030 public boolean isAccessibilityFocused() { 7031 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7032 } 7033 7034 /** 7035 * Call this to try to give accessibility focus to this view. 7036 * 7037 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7038 * returns false or the view is no visible or the view already has accessibility 7039 * focus. 7040 * 7041 * See also {@link #focusSearch(int)}, which is what you call to say that you 7042 * have focus, and you want your parent to look for the next one. 7043 * 7044 * @return Whether this view actually took accessibility focus. 7045 * 7046 * @hide 7047 */ 7048 public boolean requestAccessibilityFocus() { 7049 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7050 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7051 return false; 7052 } 7053 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7054 return false; 7055 } 7056 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7057 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7058 ViewRootImpl viewRootImpl = getViewRootImpl(); 7059 if (viewRootImpl != null) { 7060 viewRootImpl.setAccessibilityFocus(this, null); 7061 } 7062 invalidate(); 7063 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7064 return true; 7065 } 7066 return false; 7067 } 7068 7069 /** 7070 * Call this to try to clear accessibility focus of this view. 7071 * 7072 * See also {@link #focusSearch(int)}, which is what you call to say that you 7073 * have focus, and you want your parent to look for the next one. 7074 * 7075 * @hide 7076 */ 7077 public void clearAccessibilityFocus() { 7078 clearAccessibilityFocusNoCallbacks(); 7079 // Clear the global reference of accessibility focus if this 7080 // view or any of its descendants had accessibility focus. 7081 ViewRootImpl viewRootImpl = getViewRootImpl(); 7082 if (viewRootImpl != null) { 7083 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7084 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7085 viewRootImpl.setAccessibilityFocus(null, null); 7086 } 7087 } 7088 } 7089 7090 private void sendAccessibilityHoverEvent(int eventType) { 7091 // Since we are not delivering to a client accessibility events from not 7092 // important views (unless the clinet request that) we need to fire the 7093 // event from the deepest view exposed to the client. As a consequence if 7094 // the user crosses a not exposed view the client will see enter and exit 7095 // of the exposed predecessor followed by and enter and exit of that same 7096 // predecessor when entering and exiting the not exposed descendant. This 7097 // is fine since the client has a clear idea which view is hovered at the 7098 // price of a couple more events being sent. This is a simple and 7099 // working solution. 7100 View source = this; 7101 while (true) { 7102 if (source.includeForAccessibility()) { 7103 source.sendAccessibilityEvent(eventType); 7104 return; 7105 } 7106 ViewParent parent = source.getParent(); 7107 if (parent instanceof View) { 7108 source = (View) parent; 7109 } else { 7110 return; 7111 } 7112 } 7113 } 7114 7115 /** 7116 * Clears accessibility focus without calling any callback methods 7117 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7118 * is used for clearing accessibility focus when giving this focus to 7119 * another view. 7120 */ 7121 void clearAccessibilityFocusNoCallbacks() { 7122 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7123 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7124 invalidate(); 7125 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7126 } 7127 } 7128 7129 /** 7130 * Call this to try to give focus to a specific view or to one of its 7131 * descendants. 7132 * 7133 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7134 * false), or if it is focusable and it is not focusable in touch mode 7135 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7136 * 7137 * See also {@link #focusSearch(int)}, which is what you call to say that you 7138 * have focus, and you want your parent to look for the next one. 7139 * 7140 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7141 * {@link #FOCUS_DOWN} and <code>null</code>. 7142 * 7143 * @return Whether this view or one of its descendants actually took focus. 7144 */ 7145 public final boolean requestFocus() { 7146 return requestFocus(View.FOCUS_DOWN); 7147 } 7148 7149 /** 7150 * Call this to try to give focus to a specific view or to one of its 7151 * descendants and give it a hint about what direction focus is heading. 7152 * 7153 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7154 * false), or if it is focusable and it is not focusable in touch mode 7155 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7156 * 7157 * See also {@link #focusSearch(int)}, which is what you call to say that you 7158 * have focus, and you want your parent to look for the next one. 7159 * 7160 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7161 * <code>null</code> set for the previously focused rectangle. 7162 * 7163 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7164 * @return Whether this view or one of its descendants actually took focus. 7165 */ 7166 public final boolean requestFocus(int direction) { 7167 return requestFocus(direction, null); 7168 } 7169 7170 /** 7171 * Call this to try to give focus to a specific view or to one of its descendants 7172 * and give it hints about the direction and a specific rectangle that the focus 7173 * is coming from. The rectangle can help give larger views a finer grained hint 7174 * about where focus is coming from, and therefore, where to show selection, or 7175 * forward focus change internally. 7176 * 7177 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7178 * false), or if it is focusable and it is not focusable in touch mode 7179 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7180 * 7181 * A View will not take focus if it is not visible. 7182 * 7183 * A View will not take focus if one of its parents has 7184 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7185 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7186 * 7187 * See also {@link #focusSearch(int)}, which is what you call to say that you 7188 * have focus, and you want your parent to look for the next one. 7189 * 7190 * You may wish to override this method if your custom {@link View} has an internal 7191 * {@link View} that it wishes to forward the request to. 7192 * 7193 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7194 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7195 * to give a finer grained hint about where focus is coming from. May be null 7196 * if there is no hint. 7197 * @return Whether this view or one of its descendants actually took focus. 7198 */ 7199 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7200 return requestFocusNoSearch(direction, previouslyFocusedRect); 7201 } 7202 7203 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7204 // need to be focusable 7205 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7206 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7207 return false; 7208 } 7209 7210 // need to be focusable in touch mode if in touch mode 7211 if (isInTouchMode() && 7212 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7213 return false; 7214 } 7215 7216 // need to not have any parents blocking us 7217 if (hasAncestorThatBlocksDescendantFocus()) { 7218 return false; 7219 } 7220 7221 handleFocusGainInternal(direction, previouslyFocusedRect); 7222 return true; 7223 } 7224 7225 /** 7226 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7227 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7228 * touch mode to request focus when they are touched. 7229 * 7230 * @return Whether this view or one of its descendants actually took focus. 7231 * 7232 * @see #isInTouchMode() 7233 * 7234 */ 7235 public final boolean requestFocusFromTouch() { 7236 // Leave touch mode if we need to 7237 if (isInTouchMode()) { 7238 ViewRootImpl viewRoot = getViewRootImpl(); 7239 if (viewRoot != null) { 7240 viewRoot.ensureTouchMode(false); 7241 } 7242 } 7243 return requestFocus(View.FOCUS_DOWN); 7244 } 7245 7246 /** 7247 * @return Whether any ancestor of this view blocks descendant focus. 7248 */ 7249 private boolean hasAncestorThatBlocksDescendantFocus() { 7250 ViewParent ancestor = mParent; 7251 while (ancestor instanceof ViewGroup) { 7252 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7253 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7254 return true; 7255 } else { 7256 ancestor = vgAncestor.getParent(); 7257 } 7258 } 7259 return false; 7260 } 7261 7262 /** 7263 * Gets the mode for determining whether this View is important for accessibility 7264 * which is if it fires accessibility events and if it is reported to 7265 * accessibility services that query the screen. 7266 * 7267 * @return The mode for determining whether a View is important for accessibility. 7268 * 7269 * @attr ref android.R.styleable#View_importantForAccessibility 7270 * 7271 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7272 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7273 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7274 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7275 */ 7276 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7277 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7278 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7279 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7280 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7281 to = "noHideDescendants") 7282 }) 7283 public int getImportantForAccessibility() { 7284 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7285 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7286 } 7287 7288 /** 7289 * Sets the live region mode for this view. This indicates to accessibility 7290 * services whether they should automatically notify the user about changes 7291 * to the view's content description or text, or to the content descriptions 7292 * or text of the view's children (where applicable). 7293 * <p> 7294 * For example, in a login screen with a TextView that displays an "incorrect 7295 * password" notification, that view should be marked as a live region with 7296 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7297 * <p> 7298 * To disable change notifications for this view, use 7299 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7300 * mode for most views. 7301 * <p> 7302 * To indicate that the user should be notified of changes, use 7303 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7304 * <p> 7305 * If the view's changes should interrupt ongoing speech and notify the user 7306 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7307 * 7308 * @param mode The live region mode for this view, one of: 7309 * <ul> 7310 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7311 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7312 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7313 * </ul> 7314 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7315 */ 7316 public void setAccessibilityLiveRegion(int mode) { 7317 if (mode != getAccessibilityLiveRegion()) { 7318 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7319 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7320 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7321 notifyViewAccessibilityStateChangedIfNeeded( 7322 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7323 } 7324 } 7325 7326 /** 7327 * Gets the live region mode for this View. 7328 * 7329 * @return The live region mode for the view. 7330 * 7331 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7332 * 7333 * @see #setAccessibilityLiveRegion(int) 7334 */ 7335 public int getAccessibilityLiveRegion() { 7336 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7337 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7338 } 7339 7340 /** 7341 * Sets how to determine whether this view is important for accessibility 7342 * which is if it fires accessibility events and if it is reported to 7343 * accessibility services that query the screen. 7344 * 7345 * @param mode How to determine whether this view is important for accessibility. 7346 * 7347 * @attr ref android.R.styleable#View_importantForAccessibility 7348 * 7349 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7350 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7351 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7352 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7353 */ 7354 public void setImportantForAccessibility(int mode) { 7355 final int oldMode = getImportantForAccessibility(); 7356 if (mode != oldMode) { 7357 // If we're moving between AUTO and another state, we might not need 7358 // to send a subtree changed notification. We'll store the computed 7359 // importance, since we'll need to check it later to make sure. 7360 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7361 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7362 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7363 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7364 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7365 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7366 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7367 notifySubtreeAccessibilityStateChangedIfNeeded(); 7368 } else { 7369 notifyViewAccessibilityStateChangedIfNeeded( 7370 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7371 } 7372 } 7373 } 7374 7375 /** 7376 * Computes whether this view should be exposed for accessibility. In 7377 * general, views that are interactive or provide information are exposed 7378 * while views that serve only as containers are hidden. 7379 * <p> 7380 * If an ancestor of this view has importance 7381 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7382 * returns <code>false</code>. 7383 * <p> 7384 * Otherwise, the value is computed according to the view's 7385 * {@link #getImportantForAccessibility()} value: 7386 * <ol> 7387 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7388 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7389 * </code> 7390 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7391 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7392 * view satisfies any of the following: 7393 * <ul> 7394 * <li>Is actionable, e.g. {@link #isClickable()}, 7395 * {@link #isLongClickable()}, or {@link #isFocusable()} 7396 * <li>Has an {@link AccessibilityDelegate} 7397 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7398 * {@link OnKeyListener}, etc. 7399 * <li>Is an accessibility live region, e.g. 7400 * {@link #getAccessibilityLiveRegion()} is not 7401 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7402 * </ul> 7403 * </ol> 7404 * 7405 * @return Whether the view is exposed for accessibility. 7406 * @see #setImportantForAccessibility(int) 7407 * @see #getImportantForAccessibility() 7408 */ 7409 public boolean isImportantForAccessibility() { 7410 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7411 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7412 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7413 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7414 return false; 7415 } 7416 7417 // Check parent mode to ensure we're not hidden. 7418 ViewParent parent = mParent; 7419 while (parent instanceof View) { 7420 if (((View) parent).getImportantForAccessibility() 7421 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7422 return false; 7423 } 7424 parent = parent.getParent(); 7425 } 7426 7427 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7428 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7429 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7430 } 7431 7432 /** 7433 * Gets the parent for accessibility purposes. Note that the parent for 7434 * accessibility is not necessary the immediate parent. It is the first 7435 * predecessor that is important for accessibility. 7436 * 7437 * @return The parent for accessibility purposes. 7438 */ 7439 public ViewParent getParentForAccessibility() { 7440 if (mParent instanceof View) { 7441 View parentView = (View) mParent; 7442 if (parentView.includeForAccessibility()) { 7443 return mParent; 7444 } else { 7445 return mParent.getParentForAccessibility(); 7446 } 7447 } 7448 return null; 7449 } 7450 7451 /** 7452 * Adds the children of a given View for accessibility. Since some Views are 7453 * not important for accessibility the children for accessibility are not 7454 * necessarily direct children of the view, rather they are the first level of 7455 * descendants important for accessibility. 7456 * 7457 * @param children The list of children for accessibility. 7458 */ 7459 public void addChildrenForAccessibility(ArrayList<View> children) { 7460 7461 } 7462 7463 /** 7464 * Whether to regard this view for accessibility. A view is regarded for 7465 * accessibility if it is important for accessibility or the querying 7466 * accessibility service has explicitly requested that view not 7467 * important for accessibility are regarded. 7468 * 7469 * @return Whether to regard the view for accessibility. 7470 * 7471 * @hide 7472 */ 7473 public boolean includeForAccessibility() { 7474 if (mAttachInfo != null) { 7475 return (mAttachInfo.mAccessibilityFetchFlags 7476 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7477 || isImportantForAccessibility(); 7478 } 7479 return false; 7480 } 7481 7482 /** 7483 * Returns whether the View is considered actionable from 7484 * accessibility perspective. Such view are important for 7485 * accessibility. 7486 * 7487 * @return True if the view is actionable for accessibility. 7488 * 7489 * @hide 7490 */ 7491 public boolean isActionableForAccessibility() { 7492 return (isClickable() || isLongClickable() || isFocusable()); 7493 } 7494 7495 /** 7496 * Returns whether the View has registered callbacks which makes it 7497 * important for accessibility. 7498 * 7499 * @return True if the view is actionable for accessibility. 7500 */ 7501 private boolean hasListenersForAccessibility() { 7502 ListenerInfo info = getListenerInfo(); 7503 return mTouchDelegate != null || info.mOnKeyListener != null 7504 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7505 || info.mOnHoverListener != null || info.mOnDragListener != null; 7506 } 7507 7508 /** 7509 * Notifies that the accessibility state of this view changed. The change 7510 * is local to this view and does not represent structural changes such 7511 * as children and parent. For example, the view became focusable. The 7512 * notification is at at most once every 7513 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7514 * to avoid unnecessary load to the system. Also once a view has a pending 7515 * notification this method is a NOP until the notification has been sent. 7516 * 7517 * @hide 7518 */ 7519 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7520 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7521 return; 7522 } 7523 if (mSendViewStateChangedAccessibilityEvent == null) { 7524 mSendViewStateChangedAccessibilityEvent = 7525 new SendViewStateChangedAccessibilityEvent(); 7526 } 7527 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7528 } 7529 7530 /** 7531 * Notifies that the accessibility state of this view changed. The change 7532 * is *not* local to this view and does represent structural changes such 7533 * as children and parent. For example, the view size changed. The 7534 * notification is at at most once every 7535 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7536 * to avoid unnecessary load to the system. Also once a view has a pending 7537 * notifucation this method is a NOP until the notification has been sent. 7538 * 7539 * @hide 7540 */ 7541 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7542 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7543 return; 7544 } 7545 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7546 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7547 if (mParent != null) { 7548 try { 7549 mParent.notifySubtreeAccessibilityStateChanged( 7550 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7551 } catch (AbstractMethodError e) { 7552 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7553 " does not fully implement ViewParent", e); 7554 } 7555 } 7556 } 7557 } 7558 7559 /** 7560 * Reset the flag indicating the accessibility state of the subtree rooted 7561 * at this view changed. 7562 */ 7563 void resetSubtreeAccessibilityStateChanged() { 7564 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7565 } 7566 7567 /** 7568 * Performs the specified accessibility action on the view. For 7569 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7570 * <p> 7571 * If an {@link AccessibilityDelegate} has been specified via calling 7572 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7573 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7574 * is responsible for handling this call. 7575 * </p> 7576 * 7577 * @param action The action to perform. 7578 * @param arguments Optional action arguments. 7579 * @return Whether the action was performed. 7580 */ 7581 public boolean performAccessibilityAction(int action, Bundle arguments) { 7582 if (mAccessibilityDelegate != null) { 7583 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7584 } else { 7585 return performAccessibilityActionInternal(action, arguments); 7586 } 7587 } 7588 7589 /** 7590 * @see #performAccessibilityAction(int, Bundle) 7591 * 7592 * Note: Called from the default {@link AccessibilityDelegate}. 7593 */ 7594 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7595 switch (action) { 7596 case AccessibilityNodeInfo.ACTION_CLICK: { 7597 if (isClickable()) { 7598 performClick(); 7599 return true; 7600 } 7601 } break; 7602 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7603 if (isLongClickable()) { 7604 performLongClick(); 7605 return true; 7606 } 7607 } break; 7608 case AccessibilityNodeInfo.ACTION_FOCUS: { 7609 if (!hasFocus()) { 7610 // Get out of touch mode since accessibility 7611 // wants to move focus around. 7612 getViewRootImpl().ensureTouchMode(false); 7613 return requestFocus(); 7614 } 7615 } break; 7616 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7617 if (hasFocus()) { 7618 clearFocus(); 7619 return !isFocused(); 7620 } 7621 } break; 7622 case AccessibilityNodeInfo.ACTION_SELECT: { 7623 if (!isSelected()) { 7624 setSelected(true); 7625 return isSelected(); 7626 } 7627 } break; 7628 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7629 if (isSelected()) { 7630 setSelected(false); 7631 return !isSelected(); 7632 } 7633 } break; 7634 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7635 if (!isAccessibilityFocused()) { 7636 return requestAccessibilityFocus(); 7637 } 7638 } break; 7639 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7640 if (isAccessibilityFocused()) { 7641 clearAccessibilityFocus(); 7642 return true; 7643 } 7644 } break; 7645 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7646 if (arguments != null) { 7647 final int granularity = arguments.getInt( 7648 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7649 final boolean extendSelection = arguments.getBoolean( 7650 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7651 return traverseAtGranularity(granularity, true, extendSelection); 7652 } 7653 } break; 7654 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7655 if (arguments != null) { 7656 final int granularity = arguments.getInt( 7657 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7658 final boolean extendSelection = arguments.getBoolean( 7659 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7660 return traverseAtGranularity(granularity, false, extendSelection); 7661 } 7662 } break; 7663 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7664 CharSequence text = getIterableTextForAccessibility(); 7665 if (text == null) { 7666 return false; 7667 } 7668 final int start = (arguments != null) ? arguments.getInt( 7669 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7670 final int end = (arguments != null) ? arguments.getInt( 7671 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7672 // Only cursor position can be specified (selection length == 0) 7673 if ((getAccessibilitySelectionStart() != start 7674 || getAccessibilitySelectionEnd() != end) 7675 && (start == end)) { 7676 setAccessibilitySelection(start, end); 7677 notifyViewAccessibilityStateChangedIfNeeded( 7678 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7679 return true; 7680 } 7681 } break; 7682 } 7683 return false; 7684 } 7685 7686 private boolean traverseAtGranularity(int granularity, boolean forward, 7687 boolean extendSelection) { 7688 CharSequence text = getIterableTextForAccessibility(); 7689 if (text == null || text.length() == 0) { 7690 return false; 7691 } 7692 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7693 if (iterator == null) { 7694 return false; 7695 } 7696 int current = getAccessibilitySelectionEnd(); 7697 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7698 current = forward ? 0 : text.length(); 7699 } 7700 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7701 if (range == null) { 7702 return false; 7703 } 7704 final int segmentStart = range[0]; 7705 final int segmentEnd = range[1]; 7706 int selectionStart; 7707 int selectionEnd; 7708 if (extendSelection && isAccessibilitySelectionExtendable()) { 7709 selectionStart = getAccessibilitySelectionStart(); 7710 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7711 selectionStart = forward ? segmentStart : segmentEnd; 7712 } 7713 selectionEnd = forward ? segmentEnd : segmentStart; 7714 } else { 7715 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7716 } 7717 setAccessibilitySelection(selectionStart, selectionEnd); 7718 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7719 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7720 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7721 return true; 7722 } 7723 7724 /** 7725 * Gets the text reported for accessibility purposes. 7726 * 7727 * @return The accessibility text. 7728 * 7729 * @hide 7730 */ 7731 public CharSequence getIterableTextForAccessibility() { 7732 return getContentDescription(); 7733 } 7734 7735 /** 7736 * Gets whether accessibility selection can be extended. 7737 * 7738 * @return If selection is extensible. 7739 * 7740 * @hide 7741 */ 7742 public boolean isAccessibilitySelectionExtendable() { 7743 return false; 7744 } 7745 7746 /** 7747 * @hide 7748 */ 7749 public int getAccessibilitySelectionStart() { 7750 return mAccessibilityCursorPosition; 7751 } 7752 7753 /** 7754 * @hide 7755 */ 7756 public int getAccessibilitySelectionEnd() { 7757 return getAccessibilitySelectionStart(); 7758 } 7759 7760 /** 7761 * @hide 7762 */ 7763 public void setAccessibilitySelection(int start, int end) { 7764 if (start == end && end == mAccessibilityCursorPosition) { 7765 return; 7766 } 7767 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7768 mAccessibilityCursorPosition = start; 7769 } else { 7770 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7771 } 7772 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7773 } 7774 7775 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7776 int fromIndex, int toIndex) { 7777 if (mParent == null) { 7778 return; 7779 } 7780 AccessibilityEvent event = AccessibilityEvent.obtain( 7781 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7782 onInitializeAccessibilityEvent(event); 7783 onPopulateAccessibilityEvent(event); 7784 event.setFromIndex(fromIndex); 7785 event.setToIndex(toIndex); 7786 event.setAction(action); 7787 event.setMovementGranularity(granularity); 7788 mParent.requestSendAccessibilityEvent(this, event); 7789 } 7790 7791 /** 7792 * @hide 7793 */ 7794 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7795 switch (granularity) { 7796 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7797 CharSequence text = getIterableTextForAccessibility(); 7798 if (text != null && text.length() > 0) { 7799 CharacterTextSegmentIterator iterator = 7800 CharacterTextSegmentIterator.getInstance( 7801 mContext.getResources().getConfiguration().locale); 7802 iterator.initialize(text.toString()); 7803 return iterator; 7804 } 7805 } break; 7806 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7807 CharSequence text = getIterableTextForAccessibility(); 7808 if (text != null && text.length() > 0) { 7809 WordTextSegmentIterator iterator = 7810 WordTextSegmentIterator.getInstance( 7811 mContext.getResources().getConfiguration().locale); 7812 iterator.initialize(text.toString()); 7813 return iterator; 7814 } 7815 } break; 7816 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7817 CharSequence text = getIterableTextForAccessibility(); 7818 if (text != null && text.length() > 0) { 7819 ParagraphTextSegmentIterator iterator = 7820 ParagraphTextSegmentIterator.getInstance(); 7821 iterator.initialize(text.toString()); 7822 return iterator; 7823 } 7824 } break; 7825 } 7826 return null; 7827 } 7828 7829 /** 7830 * @hide 7831 */ 7832 public void dispatchStartTemporaryDetach() { 7833 clearDisplayList(); 7834 7835 onStartTemporaryDetach(); 7836 } 7837 7838 /** 7839 * This is called when a container is going to temporarily detach a child, with 7840 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7841 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7842 * {@link #onDetachedFromWindow()} when the container is done. 7843 */ 7844 public void onStartTemporaryDetach() { 7845 removeUnsetPressCallback(); 7846 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7847 } 7848 7849 /** 7850 * @hide 7851 */ 7852 public void dispatchFinishTemporaryDetach() { 7853 onFinishTemporaryDetach(); 7854 } 7855 7856 /** 7857 * Called after {@link #onStartTemporaryDetach} when the container is done 7858 * changing the view. 7859 */ 7860 public void onFinishTemporaryDetach() { 7861 } 7862 7863 /** 7864 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7865 * for this view's window. Returns null if the view is not currently attached 7866 * to the window. Normally you will not need to use this directly, but 7867 * just use the standard high-level event callbacks like 7868 * {@link #onKeyDown(int, KeyEvent)}. 7869 */ 7870 public KeyEvent.DispatcherState getKeyDispatcherState() { 7871 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7872 } 7873 7874 /** 7875 * Dispatch a key event before it is processed by any input method 7876 * associated with the view hierarchy. This can be used to intercept 7877 * key events in special situations before the IME consumes them; a 7878 * typical example would be handling the BACK key to update the application's 7879 * UI instead of allowing the IME to see it and close itself. 7880 * 7881 * @param event The key event to be dispatched. 7882 * @return True if the event was handled, false otherwise. 7883 */ 7884 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7885 return onKeyPreIme(event.getKeyCode(), event); 7886 } 7887 7888 /** 7889 * Dispatch a key event to the next view on the focus path. This path runs 7890 * from the top of the view tree down to the currently focused view. If this 7891 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7892 * the next node down the focus path. This method also fires any key 7893 * listeners. 7894 * 7895 * @param event The key event to be dispatched. 7896 * @return True if the event was handled, false otherwise. 7897 */ 7898 public boolean dispatchKeyEvent(KeyEvent event) { 7899 if (mInputEventConsistencyVerifier != null) { 7900 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7901 } 7902 7903 // Give any attached key listener a first crack at the event. 7904 //noinspection SimplifiableIfStatement 7905 ListenerInfo li = mListenerInfo; 7906 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7907 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7908 return true; 7909 } 7910 7911 if (event.dispatch(this, mAttachInfo != null 7912 ? mAttachInfo.mKeyDispatchState : null, this)) { 7913 return true; 7914 } 7915 7916 if (mInputEventConsistencyVerifier != null) { 7917 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7918 } 7919 return false; 7920 } 7921 7922 /** 7923 * Dispatches a key shortcut event. 7924 * 7925 * @param event The key event to be dispatched. 7926 * @return True if the event was handled by the view, false otherwise. 7927 */ 7928 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7929 return onKeyShortcut(event.getKeyCode(), event); 7930 } 7931 7932 /** 7933 * Pass the touch screen motion event down to the target view, or this 7934 * view if it is the target. 7935 * 7936 * @param event The motion event to be dispatched. 7937 * @return True if the event was handled by the view, false otherwise. 7938 */ 7939 public boolean dispatchTouchEvent(MotionEvent event) { 7940 if (mInputEventConsistencyVerifier != null) { 7941 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7942 } 7943 7944 if (onFilterTouchEventForSecurity(event)) { 7945 //noinspection SimplifiableIfStatement 7946 ListenerInfo li = mListenerInfo; 7947 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7948 && li.mOnTouchListener.onTouch(this, event)) { 7949 return true; 7950 } 7951 7952 if (onTouchEvent(event)) { 7953 return true; 7954 } 7955 } 7956 7957 if (mInputEventConsistencyVerifier != null) { 7958 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7959 } 7960 return false; 7961 } 7962 7963 /** 7964 * Filter the touch event to apply security policies. 7965 * 7966 * @param event The motion event to be filtered. 7967 * @return True if the event should be dispatched, false if the event should be dropped. 7968 * 7969 * @see #getFilterTouchesWhenObscured 7970 */ 7971 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 7972 //noinspection RedundantIfStatement 7973 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 7974 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 7975 // Window is obscured, drop this touch. 7976 return false; 7977 } 7978 return true; 7979 } 7980 7981 /** 7982 * Pass a trackball motion event down to the focused view. 7983 * 7984 * @param event The motion event to be dispatched. 7985 * @return True if the event was handled by the view, false otherwise. 7986 */ 7987 public boolean dispatchTrackballEvent(MotionEvent event) { 7988 if (mInputEventConsistencyVerifier != null) { 7989 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 7990 } 7991 7992 return onTrackballEvent(event); 7993 } 7994 7995 /** 7996 * Dispatch a generic motion event. 7997 * <p> 7998 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 7999 * are delivered to the view under the pointer. All other generic motion events are 8000 * delivered to the focused view. Hover events are handled specially and are delivered 8001 * to {@link #onHoverEvent(MotionEvent)}. 8002 * </p> 8003 * 8004 * @param event The motion event to be dispatched. 8005 * @return True if the event was handled by the view, false otherwise. 8006 */ 8007 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8008 if (mInputEventConsistencyVerifier != null) { 8009 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8010 } 8011 8012 final int source = event.getSource(); 8013 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8014 final int action = event.getAction(); 8015 if (action == MotionEvent.ACTION_HOVER_ENTER 8016 || action == MotionEvent.ACTION_HOVER_MOVE 8017 || action == MotionEvent.ACTION_HOVER_EXIT) { 8018 if (dispatchHoverEvent(event)) { 8019 return true; 8020 } 8021 } else if (dispatchGenericPointerEvent(event)) { 8022 return true; 8023 } 8024 } else if (dispatchGenericFocusedEvent(event)) { 8025 return true; 8026 } 8027 8028 if (dispatchGenericMotionEventInternal(event)) { 8029 return true; 8030 } 8031 8032 if (mInputEventConsistencyVerifier != null) { 8033 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8034 } 8035 return false; 8036 } 8037 8038 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8039 //noinspection SimplifiableIfStatement 8040 ListenerInfo li = mListenerInfo; 8041 if (li != null && li.mOnGenericMotionListener != null 8042 && (mViewFlags & ENABLED_MASK) == ENABLED 8043 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8044 return true; 8045 } 8046 8047 if (onGenericMotionEvent(event)) { 8048 return true; 8049 } 8050 8051 if (mInputEventConsistencyVerifier != null) { 8052 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8053 } 8054 return false; 8055 } 8056 8057 /** 8058 * Dispatch a hover event. 8059 * <p> 8060 * Do not call this method directly. 8061 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8062 * </p> 8063 * 8064 * @param event The motion event to be dispatched. 8065 * @return True if the event was handled by the view, false otherwise. 8066 */ 8067 protected boolean dispatchHoverEvent(MotionEvent event) { 8068 ListenerInfo li = mListenerInfo; 8069 //noinspection SimplifiableIfStatement 8070 if (li != null && li.mOnHoverListener != null 8071 && (mViewFlags & ENABLED_MASK) == ENABLED 8072 && li.mOnHoverListener.onHover(this, event)) { 8073 return true; 8074 } 8075 8076 return onHoverEvent(event); 8077 } 8078 8079 /** 8080 * Returns true if the view has a child to which it has recently sent 8081 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8082 * it does not have a hovered child, then it must be the innermost hovered view. 8083 * @hide 8084 */ 8085 protected boolean hasHoveredChild() { 8086 return false; 8087 } 8088 8089 /** 8090 * Dispatch a generic motion event to the view under the first pointer. 8091 * <p> 8092 * Do not call this method directly. 8093 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8094 * </p> 8095 * 8096 * @param event The motion event to be dispatched. 8097 * @return True if the event was handled by the view, false otherwise. 8098 */ 8099 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8100 return false; 8101 } 8102 8103 /** 8104 * Dispatch a generic motion event to the currently focused view. 8105 * <p> 8106 * Do not call this method directly. 8107 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8108 * </p> 8109 * 8110 * @param event The motion event to be dispatched. 8111 * @return True if the event was handled by the view, false otherwise. 8112 */ 8113 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8114 return false; 8115 } 8116 8117 /** 8118 * Dispatch a pointer event. 8119 * <p> 8120 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8121 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8122 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8123 * and should not be expected to handle other pointing device features. 8124 * </p> 8125 * 8126 * @param event The motion event to be dispatched. 8127 * @return True if the event was handled by the view, false otherwise. 8128 * @hide 8129 */ 8130 public final boolean dispatchPointerEvent(MotionEvent event) { 8131 if (event.isTouchEvent()) { 8132 return dispatchTouchEvent(event); 8133 } else { 8134 return dispatchGenericMotionEvent(event); 8135 } 8136 } 8137 8138 /** 8139 * Called when the window containing this view gains or loses window focus. 8140 * ViewGroups should override to route to their children. 8141 * 8142 * @param hasFocus True if the window containing this view now has focus, 8143 * false otherwise. 8144 */ 8145 public void dispatchWindowFocusChanged(boolean hasFocus) { 8146 onWindowFocusChanged(hasFocus); 8147 } 8148 8149 /** 8150 * Called when the window containing this view gains or loses focus. Note 8151 * that this is separate from view focus: to receive key events, both 8152 * your view and its window must have focus. If a window is displayed 8153 * on top of yours that takes input focus, then your own window will lose 8154 * focus but the view focus will remain unchanged. 8155 * 8156 * @param hasWindowFocus True if the window containing this view now has 8157 * focus, false otherwise. 8158 */ 8159 public void onWindowFocusChanged(boolean hasWindowFocus) { 8160 InputMethodManager imm = InputMethodManager.peekInstance(); 8161 if (!hasWindowFocus) { 8162 if (isPressed()) { 8163 setPressed(false); 8164 } 8165 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8166 imm.focusOut(this); 8167 } 8168 removeLongPressCallback(); 8169 removeTapCallback(); 8170 onFocusLost(); 8171 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8172 imm.focusIn(this); 8173 } 8174 refreshDrawableState(); 8175 } 8176 8177 /** 8178 * Returns true if this view is in a window that currently has window focus. 8179 * Note that this is not the same as the view itself having focus. 8180 * 8181 * @return True if this view is in a window that currently has window focus. 8182 */ 8183 public boolean hasWindowFocus() { 8184 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8185 } 8186 8187 /** 8188 * Dispatch a view visibility change down the view hierarchy. 8189 * ViewGroups should override to route to their children. 8190 * @param changedView The view whose visibility changed. Could be 'this' or 8191 * an ancestor view. 8192 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8193 * {@link #INVISIBLE} or {@link #GONE}. 8194 */ 8195 protected void dispatchVisibilityChanged(@NonNull View changedView, 8196 @Visibility int visibility) { 8197 onVisibilityChanged(changedView, visibility); 8198 } 8199 8200 /** 8201 * Called when the visibility of the view or an ancestor of the view is changed. 8202 * @param changedView The view whose visibility changed. Could be 'this' or 8203 * an ancestor view. 8204 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8205 * {@link #INVISIBLE} or {@link #GONE}. 8206 */ 8207 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8208 if (visibility == VISIBLE) { 8209 if (mAttachInfo != null) { 8210 initialAwakenScrollBars(); 8211 } else { 8212 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8213 } 8214 } 8215 } 8216 8217 /** 8218 * Dispatch a hint about whether this view is displayed. For instance, when 8219 * a View moves out of the screen, it might receives a display hint indicating 8220 * the view is not displayed. Applications should not <em>rely</em> on this hint 8221 * as there is no guarantee that they will receive one. 8222 * 8223 * @param hint A hint about whether or not this view is displayed: 8224 * {@link #VISIBLE} or {@link #INVISIBLE}. 8225 */ 8226 public void dispatchDisplayHint(@Visibility int hint) { 8227 onDisplayHint(hint); 8228 } 8229 8230 /** 8231 * Gives this view a hint about whether is displayed or not. For instance, when 8232 * a View moves out of the screen, it might receives a display hint indicating 8233 * the view is not displayed. Applications should not <em>rely</em> on this hint 8234 * as there is no guarantee that they will receive one. 8235 * 8236 * @param hint A hint about whether or not this view is displayed: 8237 * {@link #VISIBLE} or {@link #INVISIBLE}. 8238 */ 8239 protected void onDisplayHint(@Visibility int hint) { 8240 } 8241 8242 /** 8243 * Dispatch a window visibility change down the view hierarchy. 8244 * ViewGroups should override to route to their children. 8245 * 8246 * @param visibility The new visibility of the window. 8247 * 8248 * @see #onWindowVisibilityChanged(int) 8249 */ 8250 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8251 onWindowVisibilityChanged(visibility); 8252 } 8253 8254 /** 8255 * Called when the window containing has change its visibility 8256 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8257 * that this tells you whether or not your window is being made visible 8258 * to the window manager; this does <em>not</em> tell you whether or not 8259 * your window is obscured by other windows on the screen, even if it 8260 * is itself visible. 8261 * 8262 * @param visibility The new visibility of the window. 8263 */ 8264 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8265 if (visibility == VISIBLE) { 8266 initialAwakenScrollBars(); 8267 } 8268 } 8269 8270 /** 8271 * Returns the current visibility of the window this view is attached to 8272 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8273 * 8274 * @return Returns the current visibility of the view's window. 8275 */ 8276 @Visibility 8277 public int getWindowVisibility() { 8278 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8279 } 8280 8281 /** 8282 * Retrieve the overall visible display size in which the window this view is 8283 * attached to has been positioned in. This takes into account screen 8284 * decorations above the window, for both cases where the window itself 8285 * is being position inside of them or the window is being placed under 8286 * then and covered insets are used for the window to position its content 8287 * inside. In effect, this tells you the available area where content can 8288 * be placed and remain visible to users. 8289 * 8290 * <p>This function requires an IPC back to the window manager to retrieve 8291 * the requested information, so should not be used in performance critical 8292 * code like drawing. 8293 * 8294 * @param outRect Filled in with the visible display frame. If the view 8295 * is not attached to a window, this is simply the raw display size. 8296 */ 8297 public void getWindowVisibleDisplayFrame(Rect outRect) { 8298 if (mAttachInfo != null) { 8299 try { 8300 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8301 } catch (RemoteException e) { 8302 return; 8303 } 8304 // XXX This is really broken, and probably all needs to be done 8305 // in the window manager, and we need to know more about whether 8306 // we want the area behind or in front of the IME. 8307 final Rect insets = mAttachInfo.mVisibleInsets; 8308 outRect.left += insets.left; 8309 outRect.top += insets.top; 8310 outRect.right -= insets.right; 8311 outRect.bottom -= insets.bottom; 8312 return; 8313 } 8314 // The view is not attached to a display so we don't have a context. 8315 // Make a best guess about the display size. 8316 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8317 d.getRectSize(outRect); 8318 } 8319 8320 /** 8321 * Dispatch a notification about a resource configuration change down 8322 * the view hierarchy. 8323 * ViewGroups should override to route to their children. 8324 * 8325 * @param newConfig The new resource configuration. 8326 * 8327 * @see #onConfigurationChanged(android.content.res.Configuration) 8328 */ 8329 public void dispatchConfigurationChanged(Configuration newConfig) { 8330 onConfigurationChanged(newConfig); 8331 } 8332 8333 /** 8334 * Called when the current configuration of the resources being used 8335 * by the application have changed. You can use this to decide when 8336 * to reload resources that can changed based on orientation and other 8337 * configuration characterstics. You only need to use this if you are 8338 * not relying on the normal {@link android.app.Activity} mechanism of 8339 * recreating the activity instance upon a configuration change. 8340 * 8341 * @param newConfig The new resource configuration. 8342 */ 8343 protected void onConfigurationChanged(Configuration newConfig) { 8344 } 8345 8346 /** 8347 * Private function to aggregate all per-view attributes in to the view 8348 * root. 8349 */ 8350 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8351 performCollectViewAttributes(attachInfo, visibility); 8352 } 8353 8354 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8355 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8356 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8357 attachInfo.mKeepScreenOn = true; 8358 } 8359 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8360 ListenerInfo li = mListenerInfo; 8361 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8362 attachInfo.mHasSystemUiListeners = true; 8363 } 8364 } 8365 } 8366 8367 void needGlobalAttributesUpdate(boolean force) { 8368 final AttachInfo ai = mAttachInfo; 8369 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8370 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8371 || ai.mHasSystemUiListeners) { 8372 ai.mRecomputeGlobalAttributes = true; 8373 } 8374 } 8375 } 8376 8377 /** 8378 * Returns whether the device is currently in touch mode. Touch mode is entered 8379 * once the user begins interacting with the device by touch, and affects various 8380 * things like whether focus is always visible to the user. 8381 * 8382 * @return Whether the device is in touch mode. 8383 */ 8384 @ViewDebug.ExportedProperty 8385 public boolean isInTouchMode() { 8386 if (mAttachInfo != null) { 8387 return mAttachInfo.mInTouchMode; 8388 } else { 8389 return ViewRootImpl.isInTouchMode(); 8390 } 8391 } 8392 8393 /** 8394 * Returns the context the view is running in, through which it can 8395 * access the current theme, resources, etc. 8396 * 8397 * @return The view's Context. 8398 */ 8399 @ViewDebug.CapturedViewProperty 8400 public final Context getContext() { 8401 return mContext; 8402 } 8403 8404 /** 8405 * Handle a key event before it is processed by any input method 8406 * associated with the view hierarchy. This can be used to intercept 8407 * key events in special situations before the IME consumes them; a 8408 * typical example would be handling the BACK key to update the application's 8409 * UI instead of allowing the IME to see it and close itself. 8410 * 8411 * @param keyCode The value in event.getKeyCode(). 8412 * @param event Description of the key event. 8413 * @return If you handled the event, return true. If you want to allow the 8414 * event to be handled by the next receiver, return false. 8415 */ 8416 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8417 return false; 8418 } 8419 8420 /** 8421 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8422 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8423 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8424 * is released, if the view is enabled and clickable. 8425 * 8426 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8427 * although some may elect to do so in some situations. Do not rely on this to 8428 * catch software key presses. 8429 * 8430 * @param keyCode A key code that represents the button pressed, from 8431 * {@link android.view.KeyEvent}. 8432 * @param event The KeyEvent object that defines the button action. 8433 */ 8434 public boolean onKeyDown(int keyCode, KeyEvent event) { 8435 boolean result = false; 8436 8437 if (KeyEvent.isConfirmKey(keyCode)) { 8438 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8439 return true; 8440 } 8441 // Long clickable items don't necessarily have to be clickable 8442 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8443 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8444 (event.getRepeatCount() == 0)) { 8445 setPressed(true); 8446 checkForLongClick(0); 8447 return true; 8448 } 8449 } 8450 return result; 8451 } 8452 8453 /** 8454 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8455 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8456 * the event). 8457 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8458 * although some may elect to do so in some situations. Do not rely on this to 8459 * catch software key presses. 8460 */ 8461 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8462 return false; 8463 } 8464 8465 /** 8466 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8467 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8468 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8469 * {@link KeyEvent#KEYCODE_ENTER} is released. 8470 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8471 * although some may elect to do so in some situations. Do not rely on this to 8472 * catch software key presses. 8473 * 8474 * @param keyCode A key code that represents the button pressed, from 8475 * {@link android.view.KeyEvent}. 8476 * @param event The KeyEvent object that defines the button action. 8477 */ 8478 public boolean onKeyUp(int keyCode, KeyEvent event) { 8479 if (KeyEvent.isConfirmKey(keyCode)) { 8480 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8481 return true; 8482 } 8483 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8484 setPressed(false); 8485 8486 if (!mHasPerformedLongPress) { 8487 // This is a tap, so remove the longpress check 8488 removeLongPressCallback(); 8489 return performClick(); 8490 } 8491 } 8492 } 8493 return false; 8494 } 8495 8496 /** 8497 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8498 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8499 * the event). 8500 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8501 * although some may elect to do so in some situations. Do not rely on this to 8502 * catch software key presses. 8503 * 8504 * @param keyCode A key code that represents the button pressed, from 8505 * {@link android.view.KeyEvent}. 8506 * @param repeatCount The number of times the action was made. 8507 * @param event The KeyEvent object that defines the button action. 8508 */ 8509 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8510 return false; 8511 } 8512 8513 /** 8514 * Called on the focused view when a key shortcut event is not handled. 8515 * Override this method to implement local key shortcuts for the View. 8516 * Key shortcuts can also be implemented by setting the 8517 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8518 * 8519 * @param keyCode The value in event.getKeyCode(). 8520 * @param event Description of the key event. 8521 * @return If you handled the event, return true. If you want to allow the 8522 * event to be handled by the next receiver, return false. 8523 */ 8524 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8525 return false; 8526 } 8527 8528 /** 8529 * Check whether the called view is a text editor, in which case it 8530 * would make sense to automatically display a soft input window for 8531 * it. Subclasses should override this if they implement 8532 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8533 * a call on that method would return a non-null InputConnection, and 8534 * they are really a first-class editor that the user would normally 8535 * start typing on when the go into a window containing your view. 8536 * 8537 * <p>The default implementation always returns false. This does 8538 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8539 * will not be called or the user can not otherwise perform edits on your 8540 * view; it is just a hint to the system that this is not the primary 8541 * purpose of this view. 8542 * 8543 * @return Returns true if this view is a text editor, else false. 8544 */ 8545 public boolean onCheckIsTextEditor() { 8546 return false; 8547 } 8548 8549 /** 8550 * Create a new InputConnection for an InputMethod to interact 8551 * with the view. The default implementation returns null, since it doesn't 8552 * support input methods. You can override this to implement such support. 8553 * This is only needed for views that take focus and text input. 8554 * 8555 * <p>When implementing this, you probably also want to implement 8556 * {@link #onCheckIsTextEditor()} to indicate you will return a 8557 * non-null InputConnection. 8558 * 8559 * @param outAttrs Fill in with attribute information about the connection. 8560 */ 8561 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8562 return null; 8563 } 8564 8565 /** 8566 * Called by the {@link android.view.inputmethod.InputMethodManager} 8567 * when a view who is not the current 8568 * input connection target is trying to make a call on the manager. The 8569 * default implementation returns false; you can override this to return 8570 * true for certain views if you are performing InputConnection proxying 8571 * to them. 8572 * @param view The View that is making the InputMethodManager call. 8573 * @return Return true to allow the call, false to reject. 8574 */ 8575 public boolean checkInputConnectionProxy(View view) { 8576 return false; 8577 } 8578 8579 /** 8580 * Show the context menu for this view. It is not safe to hold on to the 8581 * menu after returning from this method. 8582 * 8583 * You should normally not overload this method. Overload 8584 * {@link #onCreateContextMenu(ContextMenu)} or define an 8585 * {@link OnCreateContextMenuListener} to add items to the context menu. 8586 * 8587 * @param menu The context menu to populate 8588 */ 8589 public void createContextMenu(ContextMenu menu) { 8590 ContextMenuInfo menuInfo = getContextMenuInfo(); 8591 8592 // Sets the current menu info so all items added to menu will have 8593 // my extra info set. 8594 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8595 8596 onCreateContextMenu(menu); 8597 ListenerInfo li = mListenerInfo; 8598 if (li != null && li.mOnCreateContextMenuListener != null) { 8599 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8600 } 8601 8602 // Clear the extra information so subsequent items that aren't mine don't 8603 // have my extra info. 8604 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8605 8606 if (mParent != null) { 8607 mParent.createContextMenu(menu); 8608 } 8609 } 8610 8611 /** 8612 * Views should implement this if they have extra information to associate 8613 * with the context menu. The return result is supplied as a parameter to 8614 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8615 * callback. 8616 * 8617 * @return Extra information about the item for which the context menu 8618 * should be shown. This information will vary across different 8619 * subclasses of View. 8620 */ 8621 protected ContextMenuInfo getContextMenuInfo() { 8622 return null; 8623 } 8624 8625 /** 8626 * Views should implement this if the view itself is going to add items to 8627 * the context menu. 8628 * 8629 * @param menu the context menu to populate 8630 */ 8631 protected void onCreateContextMenu(ContextMenu menu) { 8632 } 8633 8634 /** 8635 * Implement this method to handle trackball motion events. The 8636 * <em>relative</em> movement of the trackball since the last event 8637 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8638 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8639 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8640 * they will often be fractional values, representing the more fine-grained 8641 * movement information available from a trackball). 8642 * 8643 * @param event The motion event. 8644 * @return True if the event was handled, false otherwise. 8645 */ 8646 public boolean onTrackballEvent(MotionEvent event) { 8647 return false; 8648 } 8649 8650 /** 8651 * Implement this method to handle generic motion events. 8652 * <p> 8653 * Generic motion events describe joystick movements, mouse hovers, track pad 8654 * touches, scroll wheel movements and other input events. The 8655 * {@link MotionEvent#getSource() source} of the motion event specifies 8656 * the class of input that was received. Implementations of this method 8657 * must examine the bits in the source before processing the event. 8658 * The following code example shows how this is done. 8659 * </p><p> 8660 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8661 * are delivered to the view under the pointer. All other generic motion events are 8662 * delivered to the focused view. 8663 * </p> 8664 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8665 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8666 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8667 * // process the joystick movement... 8668 * return true; 8669 * } 8670 * } 8671 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8672 * switch (event.getAction()) { 8673 * case MotionEvent.ACTION_HOVER_MOVE: 8674 * // process the mouse hover movement... 8675 * return true; 8676 * case MotionEvent.ACTION_SCROLL: 8677 * // process the scroll wheel movement... 8678 * return true; 8679 * } 8680 * } 8681 * return super.onGenericMotionEvent(event); 8682 * }</pre> 8683 * 8684 * @param event The generic motion event being processed. 8685 * @return True if the event was handled, false otherwise. 8686 */ 8687 public boolean onGenericMotionEvent(MotionEvent event) { 8688 return false; 8689 } 8690 8691 /** 8692 * Implement this method to handle hover events. 8693 * <p> 8694 * This method is called whenever a pointer is hovering into, over, or out of the 8695 * bounds of a view and the view is not currently being touched. 8696 * Hover events are represented as pointer events with action 8697 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8698 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8699 * </p> 8700 * <ul> 8701 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8702 * when the pointer enters the bounds of the view.</li> 8703 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8704 * when the pointer has already entered the bounds of the view and has moved.</li> 8705 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8706 * when the pointer has exited the bounds of the view or when the pointer is 8707 * about to go down due to a button click, tap, or similar user action that 8708 * causes the view to be touched.</li> 8709 * </ul> 8710 * <p> 8711 * The view should implement this method to return true to indicate that it is 8712 * handling the hover event, such as by changing its drawable state. 8713 * </p><p> 8714 * The default implementation calls {@link #setHovered} to update the hovered state 8715 * of the view when a hover enter or hover exit event is received, if the view 8716 * is enabled and is clickable. The default implementation also sends hover 8717 * accessibility events. 8718 * </p> 8719 * 8720 * @param event The motion event that describes the hover. 8721 * @return True if the view handled the hover event. 8722 * 8723 * @see #isHovered 8724 * @see #setHovered 8725 * @see #onHoverChanged 8726 */ 8727 public boolean onHoverEvent(MotionEvent event) { 8728 // The root view may receive hover (or touch) events that are outside the bounds of 8729 // the window. This code ensures that we only send accessibility events for 8730 // hovers that are actually within the bounds of the root view. 8731 final int action = event.getActionMasked(); 8732 if (!mSendingHoverAccessibilityEvents) { 8733 if ((action == MotionEvent.ACTION_HOVER_ENTER 8734 || action == MotionEvent.ACTION_HOVER_MOVE) 8735 && !hasHoveredChild() 8736 && pointInView(event.getX(), event.getY())) { 8737 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8738 mSendingHoverAccessibilityEvents = true; 8739 } 8740 } else { 8741 if (action == MotionEvent.ACTION_HOVER_EXIT 8742 || (action == MotionEvent.ACTION_MOVE 8743 && !pointInView(event.getX(), event.getY()))) { 8744 mSendingHoverAccessibilityEvents = false; 8745 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8746 // If the window does not have input focus we take away accessibility 8747 // focus as soon as the user stop hovering over the view. 8748 if (mAttachInfo != null && !mAttachInfo.mHasWindowFocus) { 8749 getViewRootImpl().setAccessibilityFocus(null, null); 8750 } 8751 } 8752 } 8753 8754 if (isHoverable()) { 8755 switch (action) { 8756 case MotionEvent.ACTION_HOVER_ENTER: 8757 setHovered(true); 8758 break; 8759 case MotionEvent.ACTION_HOVER_EXIT: 8760 setHovered(false); 8761 break; 8762 } 8763 8764 // Dispatch the event to onGenericMotionEvent before returning true. 8765 // This is to provide compatibility with existing applications that 8766 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8767 // break because of the new default handling for hoverable views 8768 // in onHoverEvent. 8769 // Note that onGenericMotionEvent will be called by default when 8770 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8771 dispatchGenericMotionEventInternal(event); 8772 // The event was already handled by calling setHovered(), so always 8773 // return true. 8774 return true; 8775 } 8776 8777 return false; 8778 } 8779 8780 /** 8781 * Returns true if the view should handle {@link #onHoverEvent} 8782 * by calling {@link #setHovered} to change its hovered state. 8783 * 8784 * @return True if the view is hoverable. 8785 */ 8786 private boolean isHoverable() { 8787 final int viewFlags = mViewFlags; 8788 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8789 return false; 8790 } 8791 8792 return (viewFlags & CLICKABLE) == CLICKABLE 8793 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8794 } 8795 8796 /** 8797 * Returns true if the view is currently hovered. 8798 * 8799 * @return True if the view is currently hovered. 8800 * 8801 * @see #setHovered 8802 * @see #onHoverChanged 8803 */ 8804 @ViewDebug.ExportedProperty 8805 public boolean isHovered() { 8806 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8807 } 8808 8809 /** 8810 * Sets whether the view is currently hovered. 8811 * <p> 8812 * Calling this method also changes the drawable state of the view. This 8813 * enables the view to react to hover by using different drawable resources 8814 * to change its appearance. 8815 * </p><p> 8816 * The {@link #onHoverChanged} method is called when the hovered state changes. 8817 * </p> 8818 * 8819 * @param hovered True if the view is hovered. 8820 * 8821 * @see #isHovered 8822 * @see #onHoverChanged 8823 */ 8824 public void setHovered(boolean hovered) { 8825 if (hovered) { 8826 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8827 mPrivateFlags |= PFLAG_HOVERED; 8828 refreshDrawableState(); 8829 onHoverChanged(true); 8830 } 8831 } else { 8832 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8833 mPrivateFlags &= ~PFLAG_HOVERED; 8834 refreshDrawableState(); 8835 onHoverChanged(false); 8836 } 8837 } 8838 } 8839 8840 /** 8841 * Implement this method to handle hover state changes. 8842 * <p> 8843 * This method is called whenever the hover state changes as a result of a 8844 * call to {@link #setHovered}. 8845 * </p> 8846 * 8847 * @param hovered The current hover state, as returned by {@link #isHovered}. 8848 * 8849 * @see #isHovered 8850 * @see #setHovered 8851 */ 8852 public void onHoverChanged(boolean hovered) { 8853 } 8854 8855 /** 8856 * Implement this method to handle touch screen motion events. 8857 * <p> 8858 * If this method is used to detect click actions, it is recommended that 8859 * the actions be performed by implementing and calling 8860 * {@link #performClick()}. This will ensure consistent system behavior, 8861 * including: 8862 * <ul> 8863 * <li>obeying click sound preferences 8864 * <li>dispatching OnClickListener calls 8865 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8866 * accessibility features are enabled 8867 * </ul> 8868 * 8869 * @param event The motion event. 8870 * @return True if the event was handled, false otherwise. 8871 */ 8872 public boolean onTouchEvent(MotionEvent event) { 8873 final int viewFlags = mViewFlags; 8874 8875 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8876 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8877 setPressed(false); 8878 } 8879 // A disabled view that is clickable still consumes the touch 8880 // events, it just doesn't respond to them. 8881 return (((viewFlags & CLICKABLE) == CLICKABLE || 8882 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8883 } 8884 8885 if (mTouchDelegate != null) { 8886 if (mTouchDelegate.onTouchEvent(event)) { 8887 return true; 8888 } 8889 } 8890 8891 if (((viewFlags & CLICKABLE) == CLICKABLE || 8892 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8893 switch (event.getAction()) { 8894 case MotionEvent.ACTION_UP: 8895 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8896 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8897 // take focus if we don't have it already and we should in 8898 // touch mode. 8899 boolean focusTaken = false; 8900 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8901 focusTaken = requestFocus(); 8902 } 8903 8904 if (prepressed) { 8905 // The button is being released before we actually 8906 // showed it as pressed. Make it show the pressed 8907 // state now (before scheduling the click) to ensure 8908 // the user sees it. 8909 setPressed(true); 8910 } 8911 8912 if (!mHasPerformedLongPress) { 8913 // This is a tap, so remove the longpress check 8914 removeLongPressCallback(); 8915 8916 // Only perform take click actions if we were in the pressed state 8917 if (!focusTaken) { 8918 // Use a Runnable and post this rather than calling 8919 // performClick directly. This lets other visual state 8920 // of the view update before click actions start. 8921 if (mPerformClick == null) { 8922 mPerformClick = new PerformClick(); 8923 } 8924 if (!post(mPerformClick)) { 8925 performClick(); 8926 } 8927 } 8928 } 8929 8930 if (mUnsetPressedState == null) { 8931 mUnsetPressedState = new UnsetPressedState(); 8932 } 8933 8934 if (prepressed) { 8935 postDelayed(mUnsetPressedState, 8936 ViewConfiguration.getPressedStateDuration()); 8937 } else if (!post(mUnsetPressedState)) { 8938 // If the post failed, unpress right now 8939 mUnsetPressedState.run(); 8940 } 8941 removeTapCallback(); 8942 } 8943 break; 8944 8945 case MotionEvent.ACTION_DOWN: 8946 mHasPerformedLongPress = false; 8947 8948 if (performButtonActionOnTouchDown(event)) { 8949 break; 8950 } 8951 8952 // Walk up the hierarchy to determine if we're inside a scrolling container. 8953 boolean isInScrollingContainer = isInScrollingContainer(); 8954 8955 // For views inside a scrolling container, delay the pressed feedback for 8956 // a short period in case this is a scroll. 8957 if (isInScrollingContainer) { 8958 mPrivateFlags |= PFLAG_PREPRESSED; 8959 if (mPendingCheckForTap == null) { 8960 mPendingCheckForTap = new CheckForTap(); 8961 } 8962 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 8963 } else { 8964 // Not inside a scrolling container, so show the feedback right away 8965 setPressed(true); 8966 checkForLongClick(0); 8967 } 8968 break; 8969 8970 case MotionEvent.ACTION_CANCEL: 8971 setPressed(false); 8972 removeTapCallback(); 8973 removeLongPressCallback(); 8974 break; 8975 8976 case MotionEvent.ACTION_MOVE: 8977 final int x = (int) event.getX(); 8978 final int y = (int) event.getY(); 8979 8980 // Be lenient about moving outside of buttons 8981 if (!pointInView(x, y, mTouchSlop)) { 8982 // Outside button 8983 removeTapCallback(); 8984 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 8985 // Remove any future long press/tap checks 8986 removeLongPressCallback(); 8987 8988 setPressed(false); 8989 } 8990 } 8991 break; 8992 } 8993 8994 if (mBackground != null && mBackground.supportsHotspots()) { 8995 manageTouchHotspot(event); 8996 } 8997 8998 return true; 8999 } 9000 9001 return false; 9002 } 9003 9004 private void manageTouchHotspot(MotionEvent event) { 9005 switch (event.getAction()) { 9006 case MotionEvent.ACTION_DOWN: 9007 case MotionEvent.ACTION_POINTER_DOWN: { 9008 final int index = event.getActionIndex(); 9009 setPointerHotspot(event, index); 9010 } break; 9011 case MotionEvent.ACTION_MOVE: { 9012 final int count = event.getPointerCount(); 9013 for (int index = 0; index < count; index++) { 9014 setPointerHotspot(event, index); 9015 } 9016 } break; 9017 case MotionEvent.ACTION_POINTER_UP: { 9018 final int actionIndex = event.getActionIndex(); 9019 final int pointerId = event.getPointerId(actionIndex); 9020 mBackground.removeHotspot(pointerId); 9021 } break; 9022 case MotionEvent.ACTION_UP: 9023 case MotionEvent.ACTION_CANCEL: 9024 mBackground.clearHotspots(); 9025 break; 9026 } 9027 } 9028 9029 private void setPointerHotspot(MotionEvent event, int index) { 9030 final int id = event.getPointerId(index); 9031 final float x = event.getX(index); 9032 final float y = event.getY(index); 9033 mBackground.setHotspot(id, x, y); 9034 } 9035 9036 /** 9037 * @hide 9038 */ 9039 public boolean isInScrollingContainer() { 9040 ViewParent p = getParent(); 9041 while (p != null && p instanceof ViewGroup) { 9042 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9043 return true; 9044 } 9045 p = p.getParent(); 9046 } 9047 return false; 9048 } 9049 9050 /** 9051 * Remove the longpress detection timer. 9052 */ 9053 private void removeLongPressCallback() { 9054 if (mPendingCheckForLongPress != null) { 9055 removeCallbacks(mPendingCheckForLongPress); 9056 } 9057 } 9058 9059 /** 9060 * Remove the pending click action 9061 */ 9062 private void removePerformClickCallback() { 9063 if (mPerformClick != null) { 9064 removeCallbacks(mPerformClick); 9065 } 9066 } 9067 9068 /** 9069 * Remove the prepress detection timer. 9070 */ 9071 private void removeUnsetPressCallback() { 9072 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9073 setPressed(false); 9074 removeCallbacks(mUnsetPressedState); 9075 } 9076 } 9077 9078 /** 9079 * Remove the tap detection timer. 9080 */ 9081 private void removeTapCallback() { 9082 if (mPendingCheckForTap != null) { 9083 mPrivateFlags &= ~PFLAG_PREPRESSED; 9084 removeCallbacks(mPendingCheckForTap); 9085 } 9086 } 9087 9088 /** 9089 * Cancels a pending long press. Your subclass can use this if you 9090 * want the context menu to come up if the user presses and holds 9091 * at the same place, but you don't want it to come up if they press 9092 * and then move around enough to cause scrolling. 9093 */ 9094 public void cancelLongPress() { 9095 removeLongPressCallback(); 9096 9097 /* 9098 * The prepressed state handled by the tap callback is a display 9099 * construct, but the tap callback will post a long press callback 9100 * less its own timeout. Remove it here. 9101 */ 9102 removeTapCallback(); 9103 } 9104 9105 /** 9106 * Remove the pending callback for sending a 9107 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9108 */ 9109 private void removeSendViewScrolledAccessibilityEventCallback() { 9110 if (mSendViewScrolledAccessibilityEvent != null) { 9111 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9112 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9113 } 9114 } 9115 9116 /** 9117 * Sets the TouchDelegate for this View. 9118 */ 9119 public void setTouchDelegate(TouchDelegate delegate) { 9120 mTouchDelegate = delegate; 9121 } 9122 9123 /** 9124 * Gets the TouchDelegate for this View. 9125 */ 9126 public TouchDelegate getTouchDelegate() { 9127 return mTouchDelegate; 9128 } 9129 9130 /** 9131 * Set flags controlling behavior of this view. 9132 * 9133 * @param flags Constant indicating the value which should be set 9134 * @param mask Constant indicating the bit range that should be changed 9135 */ 9136 void setFlags(int flags, int mask) { 9137 final boolean accessibilityEnabled = 9138 AccessibilityManager.getInstance(mContext).isEnabled(); 9139 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9140 9141 int old = mViewFlags; 9142 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9143 9144 int changed = mViewFlags ^ old; 9145 if (changed == 0) { 9146 return; 9147 } 9148 int privateFlags = mPrivateFlags; 9149 9150 /* Check if the FOCUSABLE bit has changed */ 9151 if (((changed & FOCUSABLE_MASK) != 0) && 9152 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9153 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9154 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9155 /* Give up focus if we are no longer focusable */ 9156 clearFocus(); 9157 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9158 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9159 /* 9160 * Tell the view system that we are now available to take focus 9161 * if no one else already has it. 9162 */ 9163 if (mParent != null) mParent.focusableViewAvailable(this); 9164 } 9165 } 9166 9167 final int newVisibility = flags & VISIBILITY_MASK; 9168 if (newVisibility == VISIBLE) { 9169 if ((changed & VISIBILITY_MASK) != 0) { 9170 /* 9171 * If this view is becoming visible, invalidate it in case it changed while 9172 * it was not visible. Marking it drawn ensures that the invalidation will 9173 * go through. 9174 */ 9175 mPrivateFlags |= PFLAG_DRAWN; 9176 invalidate(true); 9177 9178 needGlobalAttributesUpdate(true); 9179 9180 // a view becoming visible is worth notifying the parent 9181 // about in case nothing has focus. even if this specific view 9182 // isn't focusable, it may contain something that is, so let 9183 // the root view try to give this focus if nothing else does. 9184 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9185 mParent.focusableViewAvailable(this); 9186 } 9187 } 9188 } 9189 9190 /* Check if the GONE bit has changed */ 9191 if ((changed & GONE) != 0) { 9192 needGlobalAttributesUpdate(false); 9193 requestLayout(); 9194 9195 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9196 if (hasFocus()) clearFocus(); 9197 clearAccessibilityFocus(); 9198 destroyDrawingCache(); 9199 if (mParent instanceof View) { 9200 // GONE views noop invalidation, so invalidate the parent 9201 ((View) mParent).invalidate(true); 9202 } 9203 // Mark the view drawn to ensure that it gets invalidated properly the next 9204 // time it is visible and gets invalidated 9205 mPrivateFlags |= PFLAG_DRAWN; 9206 } 9207 if (mAttachInfo != null) { 9208 mAttachInfo.mViewVisibilityChanged = true; 9209 } 9210 } 9211 9212 /* Check if the VISIBLE bit has changed */ 9213 if ((changed & INVISIBLE) != 0) { 9214 needGlobalAttributesUpdate(false); 9215 /* 9216 * If this view is becoming invisible, set the DRAWN flag so that 9217 * the next invalidate() will not be skipped. 9218 */ 9219 mPrivateFlags |= PFLAG_DRAWN; 9220 9221 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9222 // root view becoming invisible shouldn't clear focus and accessibility focus 9223 if (getRootView() != this) { 9224 if (hasFocus()) clearFocus(); 9225 clearAccessibilityFocus(); 9226 } 9227 } 9228 if (mAttachInfo != null) { 9229 mAttachInfo.mViewVisibilityChanged = true; 9230 } 9231 } 9232 9233 if ((changed & VISIBILITY_MASK) != 0) { 9234 // If the view is invisible, cleanup its display list to free up resources 9235 if (newVisibility != VISIBLE) { 9236 cleanupDraw(); 9237 } 9238 9239 if (mParent instanceof ViewGroup) { 9240 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9241 (changed & VISIBILITY_MASK), newVisibility); 9242 ((View) mParent).invalidate(true); 9243 } else if (mParent != null) { 9244 mParent.invalidateChild(this, null); 9245 } 9246 dispatchVisibilityChanged(this, newVisibility); 9247 } 9248 9249 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9250 destroyDrawingCache(); 9251 } 9252 9253 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9254 destroyDrawingCache(); 9255 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9256 invalidateParentCaches(); 9257 } 9258 9259 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9260 destroyDrawingCache(); 9261 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9262 } 9263 9264 if ((changed & DRAW_MASK) != 0) { 9265 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9266 if (mBackground != null) { 9267 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9268 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9269 } else { 9270 mPrivateFlags |= PFLAG_SKIP_DRAW; 9271 } 9272 } else { 9273 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9274 } 9275 requestLayout(); 9276 invalidate(true); 9277 } 9278 9279 if ((changed & KEEP_SCREEN_ON) != 0) { 9280 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9281 mParent.recomputeViewAttributes(this); 9282 } 9283 } 9284 9285 if (accessibilityEnabled) { 9286 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9287 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9288 if (oldIncludeForAccessibility != includeForAccessibility()) { 9289 notifySubtreeAccessibilityStateChangedIfNeeded(); 9290 } else { 9291 notifyViewAccessibilityStateChangedIfNeeded( 9292 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9293 } 9294 } else if ((changed & ENABLED_MASK) != 0) { 9295 notifyViewAccessibilityStateChangedIfNeeded( 9296 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9297 } 9298 } 9299 } 9300 9301 /** 9302 * Change the view's z order in the tree, so it's on top of other sibling 9303 * views. This ordering change may affect layout, if the parent container 9304 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9305 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9306 * method should be followed by calls to {@link #requestLayout()} and 9307 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9308 * with the new child ordering. 9309 * 9310 * @see ViewGroup#bringChildToFront(View) 9311 */ 9312 public void bringToFront() { 9313 if (mParent != null) { 9314 mParent.bringChildToFront(this); 9315 } 9316 } 9317 9318 /** 9319 * This is called in response to an internal scroll in this view (i.e., the 9320 * view scrolled its own contents). This is typically as a result of 9321 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9322 * called. 9323 * 9324 * @param l Current horizontal scroll origin. 9325 * @param t Current vertical scroll origin. 9326 * @param oldl Previous horizontal scroll origin. 9327 * @param oldt Previous vertical scroll origin. 9328 */ 9329 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9330 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9331 postSendViewScrolledAccessibilityEventCallback(); 9332 } 9333 9334 mBackgroundSizeChanged = true; 9335 9336 final AttachInfo ai = mAttachInfo; 9337 if (ai != null) { 9338 ai.mViewScrollChanged = true; 9339 } 9340 } 9341 9342 /** 9343 * Interface definition for a callback to be invoked when the layout bounds of a view 9344 * changes due to layout processing. 9345 */ 9346 public interface OnLayoutChangeListener { 9347 /** 9348 * Called when the layout bounds of a view changes due to layout processing. 9349 * 9350 * @param v The view whose bounds have changed. 9351 * @param left The new value of the view's left property. 9352 * @param top The new value of the view's top property. 9353 * @param right The new value of the view's right property. 9354 * @param bottom The new value of the view's bottom property. 9355 * @param oldLeft The previous value of the view's left property. 9356 * @param oldTop The previous value of the view's top property. 9357 * @param oldRight The previous value of the view's right property. 9358 * @param oldBottom The previous value of the view's bottom property. 9359 */ 9360 void onLayoutChange(View v, int left, int top, int right, int bottom, 9361 int oldLeft, int oldTop, int oldRight, int oldBottom); 9362 } 9363 9364 /** 9365 * This is called during layout when the size of this view has changed. If 9366 * you were just added to the view hierarchy, you're called with the old 9367 * values of 0. 9368 * 9369 * @param w Current width of this view. 9370 * @param h Current height of this view. 9371 * @param oldw Old width of this view. 9372 * @param oldh Old height of this view. 9373 */ 9374 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9375 } 9376 9377 /** 9378 * Called by draw to draw the child views. This may be overridden 9379 * by derived classes to gain control just before its children are drawn 9380 * (but after its own view has been drawn). 9381 * @param canvas the canvas on which to draw the view 9382 */ 9383 protected void dispatchDraw(Canvas canvas) { 9384 9385 } 9386 9387 /** 9388 * Gets the parent of this view. Note that the parent is a 9389 * ViewParent and not necessarily a View. 9390 * 9391 * @return Parent of this view. 9392 */ 9393 public final ViewParent getParent() { 9394 return mParent; 9395 } 9396 9397 /** 9398 * Set the horizontal scrolled position of your view. This will cause a call to 9399 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9400 * invalidated. 9401 * @param value the x position to scroll to 9402 */ 9403 public void setScrollX(int value) { 9404 scrollTo(value, mScrollY); 9405 } 9406 9407 /** 9408 * Set the vertical scrolled position of your view. This will cause a call to 9409 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9410 * invalidated. 9411 * @param value the y position to scroll to 9412 */ 9413 public void setScrollY(int value) { 9414 scrollTo(mScrollX, value); 9415 } 9416 9417 /** 9418 * Return the scrolled left position of this view. This is the left edge of 9419 * the displayed part of your view. You do not need to draw any pixels 9420 * farther left, since those are outside of the frame of your view on 9421 * screen. 9422 * 9423 * @return The left edge of the displayed part of your view, in pixels. 9424 */ 9425 public final int getScrollX() { 9426 return mScrollX; 9427 } 9428 9429 /** 9430 * Return the scrolled top position of this view. This is the top edge of 9431 * the displayed part of your view. You do not need to draw any pixels above 9432 * it, since those are outside of the frame of your view on screen. 9433 * 9434 * @return The top edge of the displayed part of your view, in pixels. 9435 */ 9436 public final int getScrollY() { 9437 return mScrollY; 9438 } 9439 9440 /** 9441 * Return the width of the your view. 9442 * 9443 * @return The width of your view, in pixels. 9444 */ 9445 @ViewDebug.ExportedProperty(category = "layout") 9446 public final int getWidth() { 9447 return mRight - mLeft; 9448 } 9449 9450 /** 9451 * Return the height of your view. 9452 * 9453 * @return The height of your view, in pixels. 9454 */ 9455 @ViewDebug.ExportedProperty(category = "layout") 9456 public final int getHeight() { 9457 return mBottom - mTop; 9458 } 9459 9460 /** 9461 * Return the visible drawing bounds of your view. Fills in the output 9462 * rectangle with the values from getScrollX(), getScrollY(), 9463 * getWidth(), and getHeight(). These bounds do not account for any 9464 * transformation properties currently set on the view, such as 9465 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9466 * 9467 * @param outRect The (scrolled) drawing bounds of the view. 9468 */ 9469 public void getDrawingRect(Rect outRect) { 9470 outRect.left = mScrollX; 9471 outRect.top = mScrollY; 9472 outRect.right = mScrollX + (mRight - mLeft); 9473 outRect.bottom = mScrollY + (mBottom - mTop); 9474 } 9475 9476 /** 9477 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9478 * raw width component (that is the result is masked by 9479 * {@link #MEASURED_SIZE_MASK}). 9480 * 9481 * @return The raw measured width of this view. 9482 */ 9483 public final int getMeasuredWidth() { 9484 return mMeasuredWidth & MEASURED_SIZE_MASK; 9485 } 9486 9487 /** 9488 * Return the full width measurement information for this view as computed 9489 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9490 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9491 * This should be used during measurement and layout calculations only. Use 9492 * {@link #getWidth()} to see how wide a view is after layout. 9493 * 9494 * @return The measured width of this view as a bit mask. 9495 */ 9496 public final int getMeasuredWidthAndState() { 9497 return mMeasuredWidth; 9498 } 9499 9500 /** 9501 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9502 * raw width component (that is the result is masked by 9503 * {@link #MEASURED_SIZE_MASK}). 9504 * 9505 * @return The raw measured height of this view. 9506 */ 9507 public final int getMeasuredHeight() { 9508 return mMeasuredHeight & MEASURED_SIZE_MASK; 9509 } 9510 9511 /** 9512 * Return the full height measurement information for this view as computed 9513 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9514 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9515 * This should be used during measurement and layout calculations only. Use 9516 * {@link #getHeight()} to see how wide a view is after layout. 9517 * 9518 * @return The measured width of this view as a bit mask. 9519 */ 9520 public final int getMeasuredHeightAndState() { 9521 return mMeasuredHeight; 9522 } 9523 9524 /** 9525 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9526 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9527 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9528 * and the height component is at the shifted bits 9529 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9530 */ 9531 public final int getMeasuredState() { 9532 return (mMeasuredWidth&MEASURED_STATE_MASK) 9533 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9534 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9535 } 9536 9537 /** 9538 * The transform matrix of this view, which is calculated based on the current 9539 * roation, scale, and pivot properties. 9540 * 9541 * @see #getRotation() 9542 * @see #getScaleX() 9543 * @see #getScaleY() 9544 * @see #getPivotX() 9545 * @see #getPivotY() 9546 * @return The current transform matrix for the view 9547 */ 9548 public Matrix getMatrix() { 9549 if (mTransformationInfo != null) { 9550 updateMatrix(); 9551 return mTransformationInfo.mMatrix; 9552 } 9553 return Matrix.IDENTITY_MATRIX; 9554 } 9555 9556 /** 9557 * Utility function to determine if the value is far enough away from zero to be 9558 * considered non-zero. 9559 * @param value A floating point value to check for zero-ness 9560 * @return whether the passed-in value is far enough away from zero to be considered non-zero 9561 */ 9562 private static boolean nonzero(float value) { 9563 return (value < -NONZERO_EPSILON || value > NONZERO_EPSILON); 9564 } 9565 9566 /** 9567 * Returns true if the transform matrix is the identity matrix. 9568 * Recomputes the matrix if necessary. 9569 * 9570 * @return True if the transform matrix is the identity matrix, false otherwise. 9571 */ 9572 final boolean hasIdentityMatrix() { 9573 if (mTransformationInfo != null) { 9574 updateMatrix(); 9575 return mTransformationInfo.mMatrixIsIdentity; 9576 } 9577 return true; 9578 } 9579 9580 void ensureTransformationInfo() { 9581 if (mTransformationInfo == null) { 9582 mTransformationInfo = new TransformationInfo(); 9583 } 9584 } 9585 9586 /** 9587 * Recomputes the transform matrix if necessary. 9588 */ 9589 private void updateMatrix() { 9590 final TransformationInfo info = mTransformationInfo; 9591 if (info == null) { 9592 return; 9593 } 9594 if (info.mMatrixDirty) { 9595 // transform-related properties have changed since the last time someone 9596 // asked for the matrix; recalculate it with the current values 9597 9598 // Figure out if we need to update the pivot point 9599 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 9600 if ((mRight - mLeft) != info.mPrevWidth || (mBottom - mTop) != info.mPrevHeight) { 9601 info.mPrevWidth = mRight - mLeft; 9602 info.mPrevHeight = mBottom - mTop; 9603 info.mPivotX = info.mPrevWidth / 2f; 9604 info.mPivotY = info.mPrevHeight / 2f; 9605 } 9606 } 9607 info.mMatrix.reset(); 9608 if (!nonzero(info.mRotationX) && !nonzero(info.mRotationY)) { 9609 info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); 9610 info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); 9611 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9612 } else { 9613 if (info.mCamera == null) { 9614 info.mCamera = new Camera(); 9615 info.matrix3D = new Matrix(); 9616 } 9617 info.mCamera.save(); 9618 info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); 9619 info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); 9620 info.mCamera.getMatrix(info.matrix3D); 9621 info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); 9622 info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, 9623 info.mPivotY + info.mTranslationY); 9624 info.mMatrix.postConcat(info.matrix3D); 9625 info.mCamera.restore(); 9626 } 9627 info.mMatrixDirty = false; 9628 info.mMatrixIsIdentity = info.mMatrix.isIdentity(); 9629 info.mInverseMatrixDirty = true; 9630 } 9631 } 9632 9633 /** 9634 * Utility method to retrieve the inverse of the current mMatrix property. 9635 * We cache the matrix to avoid recalculating it when transform properties 9636 * have not changed. 9637 * 9638 * @return The inverse of the current matrix of this view. 9639 */ 9640 final Matrix getInverseMatrix() { 9641 final TransformationInfo info = mTransformationInfo; 9642 if (info != null) { 9643 updateMatrix(); 9644 if (info.mInverseMatrixDirty) { 9645 if (info.mInverseMatrix == null) { 9646 info.mInverseMatrix = new Matrix(); 9647 } 9648 info.mMatrix.invert(info.mInverseMatrix); 9649 info.mInverseMatrixDirty = false; 9650 } 9651 return info.mInverseMatrix; 9652 } 9653 return Matrix.IDENTITY_MATRIX; 9654 } 9655 9656 /** 9657 * Gets the distance along the Z axis from the camera to this view. 9658 * 9659 * @see #setCameraDistance(float) 9660 * 9661 * @return The distance along the Z axis. 9662 */ 9663 public float getCameraDistance() { 9664 ensureTransformationInfo(); 9665 final float dpi = mResources.getDisplayMetrics().densityDpi; 9666 final TransformationInfo info = mTransformationInfo; 9667 if (info.mCamera == null) { 9668 info.mCamera = new Camera(); 9669 info.matrix3D = new Matrix(); 9670 } 9671 return -(info.mCamera.getLocationZ() * dpi); 9672 } 9673 9674 /** 9675 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9676 * views are drawn) from the camera to this view. The camera's distance 9677 * affects 3D transformations, for instance rotations around the X and Y 9678 * axis. If the rotationX or rotationY properties are changed and this view is 9679 * large (more than half the size of the screen), it is recommended to always 9680 * use a camera distance that's greater than the height (X axis rotation) or 9681 * the width (Y axis rotation) of this view.</p> 9682 * 9683 * <p>The distance of the camera from the view plane can have an affect on the 9684 * perspective distortion of the view when it is rotated around the x or y axis. 9685 * For example, a large distance will result in a large viewing angle, and there 9686 * will not be much perspective distortion of the view as it rotates. A short 9687 * distance may cause much more perspective distortion upon rotation, and can 9688 * also result in some drawing artifacts if the rotated view ends up partially 9689 * behind the camera (which is why the recommendation is to use a distance at 9690 * least as far as the size of the view, if the view is to be rotated.)</p> 9691 * 9692 * <p>The distance is expressed in "depth pixels." The default distance depends 9693 * on the screen density. For instance, on a medium density display, the 9694 * default distance is 1280. On a high density display, the default distance 9695 * is 1920.</p> 9696 * 9697 * <p>If you want to specify a distance that leads to visually consistent 9698 * results across various densities, use the following formula:</p> 9699 * <pre> 9700 * float scale = context.getResources().getDisplayMetrics().density; 9701 * view.setCameraDistance(distance * scale); 9702 * </pre> 9703 * 9704 * <p>The density scale factor of a high density display is 1.5, 9705 * and 1920 = 1280 * 1.5.</p> 9706 * 9707 * @param distance The distance in "depth pixels", if negative the opposite 9708 * value is used 9709 * 9710 * @see #setRotationX(float) 9711 * @see #setRotationY(float) 9712 */ 9713 public void setCameraDistance(float distance) { 9714 invalidateViewProperty(true, false); 9715 9716 ensureTransformationInfo(); 9717 final float dpi = mResources.getDisplayMetrics().densityDpi; 9718 final TransformationInfo info = mTransformationInfo; 9719 if (info.mCamera == null) { 9720 info.mCamera = new Camera(); 9721 info.matrix3D = new Matrix(); 9722 } 9723 9724 info.mCamera.setLocation(0.0f, 0.0f, -Math.abs(distance) / dpi); 9725 info.mMatrixDirty = true; 9726 9727 invalidateViewProperty(false, false); 9728 if (mDisplayList != null) { 9729 mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); 9730 } 9731 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9732 // View was rejected last time it was drawn by its parent; this may have changed 9733 invalidateParentIfNeeded(); 9734 } 9735 } 9736 9737 /** 9738 * The degrees that the view is rotated around the pivot point. 9739 * 9740 * @see #setRotation(float) 9741 * @see #getPivotX() 9742 * @see #getPivotY() 9743 * 9744 * @return The degrees of rotation. 9745 */ 9746 @ViewDebug.ExportedProperty(category = "drawing") 9747 public float getRotation() { 9748 return mTransformationInfo != null ? mTransformationInfo.mRotation : 0; 9749 } 9750 9751 /** 9752 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9753 * result in clockwise rotation. 9754 * 9755 * @param rotation The degrees of rotation. 9756 * 9757 * @see #getRotation() 9758 * @see #getPivotX() 9759 * @see #getPivotY() 9760 * @see #setRotationX(float) 9761 * @see #setRotationY(float) 9762 * 9763 * @attr ref android.R.styleable#View_rotation 9764 */ 9765 public void setRotation(float rotation) { 9766 ensureTransformationInfo(); 9767 final TransformationInfo info = mTransformationInfo; 9768 if (info.mRotation != rotation) { 9769 // Double-invalidation is necessary to capture view's old and new areas 9770 invalidateViewProperty(true, false); 9771 info.mRotation = rotation; 9772 info.mMatrixDirty = true; 9773 invalidateViewProperty(false, true); 9774 if (mDisplayList != null) { 9775 mDisplayList.setRotation(rotation); 9776 } 9777 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9778 // View was rejected last time it was drawn by its parent; this may have changed 9779 invalidateParentIfNeeded(); 9780 } 9781 } 9782 } 9783 9784 /** 9785 * The degrees that the view is rotated around the vertical axis through the pivot point. 9786 * 9787 * @see #getPivotX() 9788 * @see #getPivotY() 9789 * @see #setRotationY(float) 9790 * 9791 * @return The degrees of Y rotation. 9792 */ 9793 @ViewDebug.ExportedProperty(category = "drawing") 9794 public float getRotationY() { 9795 return mTransformationInfo != null ? mTransformationInfo.mRotationY : 0; 9796 } 9797 9798 /** 9799 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9800 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9801 * down the y axis. 9802 * 9803 * When rotating large views, it is recommended to adjust the camera distance 9804 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9805 * 9806 * @param rotationY The degrees of Y rotation. 9807 * 9808 * @see #getRotationY() 9809 * @see #getPivotX() 9810 * @see #getPivotY() 9811 * @see #setRotation(float) 9812 * @see #setRotationX(float) 9813 * @see #setCameraDistance(float) 9814 * 9815 * @attr ref android.R.styleable#View_rotationY 9816 */ 9817 public void setRotationY(float rotationY) { 9818 ensureTransformationInfo(); 9819 final TransformationInfo info = mTransformationInfo; 9820 if (info.mRotationY != rotationY) { 9821 invalidateViewProperty(true, false); 9822 info.mRotationY = rotationY; 9823 info.mMatrixDirty = true; 9824 invalidateViewProperty(false, true); 9825 if (mDisplayList != null) { 9826 mDisplayList.setRotationY(rotationY); 9827 } 9828 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9829 // View was rejected last time it was drawn by its parent; this may have changed 9830 invalidateParentIfNeeded(); 9831 } 9832 } 9833 } 9834 9835 /** 9836 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9837 * 9838 * @see #getPivotX() 9839 * @see #getPivotY() 9840 * @see #setRotationX(float) 9841 * 9842 * @return The degrees of X rotation. 9843 */ 9844 @ViewDebug.ExportedProperty(category = "drawing") 9845 public float getRotationX() { 9846 return mTransformationInfo != null ? mTransformationInfo.mRotationX : 0; 9847 } 9848 9849 /** 9850 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9851 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9852 * x axis. 9853 * 9854 * When rotating large views, it is recommended to adjust the camera distance 9855 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9856 * 9857 * @param rotationX The degrees of X rotation. 9858 * 9859 * @see #getRotationX() 9860 * @see #getPivotX() 9861 * @see #getPivotY() 9862 * @see #setRotation(float) 9863 * @see #setRotationY(float) 9864 * @see #setCameraDistance(float) 9865 * 9866 * @attr ref android.R.styleable#View_rotationX 9867 */ 9868 public void setRotationX(float rotationX) { 9869 ensureTransformationInfo(); 9870 final TransformationInfo info = mTransformationInfo; 9871 if (info.mRotationX != rotationX) { 9872 invalidateViewProperty(true, false); 9873 info.mRotationX = rotationX; 9874 info.mMatrixDirty = true; 9875 invalidateViewProperty(false, true); 9876 if (mDisplayList != null) { 9877 mDisplayList.setRotationX(rotationX); 9878 } 9879 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9880 // View was rejected last time it was drawn by its parent; this may have changed 9881 invalidateParentIfNeeded(); 9882 } 9883 } 9884 } 9885 9886 /** 9887 * The amount that the view is scaled in x around the pivot point, as a proportion of 9888 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9889 * 9890 * <p>By default, this is 1.0f. 9891 * 9892 * @see #getPivotX() 9893 * @see #getPivotY() 9894 * @return The scaling factor. 9895 */ 9896 @ViewDebug.ExportedProperty(category = "drawing") 9897 public float getScaleX() { 9898 return mTransformationInfo != null ? mTransformationInfo.mScaleX : 1; 9899 } 9900 9901 /** 9902 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9903 * the view's unscaled width. A value of 1 means that no scaling is applied. 9904 * 9905 * @param scaleX The scaling factor. 9906 * @see #getPivotX() 9907 * @see #getPivotY() 9908 * 9909 * @attr ref android.R.styleable#View_scaleX 9910 */ 9911 public void setScaleX(float scaleX) { 9912 ensureTransformationInfo(); 9913 final TransformationInfo info = mTransformationInfo; 9914 if (info.mScaleX != scaleX) { 9915 invalidateViewProperty(true, false); 9916 info.mScaleX = scaleX; 9917 info.mMatrixDirty = true; 9918 invalidateViewProperty(false, true); 9919 if (mDisplayList != null) { 9920 mDisplayList.setScaleX(scaleX); 9921 } 9922 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9923 // View was rejected last time it was drawn by its parent; this may have changed 9924 invalidateParentIfNeeded(); 9925 } 9926 } 9927 } 9928 9929 /** 9930 * The amount that the view is scaled in y around the pivot point, as a proportion of 9931 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9932 * 9933 * <p>By default, this is 1.0f. 9934 * 9935 * @see #getPivotX() 9936 * @see #getPivotY() 9937 * @return The scaling factor. 9938 */ 9939 @ViewDebug.ExportedProperty(category = "drawing") 9940 public float getScaleY() { 9941 return mTransformationInfo != null ? mTransformationInfo.mScaleY : 1; 9942 } 9943 9944 /** 9945 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9946 * the view's unscaled width. A value of 1 means that no scaling is applied. 9947 * 9948 * @param scaleY The scaling factor. 9949 * @see #getPivotX() 9950 * @see #getPivotY() 9951 * 9952 * @attr ref android.R.styleable#View_scaleY 9953 */ 9954 public void setScaleY(float scaleY) { 9955 ensureTransformationInfo(); 9956 final TransformationInfo info = mTransformationInfo; 9957 if (info.mScaleY != scaleY) { 9958 invalidateViewProperty(true, false); 9959 info.mScaleY = scaleY; 9960 info.mMatrixDirty = true; 9961 invalidateViewProperty(false, true); 9962 if (mDisplayList != null) { 9963 mDisplayList.setScaleY(scaleY); 9964 } 9965 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 9966 // View was rejected last time it was drawn by its parent; this may have changed 9967 invalidateParentIfNeeded(); 9968 } 9969 } 9970 } 9971 9972 /** 9973 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9974 * and {@link #setScaleX(float) scaled}. 9975 * 9976 * @see #getRotation() 9977 * @see #getScaleX() 9978 * @see #getScaleY() 9979 * @see #getPivotY() 9980 * @return The x location of the pivot point. 9981 * 9982 * @attr ref android.R.styleable#View_transformPivotX 9983 */ 9984 @ViewDebug.ExportedProperty(category = "drawing") 9985 public float getPivotX() { 9986 return mTransformationInfo != null ? mTransformationInfo.mPivotX : 0; 9987 } 9988 9989 /** 9990 * Sets the x location of the point around which the view is 9991 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9992 * By default, the pivot point is centered on the object. 9993 * Setting this property disables this behavior and causes the view to use only the 9994 * explicitly set pivotX and pivotY values. 9995 * 9996 * @param pivotX The x location of the pivot point. 9997 * @see #getRotation() 9998 * @see #getScaleX() 9999 * @see #getScaleY() 10000 * @see #getPivotY() 10001 * 10002 * @attr ref android.R.styleable#View_transformPivotX 10003 */ 10004 public void setPivotX(float pivotX) { 10005 ensureTransformationInfo(); 10006 final TransformationInfo info = mTransformationInfo; 10007 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 10008 PFLAG_PIVOT_EXPLICITLY_SET; 10009 if (info.mPivotX != pivotX || !pivotSet) { 10010 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 10011 invalidateViewProperty(true, false); 10012 info.mPivotX = pivotX; 10013 info.mMatrixDirty = true; 10014 invalidateViewProperty(false, true); 10015 if (mDisplayList != null) { 10016 mDisplayList.setPivotX(pivotX); 10017 } 10018 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10019 // View was rejected last time it was drawn by its parent; this may have changed 10020 invalidateParentIfNeeded(); 10021 } 10022 } 10023 } 10024 10025 /** 10026 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10027 * and {@link #setScaleY(float) scaled}. 10028 * 10029 * @see #getRotation() 10030 * @see #getScaleX() 10031 * @see #getScaleY() 10032 * @see #getPivotY() 10033 * @return The y location of the pivot point. 10034 * 10035 * @attr ref android.R.styleable#View_transformPivotY 10036 */ 10037 @ViewDebug.ExportedProperty(category = "drawing") 10038 public float getPivotY() { 10039 return mTransformationInfo != null ? mTransformationInfo.mPivotY : 0; 10040 } 10041 10042 /** 10043 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10044 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10045 * Setting this property disables this behavior and causes the view to use only the 10046 * explicitly set pivotX and pivotY values. 10047 * 10048 * @param pivotY The y location of the pivot point. 10049 * @see #getRotation() 10050 * @see #getScaleX() 10051 * @see #getScaleY() 10052 * @see #getPivotY() 10053 * 10054 * @attr ref android.R.styleable#View_transformPivotY 10055 */ 10056 public void setPivotY(float pivotY) { 10057 ensureTransformationInfo(); 10058 final TransformationInfo info = mTransformationInfo; 10059 boolean pivotSet = (mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 10060 PFLAG_PIVOT_EXPLICITLY_SET; 10061 if (info.mPivotY != pivotY || !pivotSet) { 10062 mPrivateFlags |= PFLAG_PIVOT_EXPLICITLY_SET; 10063 invalidateViewProperty(true, false); 10064 info.mPivotY = pivotY; 10065 info.mMatrixDirty = true; 10066 invalidateViewProperty(false, true); 10067 if (mDisplayList != null) { 10068 mDisplayList.setPivotY(pivotY); 10069 } 10070 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10071 // View was rejected last time it was drawn by its parent; this may have changed 10072 invalidateParentIfNeeded(); 10073 } 10074 } 10075 } 10076 10077 /** 10078 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10079 * completely transparent and 1 means the view is completely opaque. 10080 * 10081 * <p>By default this is 1.0f. 10082 * @return The opacity of the view. 10083 */ 10084 @ViewDebug.ExportedProperty(category = "drawing") 10085 public float getAlpha() { 10086 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10087 } 10088 10089 /** 10090 * Returns whether this View has content which overlaps. 10091 * 10092 * <p>This function, intended to be overridden by specific View types, is an optimization when 10093 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10094 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10095 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10096 * directly. An example of overlapping rendering is a TextView with a background image, such as 10097 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10098 * ImageView with only the foreground image. The default implementation returns true; subclasses 10099 * should override if they have cases which can be optimized.</p> 10100 * 10101 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10102 * necessitates that a View return true if it uses the methods internally without passing the 10103 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10104 * 10105 * @return true if the content in this view might overlap, false otherwise. 10106 */ 10107 public boolean hasOverlappingRendering() { 10108 return true; 10109 } 10110 10111 /** 10112 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10113 * completely transparent and 1 means the view is completely opaque.</p> 10114 * 10115 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10116 * performance implications, especially for large views. It is best to use the alpha property 10117 * sparingly and transiently, as in the case of fading animations.</p> 10118 * 10119 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10120 * strongly recommended for performance reasons to either override 10121 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10122 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10123 * 10124 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10125 * responsible for applying the opacity itself.</p> 10126 * 10127 * <p>Note that if the view is backed by a 10128 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10129 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10130 * 1.0 will supercede the alpha of the layer paint.</p> 10131 * 10132 * @param alpha The opacity of the view. 10133 * 10134 * @see #hasOverlappingRendering() 10135 * @see #setLayerType(int, android.graphics.Paint) 10136 * 10137 * @attr ref android.R.styleable#View_alpha 10138 */ 10139 public void setAlpha(float alpha) { 10140 ensureTransformationInfo(); 10141 if (mTransformationInfo.mAlpha != alpha) { 10142 mTransformationInfo.mAlpha = alpha; 10143 if (onSetAlpha((int) (alpha * 255))) { 10144 mPrivateFlags |= PFLAG_ALPHA_SET; 10145 // subclass is handling alpha - don't optimize rendering cache invalidation 10146 invalidateParentCaches(); 10147 invalidate(true); 10148 } else { 10149 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10150 invalidateViewProperty(true, false); 10151 if (mDisplayList != null) { 10152 mDisplayList.setAlpha(getFinalAlpha()); 10153 } 10154 } 10155 } 10156 } 10157 10158 /** 10159 * Faster version of setAlpha() which performs the same steps except there are 10160 * no calls to invalidate(). The caller of this function should perform proper invalidation 10161 * on the parent and this object. The return value indicates whether the subclass handles 10162 * alpha (the return value for onSetAlpha()). 10163 * 10164 * @param alpha The new value for the alpha property 10165 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10166 * the new value for the alpha property is different from the old value 10167 */ 10168 boolean setAlphaNoInvalidation(float alpha) { 10169 ensureTransformationInfo(); 10170 if (mTransformationInfo.mAlpha != alpha) { 10171 mTransformationInfo.mAlpha = alpha; 10172 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10173 if (subclassHandlesAlpha) { 10174 mPrivateFlags |= PFLAG_ALPHA_SET; 10175 return true; 10176 } else { 10177 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10178 if (mDisplayList != null) { 10179 mDisplayList.setAlpha(getFinalAlpha()); 10180 } 10181 } 10182 } 10183 return false; 10184 } 10185 10186 /** 10187 * This property is hidden and intended only for use by the Fade transition, which 10188 * animates it to produce a visual translucency that does not side-effect (or get 10189 * affected by) the real alpha property. This value is composited with the other 10190 * alpha value (and the AlphaAnimation value, when that is present) to produce 10191 * a final visual translucency result, which is what is passed into the DisplayList. 10192 * 10193 * @hide 10194 */ 10195 public void setTransitionAlpha(float alpha) { 10196 ensureTransformationInfo(); 10197 if (mTransformationInfo.mTransitionAlpha != alpha) { 10198 mTransformationInfo.mTransitionAlpha = alpha; 10199 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10200 invalidateViewProperty(true, false); 10201 if (mDisplayList != null) { 10202 mDisplayList.setAlpha(getFinalAlpha()); 10203 } 10204 } 10205 } 10206 10207 /** 10208 * Calculates the visual alpha of this view, which is a combination of the actual 10209 * alpha value and the transitionAlpha value (if set). 10210 */ 10211 private float getFinalAlpha() { 10212 if (mTransformationInfo != null) { 10213 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10214 } 10215 return 1; 10216 } 10217 10218 /** 10219 * This property is hidden and intended only for use by the Fade transition, which 10220 * animates it to produce a visual translucency that does not side-effect (or get 10221 * affected by) the real alpha property. This value is composited with the other 10222 * alpha value (and the AlphaAnimation value, when that is present) to produce 10223 * a final visual translucency result, which is what is passed into the DisplayList. 10224 * 10225 * @hide 10226 */ 10227 public float getTransitionAlpha() { 10228 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10229 } 10230 10231 /** 10232 * Top position of this view relative to its parent. 10233 * 10234 * @return The top of this view, in pixels. 10235 */ 10236 @ViewDebug.CapturedViewProperty 10237 public final int getTop() { 10238 return mTop; 10239 } 10240 10241 /** 10242 * Sets the top position of this view relative to its parent. This method is meant to be called 10243 * by the layout system and should not generally be called otherwise, because the property 10244 * may be changed at any time by the layout. 10245 * 10246 * @param top The top of this view, in pixels. 10247 */ 10248 public final void setTop(int top) { 10249 if (top != mTop) { 10250 updateMatrix(); 10251 final boolean matrixIsIdentity = mTransformationInfo == null 10252 || mTransformationInfo.mMatrixIsIdentity; 10253 if (matrixIsIdentity) { 10254 if (mAttachInfo != null) { 10255 int minTop; 10256 int yLoc; 10257 if (top < mTop) { 10258 minTop = top; 10259 yLoc = top - mTop; 10260 } else { 10261 minTop = mTop; 10262 yLoc = 0; 10263 } 10264 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10265 } 10266 } else { 10267 // Double-invalidation is necessary to capture view's old and new areas 10268 invalidate(true); 10269 } 10270 10271 int width = mRight - mLeft; 10272 int oldHeight = mBottom - mTop; 10273 10274 mTop = top; 10275 if (mDisplayList != null) { 10276 mDisplayList.setTop(mTop); 10277 } 10278 10279 sizeChange(width, mBottom - mTop, width, oldHeight); 10280 10281 if (!matrixIsIdentity) { 10282 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10283 // A change in dimension means an auto-centered pivot point changes, too 10284 mTransformationInfo.mMatrixDirty = true; 10285 } 10286 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10287 invalidate(true); 10288 } 10289 mBackgroundSizeChanged = true; 10290 invalidateParentIfNeeded(); 10291 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10292 // View was rejected last time it was drawn by its parent; this may have changed 10293 invalidateParentIfNeeded(); 10294 } 10295 } 10296 } 10297 10298 /** 10299 * Bottom position of this view relative to its parent. 10300 * 10301 * @return The bottom of this view, in pixels. 10302 */ 10303 @ViewDebug.CapturedViewProperty 10304 public final int getBottom() { 10305 return mBottom; 10306 } 10307 10308 /** 10309 * True if this view has changed since the last time being drawn. 10310 * 10311 * @return The dirty state of this view. 10312 */ 10313 public boolean isDirty() { 10314 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10315 } 10316 10317 /** 10318 * Sets the bottom position of this view relative to its parent. This method is meant to be 10319 * called by the layout system and should not generally be called otherwise, because the 10320 * property may be changed at any time by the layout. 10321 * 10322 * @param bottom The bottom of this view, in pixels. 10323 */ 10324 public final void setBottom(int bottom) { 10325 if (bottom != mBottom) { 10326 updateMatrix(); 10327 final boolean matrixIsIdentity = mTransformationInfo == null 10328 || mTransformationInfo.mMatrixIsIdentity; 10329 if (matrixIsIdentity) { 10330 if (mAttachInfo != null) { 10331 int maxBottom; 10332 if (bottom < mBottom) { 10333 maxBottom = mBottom; 10334 } else { 10335 maxBottom = bottom; 10336 } 10337 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10338 } 10339 } else { 10340 // Double-invalidation is necessary to capture view's old and new areas 10341 invalidate(true); 10342 } 10343 10344 int width = mRight - mLeft; 10345 int oldHeight = mBottom - mTop; 10346 10347 mBottom = bottom; 10348 if (mDisplayList != null) { 10349 mDisplayList.setBottom(mBottom); 10350 } 10351 10352 sizeChange(width, mBottom - mTop, width, oldHeight); 10353 10354 if (!matrixIsIdentity) { 10355 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10356 // A change in dimension means an auto-centered pivot point changes, too 10357 mTransformationInfo.mMatrixDirty = true; 10358 } 10359 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10360 invalidate(true); 10361 } 10362 mBackgroundSizeChanged = true; 10363 invalidateParentIfNeeded(); 10364 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10365 // View was rejected last time it was drawn by its parent; this may have changed 10366 invalidateParentIfNeeded(); 10367 } 10368 } 10369 } 10370 10371 /** 10372 * Left position of this view relative to its parent. 10373 * 10374 * @return The left edge of this view, in pixels. 10375 */ 10376 @ViewDebug.CapturedViewProperty 10377 public final int getLeft() { 10378 return mLeft; 10379 } 10380 10381 /** 10382 * Sets the left position of this view relative to its parent. This method is meant to be called 10383 * by the layout system and should not generally be called otherwise, because the property 10384 * may be changed at any time by the layout. 10385 * 10386 * @param left The bottom of this view, in pixels. 10387 */ 10388 public final void setLeft(int left) { 10389 if (left != mLeft) { 10390 updateMatrix(); 10391 final boolean matrixIsIdentity = mTransformationInfo == null 10392 || mTransformationInfo.mMatrixIsIdentity; 10393 if (matrixIsIdentity) { 10394 if (mAttachInfo != null) { 10395 int minLeft; 10396 int xLoc; 10397 if (left < mLeft) { 10398 minLeft = left; 10399 xLoc = left - mLeft; 10400 } else { 10401 minLeft = mLeft; 10402 xLoc = 0; 10403 } 10404 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10405 } 10406 } else { 10407 // Double-invalidation is necessary to capture view's old and new areas 10408 invalidate(true); 10409 } 10410 10411 int oldWidth = mRight - mLeft; 10412 int height = mBottom - mTop; 10413 10414 mLeft = left; 10415 if (mDisplayList != null) { 10416 mDisplayList.setLeft(left); 10417 } 10418 10419 sizeChange(mRight - mLeft, height, oldWidth, height); 10420 10421 if (!matrixIsIdentity) { 10422 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10423 // A change in dimension means an auto-centered pivot point changes, too 10424 mTransformationInfo.mMatrixDirty = true; 10425 } 10426 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10427 invalidate(true); 10428 } 10429 mBackgroundSizeChanged = true; 10430 invalidateParentIfNeeded(); 10431 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10432 // View was rejected last time it was drawn by its parent; this may have changed 10433 invalidateParentIfNeeded(); 10434 } 10435 } 10436 } 10437 10438 /** 10439 * Right position of this view relative to its parent. 10440 * 10441 * @return The right edge of this view, in pixels. 10442 */ 10443 @ViewDebug.CapturedViewProperty 10444 public final int getRight() { 10445 return mRight; 10446 } 10447 10448 /** 10449 * Sets the right position of this view relative to its parent. This method is meant to be called 10450 * by the layout system and should not generally be called otherwise, because the property 10451 * may be changed at any time by the layout. 10452 * 10453 * @param right The bottom of this view, in pixels. 10454 */ 10455 public final void setRight(int right) { 10456 if (right != mRight) { 10457 updateMatrix(); 10458 final boolean matrixIsIdentity = mTransformationInfo == null 10459 || mTransformationInfo.mMatrixIsIdentity; 10460 if (matrixIsIdentity) { 10461 if (mAttachInfo != null) { 10462 int maxRight; 10463 if (right < mRight) { 10464 maxRight = mRight; 10465 } else { 10466 maxRight = right; 10467 } 10468 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10469 } 10470 } else { 10471 // Double-invalidation is necessary to capture view's old and new areas 10472 invalidate(true); 10473 } 10474 10475 int oldWidth = mRight - mLeft; 10476 int height = mBottom - mTop; 10477 10478 mRight = right; 10479 if (mDisplayList != null) { 10480 mDisplayList.setRight(mRight); 10481 } 10482 10483 sizeChange(mRight - mLeft, height, oldWidth, height); 10484 10485 if (!matrixIsIdentity) { 10486 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 10487 // A change in dimension means an auto-centered pivot point changes, too 10488 mTransformationInfo.mMatrixDirty = true; 10489 } 10490 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10491 invalidate(true); 10492 } 10493 mBackgroundSizeChanged = true; 10494 invalidateParentIfNeeded(); 10495 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10496 // View was rejected last time it was drawn by its parent; this may have changed 10497 invalidateParentIfNeeded(); 10498 } 10499 } 10500 } 10501 10502 /** 10503 * The visual x position of this view, in pixels. This is equivalent to the 10504 * {@link #setTranslationX(float) translationX} property plus the current 10505 * {@link #getLeft() left} property. 10506 * 10507 * @return The visual x position of this view, in pixels. 10508 */ 10509 @ViewDebug.ExportedProperty(category = "drawing") 10510 public float getX() { 10511 return mLeft + (mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0); 10512 } 10513 10514 /** 10515 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10516 * {@link #setTranslationX(float) translationX} property to be the difference between 10517 * the x value passed in and the current {@link #getLeft() left} property. 10518 * 10519 * @param x The visual x position of this view, in pixels. 10520 */ 10521 public void setX(float x) { 10522 setTranslationX(x - mLeft); 10523 } 10524 10525 /** 10526 * The visual y position of this view, in pixels. This is equivalent to the 10527 * {@link #setTranslationY(float) translationY} property plus the current 10528 * {@link #getTop() top} property. 10529 * 10530 * @return The visual y position of this view, in pixels. 10531 */ 10532 @ViewDebug.ExportedProperty(category = "drawing") 10533 public float getY() { 10534 return mTop + (mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0); 10535 } 10536 10537 /** 10538 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10539 * {@link #setTranslationY(float) translationY} property to be the difference between 10540 * the y value passed in and the current {@link #getTop() top} property. 10541 * 10542 * @param y The visual y position of this view, in pixels. 10543 */ 10544 public void setY(float y) { 10545 setTranslationY(y - mTop); 10546 } 10547 10548 10549 /** 10550 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10551 * This position is post-layout, in addition to wherever the object's 10552 * layout placed it. 10553 * 10554 * @return The horizontal position of this view relative to its left position, in pixels. 10555 */ 10556 @ViewDebug.ExportedProperty(category = "drawing") 10557 public float getTranslationX() { 10558 return mTransformationInfo != null ? mTransformationInfo.mTranslationX : 0; 10559 } 10560 10561 /** 10562 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10563 * This effectively positions the object post-layout, in addition to wherever the object's 10564 * layout placed it. 10565 * 10566 * @param translationX The horizontal position of this view relative to its left position, 10567 * in pixels. 10568 * 10569 * @attr ref android.R.styleable#View_translationX 10570 */ 10571 public void setTranslationX(float translationX) { 10572 ensureTransformationInfo(); 10573 final TransformationInfo info = mTransformationInfo; 10574 if (info.mTranslationX != translationX) { 10575 // Double-invalidation is necessary to capture view's old and new areas 10576 invalidateViewProperty(true, false); 10577 info.mTranslationX = translationX; 10578 info.mMatrixDirty = true; 10579 invalidateViewProperty(false, true); 10580 if (mDisplayList != null) { 10581 mDisplayList.setTranslationX(translationX); 10582 } 10583 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10584 // View was rejected last time it was drawn by its parent; this may have changed 10585 invalidateParentIfNeeded(); 10586 } 10587 } 10588 } 10589 10590 /** 10591 * The vertical location of this view relative to its {@link #getTop() top} position. 10592 * This position is post-layout, in addition to wherever the object's 10593 * layout placed it. 10594 * 10595 * @return The vertical position of this view relative to its top position, 10596 * in pixels. 10597 */ 10598 @ViewDebug.ExportedProperty(category = "drawing") 10599 public float getTranslationY() { 10600 return mTransformationInfo != null ? mTransformationInfo.mTranslationY : 0; 10601 } 10602 10603 /** 10604 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10605 * This effectively positions the object post-layout, in addition to wherever the object's 10606 * layout placed it. 10607 * 10608 * @param translationY The vertical position of this view relative to its top position, 10609 * in pixels. 10610 * 10611 * @attr ref android.R.styleable#View_translationY 10612 */ 10613 public void setTranslationY(float translationY) { 10614 ensureTransformationInfo(); 10615 final TransformationInfo info = mTransformationInfo; 10616 if (info.mTranslationY != translationY) { 10617 invalidateViewProperty(true, false); 10618 info.mTranslationY = translationY; 10619 info.mMatrixDirty = true; 10620 invalidateViewProperty(false, true); 10621 if (mDisplayList != null) { 10622 mDisplayList.setTranslationY(translationY); 10623 } 10624 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10625 // View was rejected last time it was drawn by its parent; this may have changed 10626 invalidateParentIfNeeded(); 10627 } 10628 } 10629 } 10630 10631 /** 10632 * The depth location of this view relative to its parent. 10633 * 10634 * @return The depth of this view relative to its parent. 10635 */ 10636 @ViewDebug.ExportedProperty(category = "drawing") 10637 public float getTranslationZ() { 10638 return mTransformationInfo != null ? mTransformationInfo.mTranslationZ : 0; 10639 } 10640 10641 /** 10642 * Sets the depth location of this view relative to its parent. 10643 * 10644 * @attr ref android.R.styleable#View_translationZ 10645 */ 10646 public void setTranslationZ(float translationZ) { 10647 ensureTransformationInfo(); 10648 final TransformationInfo info = mTransformationInfo; 10649 if (info.mTranslationZ != translationZ) { 10650 invalidateViewProperty(true, false); 10651 info.mTranslationZ = translationZ; 10652 info.mMatrixDirty = true; 10653 invalidateViewProperty(false, true); 10654 if (mDisplayList != null) { 10655 mDisplayList.setTranslationZ(translationZ); 10656 } 10657 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10658 // View was rejected last time it was drawn by its parent; this may have changed 10659 invalidateParentIfNeeded(); 10660 } 10661 } 10662 } 10663 10664 /** 10665 * @hide 10666 */ 10667 public final void getOutline(Path outline) { 10668 if (mOutline == null) { 10669 outline.reset(); 10670 } else { 10671 outline.set(mOutline); 10672 } 10673 } 10674 10675 /** 10676 * @hide 10677 */ 10678 public void setOutline(Path path) { 10679 // always copy the path since caller may reuse 10680 if (mOutline == null) { 10681 mOutline = new Path(path); 10682 } else { 10683 mOutline.set(path); 10684 } 10685 10686 if (mDisplayList != null) { 10687 mDisplayList.setOutline(path); 10688 } 10689 } 10690 10691 /** 10692 * Hit rectangle in parent's coordinates 10693 * 10694 * @param outRect The hit rectangle of the view. 10695 */ 10696 public void getHitRect(Rect outRect) { 10697 updateMatrix(); 10698 final TransformationInfo info = mTransformationInfo; 10699 if (info == null || info.mMatrixIsIdentity || mAttachInfo == null) { 10700 outRect.set(mLeft, mTop, mRight, mBottom); 10701 } else { 10702 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10703 tmpRect.set(0, 0, getWidth(), getHeight()); 10704 info.mMatrix.mapRect(tmpRect); 10705 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10706 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10707 } 10708 } 10709 10710 /** 10711 * Determines whether the given point, in local coordinates is inside the view. 10712 */ 10713 /*package*/ final boolean pointInView(float localX, float localY) { 10714 return localX >= 0 && localX < (mRight - mLeft) 10715 && localY >= 0 && localY < (mBottom - mTop); 10716 } 10717 10718 /** 10719 * Utility method to determine whether the given point, in local coordinates, 10720 * is inside the view, where the area of the view is expanded by the slop factor. 10721 * This method is called while processing touch-move events to determine if the event 10722 * is still within the view. 10723 * 10724 * @hide 10725 */ 10726 public boolean pointInView(float localX, float localY, float slop) { 10727 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10728 localY < ((mBottom - mTop) + slop); 10729 } 10730 10731 /** 10732 * When a view has focus and the user navigates away from it, the next view is searched for 10733 * starting from the rectangle filled in by this method. 10734 * 10735 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10736 * of the view. However, if your view maintains some idea of internal selection, 10737 * such as a cursor, or a selected row or column, you should override this method and 10738 * fill in a more specific rectangle. 10739 * 10740 * @param r The rectangle to fill in, in this view's coordinates. 10741 */ 10742 public void getFocusedRect(Rect r) { 10743 getDrawingRect(r); 10744 } 10745 10746 /** 10747 * If some part of this view is not clipped by any of its parents, then 10748 * return that area in r in global (root) coordinates. To convert r to local 10749 * coordinates (without taking possible View rotations into account), offset 10750 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10751 * If the view is completely clipped or translated out, return false. 10752 * 10753 * @param r If true is returned, r holds the global coordinates of the 10754 * visible portion of this view. 10755 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10756 * between this view and its root. globalOffet may be null. 10757 * @return true if r is non-empty (i.e. part of the view is visible at the 10758 * root level. 10759 */ 10760 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10761 int width = mRight - mLeft; 10762 int height = mBottom - mTop; 10763 if (width > 0 && height > 0) { 10764 r.set(0, 0, width, height); 10765 if (globalOffset != null) { 10766 globalOffset.set(-mScrollX, -mScrollY); 10767 } 10768 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10769 } 10770 return false; 10771 } 10772 10773 public final boolean getGlobalVisibleRect(Rect r) { 10774 return getGlobalVisibleRect(r, null); 10775 } 10776 10777 public final boolean getLocalVisibleRect(Rect r) { 10778 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10779 if (getGlobalVisibleRect(r, offset)) { 10780 r.offset(-offset.x, -offset.y); // make r local 10781 return true; 10782 } 10783 return false; 10784 } 10785 10786 /** 10787 * Offset this view's vertical location by the specified number of pixels. 10788 * 10789 * @param offset the number of pixels to offset the view by 10790 */ 10791 public void offsetTopAndBottom(int offset) { 10792 if (offset != 0) { 10793 updateMatrix(); 10794 final boolean matrixIsIdentity = mTransformationInfo == null 10795 || mTransformationInfo.mMatrixIsIdentity; 10796 if (matrixIsIdentity) { 10797 if (mDisplayList != null) { 10798 invalidateViewProperty(false, false); 10799 } else { 10800 final ViewParent p = mParent; 10801 if (p != null && mAttachInfo != null) { 10802 final Rect r = mAttachInfo.mTmpInvalRect; 10803 int minTop; 10804 int maxBottom; 10805 int yLoc; 10806 if (offset < 0) { 10807 minTop = mTop + offset; 10808 maxBottom = mBottom; 10809 yLoc = offset; 10810 } else { 10811 minTop = mTop; 10812 maxBottom = mBottom + offset; 10813 yLoc = 0; 10814 } 10815 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10816 p.invalidateChild(this, r); 10817 } 10818 } 10819 } else { 10820 invalidateViewProperty(false, false); 10821 } 10822 10823 mTop += offset; 10824 mBottom += offset; 10825 if (mDisplayList != null) { 10826 mDisplayList.offsetTopAndBottom(offset); 10827 invalidateViewProperty(false, false); 10828 } else { 10829 if (!matrixIsIdentity) { 10830 invalidateViewProperty(false, true); 10831 } 10832 invalidateParentIfNeeded(); 10833 } 10834 } 10835 } 10836 10837 /** 10838 * Offset this view's horizontal location by the specified amount of pixels. 10839 * 10840 * @param offset the number of pixels to offset the view by 10841 */ 10842 public void offsetLeftAndRight(int offset) { 10843 if (offset != 0) { 10844 updateMatrix(); 10845 final boolean matrixIsIdentity = mTransformationInfo == null 10846 || mTransformationInfo.mMatrixIsIdentity; 10847 if (matrixIsIdentity) { 10848 if (mDisplayList != null) { 10849 invalidateViewProperty(false, false); 10850 } else { 10851 final ViewParent p = mParent; 10852 if (p != null && mAttachInfo != null) { 10853 final Rect r = mAttachInfo.mTmpInvalRect; 10854 int minLeft; 10855 int maxRight; 10856 if (offset < 0) { 10857 minLeft = mLeft + offset; 10858 maxRight = mRight; 10859 } else { 10860 minLeft = mLeft; 10861 maxRight = mRight + offset; 10862 } 10863 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10864 p.invalidateChild(this, r); 10865 } 10866 } 10867 } else { 10868 invalidateViewProperty(false, false); 10869 } 10870 10871 mLeft += offset; 10872 mRight += offset; 10873 if (mDisplayList != null) { 10874 mDisplayList.offsetLeftAndRight(offset); 10875 invalidateViewProperty(false, false); 10876 } else { 10877 if (!matrixIsIdentity) { 10878 invalidateViewProperty(false, true); 10879 } 10880 invalidateParentIfNeeded(); 10881 } 10882 } 10883 } 10884 10885 /** 10886 * Get the LayoutParams associated with this view. All views should have 10887 * layout parameters. These supply parameters to the <i>parent</i> of this 10888 * view specifying how it should be arranged. There are many subclasses of 10889 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10890 * of ViewGroup that are responsible for arranging their children. 10891 * 10892 * This method may return null if this View is not attached to a parent 10893 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10894 * was not invoked successfully. When a View is attached to a parent 10895 * ViewGroup, this method must not return null. 10896 * 10897 * @return The LayoutParams associated with this view, or null if no 10898 * parameters have been set yet 10899 */ 10900 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10901 public ViewGroup.LayoutParams getLayoutParams() { 10902 return mLayoutParams; 10903 } 10904 10905 /** 10906 * Set the layout parameters associated with this view. These supply 10907 * parameters to the <i>parent</i> of this view specifying how it should be 10908 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10909 * correspond to the different subclasses of ViewGroup that are responsible 10910 * for arranging their children. 10911 * 10912 * @param params The layout parameters for this view, cannot be null 10913 */ 10914 public void setLayoutParams(ViewGroup.LayoutParams params) { 10915 if (params == null) { 10916 throw new NullPointerException("Layout parameters cannot be null"); 10917 } 10918 mLayoutParams = params; 10919 resolveLayoutParams(); 10920 if (mParent instanceof ViewGroup) { 10921 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10922 } 10923 requestLayout(); 10924 } 10925 10926 /** 10927 * Resolve the layout parameters depending on the resolved layout direction 10928 * 10929 * @hide 10930 */ 10931 public void resolveLayoutParams() { 10932 if (mLayoutParams != null) { 10933 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10934 } 10935 } 10936 10937 /** 10938 * Set the scrolled position of your view. This will cause a call to 10939 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10940 * invalidated. 10941 * @param x the x position to scroll to 10942 * @param y the y position to scroll to 10943 */ 10944 public void scrollTo(int x, int y) { 10945 if (mScrollX != x || mScrollY != y) { 10946 int oldX = mScrollX; 10947 int oldY = mScrollY; 10948 mScrollX = x; 10949 mScrollY = y; 10950 invalidateParentCaches(); 10951 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10952 if (!awakenScrollBars()) { 10953 postInvalidateOnAnimation(); 10954 } 10955 } 10956 } 10957 10958 /** 10959 * Move the scrolled position of your view. This will cause a call to 10960 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10961 * invalidated. 10962 * @param x the amount of pixels to scroll by horizontally 10963 * @param y the amount of pixels to scroll by vertically 10964 */ 10965 public void scrollBy(int x, int y) { 10966 scrollTo(mScrollX + x, mScrollY + y); 10967 } 10968 10969 /** 10970 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10971 * animation to fade the scrollbars out after a default delay. If a subclass 10972 * provides animated scrolling, the start delay should equal the duration 10973 * of the scrolling animation.</p> 10974 * 10975 * <p>The animation starts only if at least one of the scrollbars is 10976 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10977 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10978 * this method returns true, and false otherwise. If the animation is 10979 * started, this method calls {@link #invalidate()}; in that case the 10980 * caller should not call {@link #invalidate()}.</p> 10981 * 10982 * <p>This method should be invoked every time a subclass directly updates 10983 * the scroll parameters.</p> 10984 * 10985 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10986 * and {@link #scrollTo(int, int)}.</p> 10987 * 10988 * @return true if the animation is played, false otherwise 10989 * 10990 * @see #awakenScrollBars(int) 10991 * @see #scrollBy(int, int) 10992 * @see #scrollTo(int, int) 10993 * @see #isHorizontalScrollBarEnabled() 10994 * @see #isVerticalScrollBarEnabled() 10995 * @see #setHorizontalScrollBarEnabled(boolean) 10996 * @see #setVerticalScrollBarEnabled(boolean) 10997 */ 10998 protected boolean awakenScrollBars() { 10999 return mScrollCache != null && 11000 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11001 } 11002 11003 /** 11004 * Trigger the scrollbars to draw. 11005 * This method differs from awakenScrollBars() only in its default duration. 11006 * initialAwakenScrollBars() will show the scroll bars for longer than 11007 * usual to give the user more of a chance to notice them. 11008 * 11009 * @return true if the animation is played, false otherwise. 11010 */ 11011 private boolean initialAwakenScrollBars() { 11012 return mScrollCache != null && 11013 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11014 } 11015 11016 /** 11017 * <p> 11018 * Trigger the scrollbars to draw. When invoked this method starts an 11019 * animation to fade the scrollbars out after a fixed delay. If a subclass 11020 * provides animated scrolling, the start delay should equal the duration of 11021 * the scrolling animation. 11022 * </p> 11023 * 11024 * <p> 11025 * The animation starts only if at least one of the scrollbars is enabled, 11026 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11027 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11028 * this method returns true, and false otherwise. If the animation is 11029 * started, this method calls {@link #invalidate()}; in that case the caller 11030 * should not call {@link #invalidate()}. 11031 * </p> 11032 * 11033 * <p> 11034 * This method should be invoked everytime a subclass directly updates the 11035 * scroll parameters. 11036 * </p> 11037 * 11038 * @param startDelay the delay, in milliseconds, after which the animation 11039 * should start; when the delay is 0, the animation starts 11040 * immediately 11041 * @return true if the animation is played, false otherwise 11042 * 11043 * @see #scrollBy(int, int) 11044 * @see #scrollTo(int, int) 11045 * @see #isHorizontalScrollBarEnabled() 11046 * @see #isVerticalScrollBarEnabled() 11047 * @see #setHorizontalScrollBarEnabled(boolean) 11048 * @see #setVerticalScrollBarEnabled(boolean) 11049 */ 11050 protected boolean awakenScrollBars(int startDelay) { 11051 return awakenScrollBars(startDelay, true); 11052 } 11053 11054 /** 11055 * <p> 11056 * Trigger the scrollbars to draw. When invoked this method starts an 11057 * animation to fade the scrollbars out after a fixed delay. If a subclass 11058 * provides animated scrolling, the start delay should equal the duration of 11059 * the scrolling animation. 11060 * </p> 11061 * 11062 * <p> 11063 * The animation starts only if at least one of the scrollbars is enabled, 11064 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11065 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11066 * this method returns true, and false otherwise. If the animation is 11067 * started, this method calls {@link #invalidate()} if the invalidate parameter 11068 * is set to true; in that case the caller 11069 * should not call {@link #invalidate()}. 11070 * </p> 11071 * 11072 * <p> 11073 * This method should be invoked everytime a subclass directly updates the 11074 * scroll parameters. 11075 * </p> 11076 * 11077 * @param startDelay the delay, in milliseconds, after which the animation 11078 * should start; when the delay is 0, the animation starts 11079 * immediately 11080 * 11081 * @param invalidate Wheter this method should call invalidate 11082 * 11083 * @return true if the animation is played, false otherwise 11084 * 11085 * @see #scrollBy(int, int) 11086 * @see #scrollTo(int, int) 11087 * @see #isHorizontalScrollBarEnabled() 11088 * @see #isVerticalScrollBarEnabled() 11089 * @see #setHorizontalScrollBarEnabled(boolean) 11090 * @see #setVerticalScrollBarEnabled(boolean) 11091 */ 11092 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11093 final ScrollabilityCache scrollCache = mScrollCache; 11094 11095 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11096 return false; 11097 } 11098 11099 if (scrollCache.scrollBar == null) { 11100 scrollCache.scrollBar = new ScrollBarDrawable(); 11101 } 11102 11103 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11104 11105 if (invalidate) { 11106 // Invalidate to show the scrollbars 11107 postInvalidateOnAnimation(); 11108 } 11109 11110 if (scrollCache.state == ScrollabilityCache.OFF) { 11111 // FIXME: this is copied from WindowManagerService. 11112 // We should get this value from the system when it 11113 // is possible to do so. 11114 final int KEY_REPEAT_FIRST_DELAY = 750; 11115 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11116 } 11117 11118 // Tell mScrollCache when we should start fading. This may 11119 // extend the fade start time if one was already scheduled 11120 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11121 scrollCache.fadeStartTime = fadeStartTime; 11122 scrollCache.state = ScrollabilityCache.ON; 11123 11124 // Schedule our fader to run, unscheduling any old ones first 11125 if (mAttachInfo != null) { 11126 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11127 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11128 } 11129 11130 return true; 11131 } 11132 11133 return false; 11134 } 11135 11136 /** 11137 * Do not invalidate views which are not visible and which are not running an animation. They 11138 * will not get drawn and they should not set dirty flags as if they will be drawn 11139 */ 11140 private boolean skipInvalidate() { 11141 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11142 (!(mParent instanceof ViewGroup) || 11143 !((ViewGroup) mParent).isViewTransitioning(this)); 11144 } 11145 /** 11146 * Mark the area defined by dirty as needing to be drawn. If the view is 11147 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some point 11148 * in the future. This must be called from a UI thread. To call from a non-UI 11149 * thread, call {@link #postInvalidate()}. 11150 * 11151 * WARNING: This method is destructive to dirty. 11152 * @param dirty the rectangle representing the bounds of the dirty region 11153 */ 11154 public void invalidate(Rect dirty) { 11155 if (skipInvalidate()) { 11156 return; 11157 } 11158 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 11159 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 11160 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 11161 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11162 mPrivateFlags |= PFLAG_INVALIDATED; 11163 mPrivateFlags |= PFLAG_DIRTY; 11164 final ViewParent p = mParent; 11165 final AttachInfo ai = mAttachInfo; 11166 if (p != null && ai != null) { 11167 final int scrollX = mScrollX; 11168 final int scrollY = mScrollY; 11169 final Rect r = ai.mTmpInvalRect; 11170 r.set(dirty.left - scrollX, dirty.top - scrollY, 11171 dirty.right - scrollX, dirty.bottom - scrollY); 11172 mParent.invalidateChild(this, r); 11173 } 11174 } 11175 } 11176 11177 /** 11178 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. 11179 * The coordinates of the dirty rect are relative to the view. 11180 * If the view is visible, {@link #onDraw(android.graphics.Canvas)} 11181 * will be called at some point in the future. This must be called from 11182 * a UI thread. To call from a non-UI thread, call {@link #postInvalidate()}. 11183 * @param l the left position of the dirty region 11184 * @param t the top position of the dirty region 11185 * @param r the right position of the dirty region 11186 * @param b the bottom position of the dirty region 11187 */ 11188 public void invalidate(int l, int t, int r, int b) { 11189 if (skipInvalidate()) { 11190 return; 11191 } 11192 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 11193 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID || 11194 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED) { 11195 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11196 mPrivateFlags |= PFLAG_INVALIDATED; 11197 mPrivateFlags |= PFLAG_DIRTY; 11198 final ViewParent p = mParent; 11199 final AttachInfo ai = mAttachInfo; 11200 if (p != null && ai != null && l < r && t < b) { 11201 final int scrollX = mScrollX; 11202 final int scrollY = mScrollY; 11203 final Rect tmpr = ai.mTmpInvalRect; 11204 tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); 11205 p.invalidateChild(this, tmpr); 11206 } 11207 } 11208 } 11209 11210 /** 11211 * Invalidate the whole view. If the view is visible, 11212 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11213 * the future. This must be called from a UI thread. To call from a non-UI thread, 11214 * call {@link #postInvalidate()}. 11215 */ 11216 public void invalidate() { 11217 invalidate(true); 11218 } 11219 11220 /** 11221 * This is where the invalidate() work actually happens. A full invalidate() 11222 * causes the drawing cache to be invalidated, but this function can be called with 11223 * invalidateCache set to false to skip that invalidation step for cases that do not 11224 * need it (for example, a component that remains at the same dimensions with the same 11225 * content). 11226 * 11227 * @param invalidateCache Whether the drawing cache for this view should be invalidated as 11228 * well. This is usually true for a full invalidate, but may be set to false if the 11229 * View's contents or dimensions have not changed. 11230 */ 11231 void invalidate(boolean invalidateCache) { 11232 if (skipInvalidate()) { 11233 return; 11234 } 11235 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) || 11236 (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) || 11237 (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED || isOpaque() != mLastIsOpaque) { 11238 mLastIsOpaque = isOpaque(); 11239 mPrivateFlags &= ~PFLAG_DRAWN; 11240 mPrivateFlags |= PFLAG_DIRTY; 11241 if (invalidateCache) { 11242 mPrivateFlags |= PFLAG_INVALIDATED; 11243 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11244 } 11245 final AttachInfo ai = mAttachInfo; 11246 final ViewParent p = mParent; 11247 11248 if (p != null && ai != null) { 11249 final Rect r = ai.mTmpInvalRect; 11250 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11251 // Don't call invalidate -- we don't want to internally scroll 11252 // our own bounds 11253 p.invalidateChild(this, r); 11254 } 11255 } 11256 } 11257 11258 /** 11259 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11260 * set any flags or handle all of the cases handled by the default invalidation methods. 11261 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11262 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11263 * walk up the hierarchy, transforming the dirty rect as necessary. 11264 * 11265 * The method also handles normal invalidation logic if display list properties are not 11266 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11267 * backup approach, to handle these cases used in the various property-setting methods. 11268 * 11269 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11270 * are not being used in this view 11271 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11272 * list properties are not being used in this view 11273 */ 11274 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11275 if (mDisplayList == null || (mPrivateFlags & PFLAG_DRAW_ANIMATION) == PFLAG_DRAW_ANIMATION) { 11276 if (invalidateParent) { 11277 invalidateParentCaches(); 11278 } 11279 if (forceRedraw) { 11280 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11281 } 11282 invalidate(false); 11283 } else { 11284 final AttachInfo ai = mAttachInfo; 11285 final ViewParent p = mParent; 11286 if (p != null && ai != null) { 11287 final Rect r = ai.mTmpInvalRect; 11288 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11289 if (mParent instanceof ViewGroup) { 11290 ((ViewGroup) mParent).invalidateChildFast(this, r); 11291 } else { 11292 mParent.invalidateChild(this, r); 11293 } 11294 } 11295 } 11296 } 11297 11298 /** 11299 * Utility method to transform a given Rect by the current matrix of this view. 11300 */ 11301 void transformRect(final Rect rect) { 11302 if (!getMatrix().isIdentity()) { 11303 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11304 boundingRect.set(rect); 11305 getMatrix().mapRect(boundingRect); 11306 rect.set((int) Math.floor(boundingRect.left), 11307 (int) Math.floor(boundingRect.top), 11308 (int) Math.ceil(boundingRect.right), 11309 (int) Math.ceil(boundingRect.bottom)); 11310 } 11311 } 11312 11313 /** 11314 * Used to indicate that the parent of this view should clear its caches. This functionality 11315 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11316 * which is necessary when various parent-managed properties of the view change, such as 11317 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11318 * clears the parent caches and does not causes an invalidate event. 11319 * 11320 * @hide 11321 */ 11322 protected void invalidateParentCaches() { 11323 if (mParent instanceof View) { 11324 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11325 } 11326 } 11327 11328 /** 11329 * Used to indicate that the parent of this view should be invalidated. This functionality 11330 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11331 * which is necessary when various parent-managed properties of the view change, such as 11332 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11333 * an invalidation event to the parent. 11334 * 11335 * @hide 11336 */ 11337 protected void invalidateParentIfNeeded() { 11338 if (isHardwareAccelerated() && mParent instanceof View) { 11339 ((View) mParent).invalidate(true); 11340 } 11341 } 11342 11343 /** 11344 * Indicates whether this View is opaque. An opaque View guarantees that it will 11345 * draw all the pixels overlapping its bounds using a fully opaque color. 11346 * 11347 * Subclasses of View should override this method whenever possible to indicate 11348 * whether an instance is opaque. Opaque Views are treated in a special way by 11349 * the View hierarchy, possibly allowing it to perform optimizations during 11350 * invalidate/draw passes. 11351 * 11352 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11353 */ 11354 @ViewDebug.ExportedProperty(category = "drawing") 11355 public boolean isOpaque() { 11356 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11357 getFinalAlpha() >= 1.0f; 11358 } 11359 11360 /** 11361 * @hide 11362 */ 11363 protected void computeOpaqueFlags() { 11364 // Opaque if: 11365 // - Has a background 11366 // - Background is opaque 11367 // - Doesn't have scrollbars or scrollbars overlay 11368 11369 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11370 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11371 } else { 11372 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11373 } 11374 11375 final int flags = mViewFlags; 11376 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11377 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11378 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11379 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11380 } else { 11381 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11382 } 11383 } 11384 11385 /** 11386 * @hide 11387 */ 11388 protected boolean hasOpaqueScrollbars() { 11389 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11390 } 11391 11392 /** 11393 * @return A handler associated with the thread running the View. This 11394 * handler can be used to pump events in the UI events queue. 11395 */ 11396 public Handler getHandler() { 11397 final AttachInfo attachInfo = mAttachInfo; 11398 if (attachInfo != null) { 11399 return attachInfo.mHandler; 11400 } 11401 return null; 11402 } 11403 11404 /** 11405 * Gets the view root associated with the View. 11406 * @return The view root, or null if none. 11407 * @hide 11408 */ 11409 public ViewRootImpl getViewRootImpl() { 11410 if (mAttachInfo != null) { 11411 return mAttachInfo.mViewRootImpl; 11412 } 11413 return null; 11414 } 11415 11416 /** 11417 * @hide 11418 */ 11419 public HardwareRenderer getHardwareRenderer() { 11420 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11421 } 11422 11423 /** 11424 * <p>Causes the Runnable to be added to the message queue. 11425 * The runnable will be run on the user interface thread.</p> 11426 * 11427 * @param action The Runnable that will be executed. 11428 * 11429 * @return Returns true if the Runnable was successfully placed in to the 11430 * message queue. Returns false on failure, usually because the 11431 * looper processing the message queue is exiting. 11432 * 11433 * @see #postDelayed 11434 * @see #removeCallbacks 11435 */ 11436 public boolean post(Runnable action) { 11437 final AttachInfo attachInfo = mAttachInfo; 11438 if (attachInfo != null) { 11439 return attachInfo.mHandler.post(action); 11440 } 11441 // Assume that post will succeed later 11442 ViewRootImpl.getRunQueue().post(action); 11443 return true; 11444 } 11445 11446 /** 11447 * <p>Causes the Runnable to be added to the message queue, to be run 11448 * after the specified amount of time elapses. 11449 * The runnable will be run on the user interface thread.</p> 11450 * 11451 * @param action The Runnable that will be executed. 11452 * @param delayMillis The delay (in milliseconds) until the Runnable 11453 * will be executed. 11454 * 11455 * @return true if the Runnable was successfully placed in to the 11456 * message queue. Returns false on failure, usually because the 11457 * looper processing the message queue is exiting. Note that a 11458 * result of true does not mean the Runnable will be processed -- 11459 * if the looper is quit before the delivery time of the message 11460 * occurs then the message will be dropped. 11461 * 11462 * @see #post 11463 * @see #removeCallbacks 11464 */ 11465 public boolean postDelayed(Runnable action, long delayMillis) { 11466 final AttachInfo attachInfo = mAttachInfo; 11467 if (attachInfo != null) { 11468 return attachInfo.mHandler.postDelayed(action, delayMillis); 11469 } 11470 // Assume that post will succeed later 11471 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11472 return true; 11473 } 11474 11475 /** 11476 * <p>Causes the Runnable to execute on the next animation time step. 11477 * The runnable will be run on the user interface thread.</p> 11478 * 11479 * @param action The Runnable that will be executed. 11480 * 11481 * @see #postOnAnimationDelayed 11482 * @see #removeCallbacks 11483 */ 11484 public void postOnAnimation(Runnable action) { 11485 final AttachInfo attachInfo = mAttachInfo; 11486 if (attachInfo != null) { 11487 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11488 Choreographer.CALLBACK_ANIMATION, action, null); 11489 } else { 11490 // Assume that post will succeed later 11491 ViewRootImpl.getRunQueue().post(action); 11492 } 11493 } 11494 11495 /** 11496 * <p>Causes the Runnable to execute on the next animation time step, 11497 * after the specified amount of time elapses. 11498 * The runnable will be run on the user interface thread.</p> 11499 * 11500 * @param action The Runnable that will be executed. 11501 * @param delayMillis The delay (in milliseconds) until the Runnable 11502 * will be executed. 11503 * 11504 * @see #postOnAnimation 11505 * @see #removeCallbacks 11506 */ 11507 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11508 final AttachInfo attachInfo = mAttachInfo; 11509 if (attachInfo != null) { 11510 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11511 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11512 } else { 11513 // Assume that post will succeed later 11514 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11515 } 11516 } 11517 11518 /** 11519 * <p>Removes the specified Runnable from the message queue.</p> 11520 * 11521 * @param action The Runnable to remove from the message handling queue 11522 * 11523 * @return true if this view could ask the Handler to remove the Runnable, 11524 * false otherwise. When the returned value is true, the Runnable 11525 * may or may not have been actually removed from the message queue 11526 * (for instance, if the Runnable was not in the queue already.) 11527 * 11528 * @see #post 11529 * @see #postDelayed 11530 * @see #postOnAnimation 11531 * @see #postOnAnimationDelayed 11532 */ 11533 public boolean removeCallbacks(Runnable action) { 11534 if (action != null) { 11535 final AttachInfo attachInfo = mAttachInfo; 11536 if (attachInfo != null) { 11537 attachInfo.mHandler.removeCallbacks(action); 11538 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11539 Choreographer.CALLBACK_ANIMATION, action, null); 11540 } 11541 // Assume that post will succeed later 11542 ViewRootImpl.getRunQueue().removeCallbacks(action); 11543 } 11544 return true; 11545 } 11546 11547 /** 11548 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11549 * Use this to invalidate the View from a non-UI thread.</p> 11550 * 11551 * <p>This method can be invoked from outside of the UI thread 11552 * only when this View is attached to a window.</p> 11553 * 11554 * @see #invalidate() 11555 * @see #postInvalidateDelayed(long) 11556 */ 11557 public void postInvalidate() { 11558 postInvalidateDelayed(0); 11559 } 11560 11561 /** 11562 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11563 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11564 * 11565 * <p>This method can be invoked from outside of the UI thread 11566 * only when this View is attached to a window.</p> 11567 * 11568 * @param left The left coordinate of the rectangle to invalidate. 11569 * @param top The top coordinate of the rectangle to invalidate. 11570 * @param right The right coordinate of the rectangle to invalidate. 11571 * @param bottom The bottom coordinate of the rectangle to invalidate. 11572 * 11573 * @see #invalidate(int, int, int, int) 11574 * @see #invalidate(Rect) 11575 * @see #postInvalidateDelayed(long, int, int, int, int) 11576 */ 11577 public void postInvalidate(int left, int top, int right, int bottom) { 11578 postInvalidateDelayed(0, left, top, right, bottom); 11579 } 11580 11581 /** 11582 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11583 * loop. Waits for the specified amount of time.</p> 11584 * 11585 * <p>This method can be invoked from outside of the UI thread 11586 * only when this View is attached to a window.</p> 11587 * 11588 * @param delayMilliseconds the duration in milliseconds to delay the 11589 * invalidation by 11590 * 11591 * @see #invalidate() 11592 * @see #postInvalidate() 11593 */ 11594 public void postInvalidateDelayed(long delayMilliseconds) { 11595 // We try only with the AttachInfo because there's no point in invalidating 11596 // if we are not attached to our window 11597 final AttachInfo attachInfo = mAttachInfo; 11598 if (attachInfo != null) { 11599 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11600 } 11601 } 11602 11603 /** 11604 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11605 * through the event loop. Waits for the specified amount of time.</p> 11606 * 11607 * <p>This method can be invoked from outside of the UI thread 11608 * only when this View is attached to a window.</p> 11609 * 11610 * @param delayMilliseconds the duration in milliseconds to delay the 11611 * invalidation by 11612 * @param left The left coordinate of the rectangle to invalidate. 11613 * @param top The top coordinate of the rectangle to invalidate. 11614 * @param right The right coordinate of the rectangle to invalidate. 11615 * @param bottom The bottom coordinate of the rectangle to invalidate. 11616 * 11617 * @see #invalidate(int, int, int, int) 11618 * @see #invalidate(Rect) 11619 * @see #postInvalidate(int, int, int, int) 11620 */ 11621 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11622 int right, int bottom) { 11623 11624 // We try only with the AttachInfo because there's no point in invalidating 11625 // if we are not attached to our window 11626 final AttachInfo attachInfo = mAttachInfo; 11627 if (attachInfo != null) { 11628 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11629 info.target = this; 11630 info.left = left; 11631 info.top = top; 11632 info.right = right; 11633 info.bottom = bottom; 11634 11635 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11636 } 11637 } 11638 11639 /** 11640 * <p>Cause an invalidate to happen on the next animation time step, typically the 11641 * next display frame.</p> 11642 * 11643 * <p>This method can be invoked from outside of the UI thread 11644 * only when this View is attached to a window.</p> 11645 * 11646 * @see #invalidate() 11647 */ 11648 public void postInvalidateOnAnimation() { 11649 // We try only with the AttachInfo because there's no point in invalidating 11650 // if we are not attached to our window 11651 final AttachInfo attachInfo = mAttachInfo; 11652 if (attachInfo != null) { 11653 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11654 } 11655 } 11656 11657 /** 11658 * <p>Cause an invalidate of the specified area to happen on the next animation 11659 * time step, typically the next display frame.</p> 11660 * 11661 * <p>This method can be invoked from outside of the UI thread 11662 * only when this View is attached to a window.</p> 11663 * 11664 * @param left The left coordinate of the rectangle to invalidate. 11665 * @param top The top coordinate of the rectangle to invalidate. 11666 * @param right The right coordinate of the rectangle to invalidate. 11667 * @param bottom The bottom coordinate of the rectangle to invalidate. 11668 * 11669 * @see #invalidate(int, int, int, int) 11670 * @see #invalidate(Rect) 11671 */ 11672 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11673 // We try only with the AttachInfo because there's no point in invalidating 11674 // if we are not attached to our window 11675 final AttachInfo attachInfo = mAttachInfo; 11676 if (attachInfo != null) { 11677 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11678 info.target = this; 11679 info.left = left; 11680 info.top = top; 11681 info.right = right; 11682 info.bottom = bottom; 11683 11684 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11685 } 11686 } 11687 11688 /** 11689 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11690 * This event is sent at most once every 11691 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11692 */ 11693 private void postSendViewScrolledAccessibilityEventCallback() { 11694 if (mSendViewScrolledAccessibilityEvent == null) { 11695 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11696 } 11697 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11698 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11699 postDelayed(mSendViewScrolledAccessibilityEvent, 11700 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11701 } 11702 } 11703 11704 /** 11705 * Called by a parent to request that a child update its values for mScrollX 11706 * and mScrollY if necessary. This will typically be done if the child is 11707 * animating a scroll using a {@link android.widget.Scroller Scroller} 11708 * object. 11709 */ 11710 public void computeScroll() { 11711 } 11712 11713 /** 11714 * <p>Indicate whether the horizontal edges are faded when the view is 11715 * scrolled horizontally.</p> 11716 * 11717 * @return true if the horizontal edges should are faded on scroll, false 11718 * otherwise 11719 * 11720 * @see #setHorizontalFadingEdgeEnabled(boolean) 11721 * 11722 * @attr ref android.R.styleable#View_requiresFadingEdge 11723 */ 11724 public boolean isHorizontalFadingEdgeEnabled() { 11725 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11726 } 11727 11728 /** 11729 * <p>Define whether the horizontal edges should be faded when this view 11730 * is scrolled horizontally.</p> 11731 * 11732 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11733 * be faded when the view is scrolled 11734 * horizontally 11735 * 11736 * @see #isHorizontalFadingEdgeEnabled() 11737 * 11738 * @attr ref android.R.styleable#View_requiresFadingEdge 11739 */ 11740 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11741 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11742 if (horizontalFadingEdgeEnabled) { 11743 initScrollCache(); 11744 } 11745 11746 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11747 } 11748 } 11749 11750 /** 11751 * <p>Indicate whether the vertical edges are faded when the view is 11752 * scrolled horizontally.</p> 11753 * 11754 * @return true if the vertical edges should are faded on scroll, false 11755 * otherwise 11756 * 11757 * @see #setVerticalFadingEdgeEnabled(boolean) 11758 * 11759 * @attr ref android.R.styleable#View_requiresFadingEdge 11760 */ 11761 public boolean isVerticalFadingEdgeEnabled() { 11762 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11763 } 11764 11765 /** 11766 * <p>Define whether the vertical edges should be faded when this view 11767 * is scrolled vertically.</p> 11768 * 11769 * @param verticalFadingEdgeEnabled true if the vertical edges should 11770 * be faded when the view is scrolled 11771 * vertically 11772 * 11773 * @see #isVerticalFadingEdgeEnabled() 11774 * 11775 * @attr ref android.R.styleable#View_requiresFadingEdge 11776 */ 11777 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11778 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11779 if (verticalFadingEdgeEnabled) { 11780 initScrollCache(); 11781 } 11782 11783 mViewFlags ^= FADING_EDGE_VERTICAL; 11784 } 11785 } 11786 11787 /** 11788 * Returns the strength, or intensity, of the top faded edge. The strength is 11789 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11790 * returns 0.0 or 1.0 but no value in between. 11791 * 11792 * Subclasses should override this method to provide a smoother fade transition 11793 * when scrolling occurs. 11794 * 11795 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11796 */ 11797 protected float getTopFadingEdgeStrength() { 11798 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11799 } 11800 11801 /** 11802 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11803 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11804 * returns 0.0 or 1.0 but no value in between. 11805 * 11806 * Subclasses should override this method to provide a smoother fade transition 11807 * when scrolling occurs. 11808 * 11809 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11810 */ 11811 protected float getBottomFadingEdgeStrength() { 11812 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11813 computeVerticalScrollRange() ? 1.0f : 0.0f; 11814 } 11815 11816 /** 11817 * Returns the strength, or intensity, of the left faded edge. The strength is 11818 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11819 * returns 0.0 or 1.0 but no value in between. 11820 * 11821 * Subclasses should override this method to provide a smoother fade transition 11822 * when scrolling occurs. 11823 * 11824 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11825 */ 11826 protected float getLeftFadingEdgeStrength() { 11827 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11828 } 11829 11830 /** 11831 * Returns the strength, or intensity, of the right faded edge. The strength is 11832 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11833 * returns 0.0 or 1.0 but no value in between. 11834 * 11835 * Subclasses should override this method to provide a smoother fade transition 11836 * when scrolling occurs. 11837 * 11838 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11839 */ 11840 protected float getRightFadingEdgeStrength() { 11841 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11842 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11843 } 11844 11845 /** 11846 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11847 * scrollbar is not drawn by default.</p> 11848 * 11849 * @return true if the horizontal scrollbar should be painted, false 11850 * otherwise 11851 * 11852 * @see #setHorizontalScrollBarEnabled(boolean) 11853 */ 11854 public boolean isHorizontalScrollBarEnabled() { 11855 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11856 } 11857 11858 /** 11859 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11860 * scrollbar is not drawn by default.</p> 11861 * 11862 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11863 * be painted 11864 * 11865 * @see #isHorizontalScrollBarEnabled() 11866 */ 11867 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11868 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11869 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11870 computeOpaqueFlags(); 11871 resolvePadding(); 11872 } 11873 } 11874 11875 /** 11876 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11877 * scrollbar is not drawn by default.</p> 11878 * 11879 * @return true if the vertical scrollbar should be painted, false 11880 * otherwise 11881 * 11882 * @see #setVerticalScrollBarEnabled(boolean) 11883 */ 11884 public boolean isVerticalScrollBarEnabled() { 11885 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11886 } 11887 11888 /** 11889 * <p>Define whether the vertical scrollbar should be drawn or not. The 11890 * scrollbar is not drawn by default.</p> 11891 * 11892 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11893 * be painted 11894 * 11895 * @see #isVerticalScrollBarEnabled() 11896 */ 11897 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11898 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11899 mViewFlags ^= SCROLLBARS_VERTICAL; 11900 computeOpaqueFlags(); 11901 resolvePadding(); 11902 } 11903 } 11904 11905 /** 11906 * @hide 11907 */ 11908 protected void recomputePadding() { 11909 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11910 } 11911 11912 /** 11913 * Define whether scrollbars will fade when the view is not scrolling. 11914 * 11915 * @param fadeScrollbars wheter to enable fading 11916 * 11917 * @attr ref android.R.styleable#View_fadeScrollbars 11918 */ 11919 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11920 initScrollCache(); 11921 final ScrollabilityCache scrollabilityCache = mScrollCache; 11922 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11923 if (fadeScrollbars) { 11924 scrollabilityCache.state = ScrollabilityCache.OFF; 11925 } else { 11926 scrollabilityCache.state = ScrollabilityCache.ON; 11927 } 11928 } 11929 11930 /** 11931 * 11932 * Returns true if scrollbars will fade when this view is not scrolling 11933 * 11934 * @return true if scrollbar fading is enabled 11935 * 11936 * @attr ref android.R.styleable#View_fadeScrollbars 11937 */ 11938 public boolean isScrollbarFadingEnabled() { 11939 return mScrollCache != null && mScrollCache.fadeScrollBars; 11940 } 11941 11942 /** 11943 * 11944 * Returns the delay before scrollbars fade. 11945 * 11946 * @return the delay before scrollbars fade 11947 * 11948 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11949 */ 11950 public int getScrollBarDefaultDelayBeforeFade() { 11951 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11952 mScrollCache.scrollBarDefaultDelayBeforeFade; 11953 } 11954 11955 /** 11956 * Define the delay before scrollbars fade. 11957 * 11958 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11959 * 11960 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11961 */ 11962 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11963 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11964 } 11965 11966 /** 11967 * 11968 * Returns the scrollbar fade duration. 11969 * 11970 * @return the scrollbar fade duration 11971 * 11972 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11973 */ 11974 public int getScrollBarFadeDuration() { 11975 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11976 mScrollCache.scrollBarFadeDuration; 11977 } 11978 11979 /** 11980 * Define the scrollbar fade duration. 11981 * 11982 * @param scrollBarFadeDuration - the scrollbar fade duration 11983 * 11984 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11985 */ 11986 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11987 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11988 } 11989 11990 /** 11991 * 11992 * Returns the scrollbar size. 11993 * 11994 * @return the scrollbar size 11995 * 11996 * @attr ref android.R.styleable#View_scrollbarSize 11997 */ 11998 public int getScrollBarSize() { 11999 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12000 mScrollCache.scrollBarSize; 12001 } 12002 12003 /** 12004 * Define the scrollbar size. 12005 * 12006 * @param scrollBarSize - the scrollbar size 12007 * 12008 * @attr ref android.R.styleable#View_scrollbarSize 12009 */ 12010 public void setScrollBarSize(int scrollBarSize) { 12011 getScrollCache().scrollBarSize = scrollBarSize; 12012 } 12013 12014 /** 12015 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12016 * inset. When inset, they add to the padding of the view. And the scrollbars 12017 * can be drawn inside the padding area or on the edge of the view. For example, 12018 * if a view has a background drawable and you want to draw the scrollbars 12019 * inside the padding specified by the drawable, you can use 12020 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12021 * appear at the edge of the view, ignoring the padding, then you can use 12022 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12023 * @param style the style of the scrollbars. Should be one of 12024 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12025 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12026 * @see #SCROLLBARS_INSIDE_OVERLAY 12027 * @see #SCROLLBARS_INSIDE_INSET 12028 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12029 * @see #SCROLLBARS_OUTSIDE_INSET 12030 * 12031 * @attr ref android.R.styleable#View_scrollbarStyle 12032 */ 12033 public void setScrollBarStyle(@ScrollBarStyle int style) { 12034 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12035 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12036 computeOpaqueFlags(); 12037 resolvePadding(); 12038 } 12039 } 12040 12041 /** 12042 * <p>Returns the current scrollbar style.</p> 12043 * @return the current scrollbar style 12044 * @see #SCROLLBARS_INSIDE_OVERLAY 12045 * @see #SCROLLBARS_INSIDE_INSET 12046 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12047 * @see #SCROLLBARS_OUTSIDE_INSET 12048 * 12049 * @attr ref android.R.styleable#View_scrollbarStyle 12050 */ 12051 @ViewDebug.ExportedProperty(mapping = { 12052 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12053 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12054 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12055 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12056 }) 12057 @ScrollBarStyle 12058 public int getScrollBarStyle() { 12059 return mViewFlags & SCROLLBARS_STYLE_MASK; 12060 } 12061 12062 /** 12063 * <p>Compute the horizontal range that the horizontal scrollbar 12064 * represents.</p> 12065 * 12066 * <p>The range is expressed in arbitrary units that must be the same as the 12067 * units used by {@link #computeHorizontalScrollExtent()} and 12068 * {@link #computeHorizontalScrollOffset()}.</p> 12069 * 12070 * <p>The default range is the drawing width of this view.</p> 12071 * 12072 * @return the total horizontal range represented by the horizontal 12073 * scrollbar 12074 * 12075 * @see #computeHorizontalScrollExtent() 12076 * @see #computeHorizontalScrollOffset() 12077 * @see android.widget.ScrollBarDrawable 12078 */ 12079 protected int computeHorizontalScrollRange() { 12080 return getWidth(); 12081 } 12082 12083 /** 12084 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12085 * within the horizontal range. This value is used to compute the position 12086 * of the thumb within the scrollbar's track.</p> 12087 * 12088 * <p>The range is expressed in arbitrary units that must be the same as the 12089 * units used by {@link #computeHorizontalScrollRange()} and 12090 * {@link #computeHorizontalScrollExtent()}.</p> 12091 * 12092 * <p>The default offset is the scroll offset of this view.</p> 12093 * 12094 * @return the horizontal offset of the scrollbar's thumb 12095 * 12096 * @see #computeHorizontalScrollRange() 12097 * @see #computeHorizontalScrollExtent() 12098 * @see android.widget.ScrollBarDrawable 12099 */ 12100 protected int computeHorizontalScrollOffset() { 12101 return mScrollX; 12102 } 12103 12104 /** 12105 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12106 * within the horizontal range. This value is used to compute the length 12107 * of the thumb within the scrollbar's track.</p> 12108 * 12109 * <p>The range is expressed in arbitrary units that must be the same as the 12110 * units used by {@link #computeHorizontalScrollRange()} and 12111 * {@link #computeHorizontalScrollOffset()}.</p> 12112 * 12113 * <p>The default extent is the drawing width of this view.</p> 12114 * 12115 * @return the horizontal extent of the scrollbar's thumb 12116 * 12117 * @see #computeHorizontalScrollRange() 12118 * @see #computeHorizontalScrollOffset() 12119 * @see android.widget.ScrollBarDrawable 12120 */ 12121 protected int computeHorizontalScrollExtent() { 12122 return getWidth(); 12123 } 12124 12125 /** 12126 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12127 * 12128 * <p>The range is expressed in arbitrary units that must be the same as the 12129 * units used by {@link #computeVerticalScrollExtent()} and 12130 * {@link #computeVerticalScrollOffset()}.</p> 12131 * 12132 * @return the total vertical range represented by the vertical scrollbar 12133 * 12134 * <p>The default range is the drawing height of this view.</p> 12135 * 12136 * @see #computeVerticalScrollExtent() 12137 * @see #computeVerticalScrollOffset() 12138 * @see android.widget.ScrollBarDrawable 12139 */ 12140 protected int computeVerticalScrollRange() { 12141 return getHeight(); 12142 } 12143 12144 /** 12145 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12146 * within the horizontal range. This value is used to compute the position 12147 * of the thumb within the scrollbar's track.</p> 12148 * 12149 * <p>The range is expressed in arbitrary units that must be the same as the 12150 * units used by {@link #computeVerticalScrollRange()} and 12151 * {@link #computeVerticalScrollExtent()}.</p> 12152 * 12153 * <p>The default offset is the scroll offset of this view.</p> 12154 * 12155 * @return the vertical offset of the scrollbar's thumb 12156 * 12157 * @see #computeVerticalScrollRange() 12158 * @see #computeVerticalScrollExtent() 12159 * @see android.widget.ScrollBarDrawable 12160 */ 12161 protected int computeVerticalScrollOffset() { 12162 return mScrollY; 12163 } 12164 12165 /** 12166 * <p>Compute the vertical extent of the horizontal scrollbar's thumb 12167 * within the vertical range. This value is used to compute the length 12168 * of the thumb within the scrollbar's track.</p> 12169 * 12170 * <p>The range is expressed in arbitrary units that must be the same as the 12171 * units used by {@link #computeVerticalScrollRange()} and 12172 * {@link #computeVerticalScrollOffset()}.</p> 12173 * 12174 * <p>The default extent is the drawing height of this view.</p> 12175 * 12176 * @return the vertical extent of the scrollbar's thumb 12177 * 12178 * @see #computeVerticalScrollRange() 12179 * @see #computeVerticalScrollOffset() 12180 * @see android.widget.ScrollBarDrawable 12181 */ 12182 protected int computeVerticalScrollExtent() { 12183 return getHeight(); 12184 } 12185 12186 /** 12187 * Check if this view can be scrolled horizontally in a certain direction. 12188 * 12189 * @param direction Negative to check scrolling left, positive to check scrolling right. 12190 * @return true if this view can be scrolled in the specified direction, false otherwise. 12191 */ 12192 public boolean canScrollHorizontally(int direction) { 12193 final int offset = computeHorizontalScrollOffset(); 12194 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12195 if (range == 0) return false; 12196 if (direction < 0) { 12197 return offset > 0; 12198 } else { 12199 return offset < range - 1; 12200 } 12201 } 12202 12203 /** 12204 * Check if this view can be scrolled vertically in a certain direction. 12205 * 12206 * @param direction Negative to check scrolling up, positive to check scrolling down. 12207 * @return true if this view can be scrolled in the specified direction, false otherwise. 12208 */ 12209 public boolean canScrollVertically(int direction) { 12210 final int offset = computeVerticalScrollOffset(); 12211 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12212 if (range == 0) return false; 12213 if (direction < 0) { 12214 return offset > 0; 12215 } else { 12216 return offset < range - 1; 12217 } 12218 } 12219 12220 /** 12221 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12222 * scrollbars are painted only if they have been awakened first.</p> 12223 * 12224 * @param canvas the canvas on which to draw the scrollbars 12225 * 12226 * @see #awakenScrollBars(int) 12227 */ 12228 protected final void onDrawScrollBars(Canvas canvas) { 12229 // scrollbars are drawn only when the animation is running 12230 final ScrollabilityCache cache = mScrollCache; 12231 if (cache != null) { 12232 12233 int state = cache.state; 12234 12235 if (state == ScrollabilityCache.OFF) { 12236 return; 12237 } 12238 12239 boolean invalidate = false; 12240 12241 if (state == ScrollabilityCache.FADING) { 12242 // We're fading -- get our fade interpolation 12243 if (cache.interpolatorValues == null) { 12244 cache.interpolatorValues = new float[1]; 12245 } 12246 12247 float[] values = cache.interpolatorValues; 12248 12249 // Stops the animation if we're done 12250 if (cache.scrollBarInterpolator.timeToValues(values) == 12251 Interpolator.Result.FREEZE_END) { 12252 cache.state = ScrollabilityCache.OFF; 12253 } else { 12254 cache.scrollBar.setAlpha(Math.round(values[0])); 12255 } 12256 12257 // This will make the scroll bars inval themselves after 12258 // drawing. We only want this when we're fading so that 12259 // we prevent excessive redraws 12260 invalidate = true; 12261 } else { 12262 // We're just on -- but we may have been fading before so 12263 // reset alpha 12264 cache.scrollBar.setAlpha(255); 12265 } 12266 12267 12268 final int viewFlags = mViewFlags; 12269 12270 final boolean drawHorizontalScrollBar = 12271 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12272 final boolean drawVerticalScrollBar = 12273 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12274 && !isVerticalScrollBarHidden(); 12275 12276 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12277 final int width = mRight - mLeft; 12278 final int height = mBottom - mTop; 12279 12280 final ScrollBarDrawable scrollBar = cache.scrollBar; 12281 12282 final int scrollX = mScrollX; 12283 final int scrollY = mScrollY; 12284 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12285 12286 int left; 12287 int top; 12288 int right; 12289 int bottom; 12290 12291 if (drawHorizontalScrollBar) { 12292 int size = scrollBar.getSize(false); 12293 if (size <= 0) { 12294 size = cache.scrollBarSize; 12295 } 12296 12297 scrollBar.setParameters(computeHorizontalScrollRange(), 12298 computeHorizontalScrollOffset(), 12299 computeHorizontalScrollExtent(), false); 12300 final int verticalScrollBarGap = drawVerticalScrollBar ? 12301 getVerticalScrollbarWidth() : 0; 12302 top = scrollY + height - size - (mUserPaddingBottom & inside); 12303 left = scrollX + (mPaddingLeft & inside); 12304 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12305 bottom = top + size; 12306 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12307 if (invalidate) { 12308 invalidate(left, top, right, bottom); 12309 } 12310 } 12311 12312 if (drawVerticalScrollBar) { 12313 int size = scrollBar.getSize(true); 12314 if (size <= 0) { 12315 size = cache.scrollBarSize; 12316 } 12317 12318 scrollBar.setParameters(computeVerticalScrollRange(), 12319 computeVerticalScrollOffset(), 12320 computeVerticalScrollExtent(), true); 12321 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12322 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12323 verticalScrollbarPosition = isLayoutRtl() ? 12324 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12325 } 12326 switch (verticalScrollbarPosition) { 12327 default: 12328 case SCROLLBAR_POSITION_RIGHT: 12329 left = scrollX + width - size - (mUserPaddingRight & inside); 12330 break; 12331 case SCROLLBAR_POSITION_LEFT: 12332 left = scrollX + (mUserPaddingLeft & inside); 12333 break; 12334 } 12335 top = scrollY + (mPaddingTop & inside); 12336 right = left + size; 12337 bottom = scrollY + height - (mUserPaddingBottom & inside); 12338 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12339 if (invalidate) { 12340 invalidate(left, top, right, bottom); 12341 } 12342 } 12343 } 12344 } 12345 } 12346 12347 /** 12348 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12349 * FastScroller is visible. 12350 * @return whether to temporarily hide the vertical scrollbar 12351 * @hide 12352 */ 12353 protected boolean isVerticalScrollBarHidden() { 12354 return false; 12355 } 12356 12357 /** 12358 * <p>Draw the horizontal scrollbar if 12359 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12360 * 12361 * @param canvas the canvas on which to draw the scrollbar 12362 * @param scrollBar the scrollbar's drawable 12363 * 12364 * @see #isHorizontalScrollBarEnabled() 12365 * @see #computeHorizontalScrollRange() 12366 * @see #computeHorizontalScrollExtent() 12367 * @see #computeHorizontalScrollOffset() 12368 * @see android.widget.ScrollBarDrawable 12369 * @hide 12370 */ 12371 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12372 int l, int t, int r, int b) { 12373 scrollBar.setBounds(l, t, r, b); 12374 scrollBar.draw(canvas); 12375 } 12376 12377 /** 12378 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12379 * returns true.</p> 12380 * 12381 * @param canvas the canvas on which to draw the scrollbar 12382 * @param scrollBar the scrollbar's drawable 12383 * 12384 * @see #isVerticalScrollBarEnabled() 12385 * @see #computeVerticalScrollRange() 12386 * @see #computeVerticalScrollExtent() 12387 * @see #computeVerticalScrollOffset() 12388 * @see android.widget.ScrollBarDrawable 12389 * @hide 12390 */ 12391 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12392 int l, int t, int r, int b) { 12393 scrollBar.setBounds(l, t, r, b); 12394 scrollBar.draw(canvas); 12395 } 12396 12397 /** 12398 * Implement this to do your drawing. 12399 * 12400 * @param canvas the canvas on which the background will be drawn 12401 */ 12402 protected void onDraw(Canvas canvas) { 12403 } 12404 12405 /* 12406 * Caller is responsible for calling requestLayout if necessary. 12407 * (This allows addViewInLayout to not request a new layout.) 12408 */ 12409 void assignParent(ViewParent parent) { 12410 if (mParent == null) { 12411 mParent = parent; 12412 } else if (parent == null) { 12413 mParent = null; 12414 } else { 12415 throw new RuntimeException("view " + this + " being added, but" 12416 + " it already has a parent"); 12417 } 12418 } 12419 12420 /** 12421 * This is called when the view is attached to a window. At this point it 12422 * has a Surface and will start drawing. Note that this function is 12423 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12424 * however it may be called any time before the first onDraw -- including 12425 * before or after {@link #onMeasure(int, int)}. 12426 * 12427 * @see #onDetachedFromWindow() 12428 */ 12429 protected void onAttachedToWindow() { 12430 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12431 mParent.requestTransparentRegion(this); 12432 } 12433 12434 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12435 initialAwakenScrollBars(); 12436 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12437 } 12438 12439 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12440 12441 jumpDrawablesToCurrentState(); 12442 12443 resetSubtreeAccessibilityStateChanged(); 12444 12445 if (isFocused()) { 12446 InputMethodManager imm = InputMethodManager.peekInstance(); 12447 imm.focusIn(this); 12448 } 12449 12450 if (mDisplayList != null) { 12451 mDisplayList.clearDirty(); 12452 } 12453 } 12454 12455 /** 12456 * Resolve all RTL related properties. 12457 * 12458 * @return true if resolution of RTL properties has been done 12459 * 12460 * @hide 12461 */ 12462 public boolean resolveRtlPropertiesIfNeeded() { 12463 if (!needRtlPropertiesResolution()) return false; 12464 12465 // Order is important here: LayoutDirection MUST be resolved first 12466 if (!isLayoutDirectionResolved()) { 12467 resolveLayoutDirection(); 12468 resolveLayoutParams(); 12469 } 12470 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12471 if (!isTextDirectionResolved()) { 12472 resolveTextDirection(); 12473 } 12474 if (!isTextAlignmentResolved()) { 12475 resolveTextAlignment(); 12476 } 12477 // Should resolve Drawables before Padding because we need the layout direction of the 12478 // Drawable to correctly resolve Padding. 12479 if (!isDrawablesResolved()) { 12480 resolveDrawables(); 12481 } 12482 if (!isPaddingResolved()) { 12483 resolvePadding(); 12484 } 12485 onRtlPropertiesChanged(getLayoutDirection()); 12486 return true; 12487 } 12488 12489 /** 12490 * Reset resolution of all RTL related properties. 12491 * 12492 * @hide 12493 */ 12494 public void resetRtlProperties() { 12495 resetResolvedLayoutDirection(); 12496 resetResolvedTextDirection(); 12497 resetResolvedTextAlignment(); 12498 resetResolvedPadding(); 12499 resetResolvedDrawables(); 12500 } 12501 12502 /** 12503 * @see #onScreenStateChanged(int) 12504 */ 12505 void dispatchScreenStateChanged(int screenState) { 12506 onScreenStateChanged(screenState); 12507 } 12508 12509 /** 12510 * This method is called whenever the state of the screen this view is 12511 * attached to changes. A state change will usually occurs when the screen 12512 * turns on or off (whether it happens automatically or the user does it 12513 * manually.) 12514 * 12515 * @param screenState The new state of the screen. Can be either 12516 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12517 */ 12518 public void onScreenStateChanged(int screenState) { 12519 } 12520 12521 /** 12522 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12523 */ 12524 private boolean hasRtlSupport() { 12525 return mContext.getApplicationInfo().hasRtlSupport(); 12526 } 12527 12528 /** 12529 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12530 * RTL not supported) 12531 */ 12532 private boolean isRtlCompatibilityMode() { 12533 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12534 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12535 } 12536 12537 /** 12538 * @return true if RTL properties need resolution. 12539 * 12540 */ 12541 private boolean needRtlPropertiesResolution() { 12542 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12543 } 12544 12545 /** 12546 * Called when any RTL property (layout direction or text direction or text alignment) has 12547 * been changed. 12548 * 12549 * Subclasses need to override this method to take care of cached information that depends on the 12550 * resolved layout direction, or to inform child views that inherit their layout direction. 12551 * 12552 * The default implementation does nothing. 12553 * 12554 * @param layoutDirection the direction of the layout 12555 * 12556 * @see #LAYOUT_DIRECTION_LTR 12557 * @see #LAYOUT_DIRECTION_RTL 12558 */ 12559 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12560 } 12561 12562 /** 12563 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12564 * that the parent directionality can and will be resolved before its children. 12565 * 12566 * @return true if resolution has been done, false otherwise. 12567 * 12568 * @hide 12569 */ 12570 public boolean resolveLayoutDirection() { 12571 // Clear any previous layout direction resolution 12572 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12573 12574 if (hasRtlSupport()) { 12575 // Set resolved depending on layout direction 12576 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12577 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12578 case LAYOUT_DIRECTION_INHERIT: 12579 // We cannot resolve yet. LTR is by default and let the resolution happen again 12580 // later to get the correct resolved value 12581 if (!canResolveLayoutDirection()) return false; 12582 12583 // Parent has not yet resolved, LTR is still the default 12584 try { 12585 if (!mParent.isLayoutDirectionResolved()) return false; 12586 12587 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12588 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12589 } 12590 } catch (AbstractMethodError e) { 12591 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12592 " does not fully implement ViewParent", e); 12593 } 12594 break; 12595 case LAYOUT_DIRECTION_RTL: 12596 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12597 break; 12598 case LAYOUT_DIRECTION_LOCALE: 12599 if((LAYOUT_DIRECTION_RTL == 12600 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12601 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12602 } 12603 break; 12604 default: 12605 // Nothing to do, LTR by default 12606 } 12607 } 12608 12609 // Set to resolved 12610 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12611 return true; 12612 } 12613 12614 /** 12615 * Check if layout direction resolution can be done. 12616 * 12617 * @return true if layout direction resolution can be done otherwise return false. 12618 */ 12619 public boolean canResolveLayoutDirection() { 12620 switch (getRawLayoutDirection()) { 12621 case LAYOUT_DIRECTION_INHERIT: 12622 if (mParent != null) { 12623 try { 12624 return mParent.canResolveLayoutDirection(); 12625 } catch (AbstractMethodError e) { 12626 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12627 " does not fully implement ViewParent", e); 12628 } 12629 } 12630 return false; 12631 12632 default: 12633 return true; 12634 } 12635 } 12636 12637 /** 12638 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12639 * {@link #onMeasure(int, int)}. 12640 * 12641 * @hide 12642 */ 12643 public void resetResolvedLayoutDirection() { 12644 // Reset the current resolved bits 12645 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12646 } 12647 12648 /** 12649 * @return true if the layout direction is inherited. 12650 * 12651 * @hide 12652 */ 12653 public boolean isLayoutDirectionInherited() { 12654 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12655 } 12656 12657 /** 12658 * @return true if layout direction has been resolved. 12659 */ 12660 public boolean isLayoutDirectionResolved() { 12661 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12662 } 12663 12664 /** 12665 * Return if padding has been resolved 12666 * 12667 * @hide 12668 */ 12669 boolean isPaddingResolved() { 12670 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12671 } 12672 12673 /** 12674 * Resolves padding depending on layout direction, if applicable, and 12675 * recomputes internal padding values to adjust for scroll bars. 12676 * 12677 * @hide 12678 */ 12679 public void resolvePadding() { 12680 final int resolvedLayoutDirection = getLayoutDirection(); 12681 12682 if (!isRtlCompatibilityMode()) { 12683 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12684 // If start / end padding are defined, they will be resolved (hence overriding) to 12685 // left / right or right / left depending on the resolved layout direction. 12686 // If start / end padding are not defined, use the left / right ones. 12687 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12688 Rect padding = sThreadLocal.get(); 12689 if (padding == null) { 12690 padding = new Rect(); 12691 sThreadLocal.set(padding); 12692 } 12693 mBackground.getPadding(padding); 12694 if (!mLeftPaddingDefined) { 12695 mUserPaddingLeftInitial = padding.left; 12696 } 12697 if (!mRightPaddingDefined) { 12698 mUserPaddingRightInitial = padding.right; 12699 } 12700 } 12701 switch (resolvedLayoutDirection) { 12702 case LAYOUT_DIRECTION_RTL: 12703 if (mUserPaddingStart != UNDEFINED_PADDING) { 12704 mUserPaddingRight = mUserPaddingStart; 12705 } else { 12706 mUserPaddingRight = mUserPaddingRightInitial; 12707 } 12708 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12709 mUserPaddingLeft = mUserPaddingEnd; 12710 } else { 12711 mUserPaddingLeft = mUserPaddingLeftInitial; 12712 } 12713 break; 12714 case LAYOUT_DIRECTION_LTR: 12715 default: 12716 if (mUserPaddingStart != UNDEFINED_PADDING) { 12717 mUserPaddingLeft = mUserPaddingStart; 12718 } else { 12719 mUserPaddingLeft = mUserPaddingLeftInitial; 12720 } 12721 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12722 mUserPaddingRight = mUserPaddingEnd; 12723 } else { 12724 mUserPaddingRight = mUserPaddingRightInitial; 12725 } 12726 } 12727 12728 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12729 } 12730 12731 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12732 onRtlPropertiesChanged(resolvedLayoutDirection); 12733 12734 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12735 } 12736 12737 /** 12738 * Reset the resolved layout direction. 12739 * 12740 * @hide 12741 */ 12742 public void resetResolvedPadding() { 12743 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12744 } 12745 12746 /** 12747 * This is called when the view is detached from a window. At this point it 12748 * no longer has a surface for drawing. 12749 * 12750 * @see #onAttachedToWindow() 12751 */ 12752 protected void onDetachedFromWindow() { 12753 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12754 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12755 12756 removeUnsetPressCallback(); 12757 removeLongPressCallback(); 12758 removePerformClickCallback(); 12759 removeSendViewScrolledAccessibilityEventCallback(); 12760 12761 destroyDrawingCache(); 12762 destroyLayer(false); 12763 12764 cleanupDraw(); 12765 12766 mCurrentAnimation = null; 12767 } 12768 12769 private void cleanupDraw() { 12770 if (mAttachInfo != null) { 12771 if (mDisplayList != null) { 12772 mDisplayList.markDirty(); 12773 mAttachInfo.mViewRootImpl.enqueueDisplayList(mDisplayList); 12774 } 12775 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12776 } else { 12777 // Should never happen 12778 resetDisplayList(); 12779 } 12780 } 12781 12782 /** 12783 * This method ensures the hardware renderer is in a valid state 12784 * before executing the specified action. 12785 * 12786 * This method will attempt to set a valid state even if the window 12787 * the renderer is attached to was destroyed. 12788 * 12789 * This method is not guaranteed to work. If the hardware renderer 12790 * does not exist or cannot be put in a valid state, this method 12791 * will not executed the specified action. 12792 * 12793 * The specified action is executed synchronously. 12794 * 12795 * @param action The action to execute after the renderer is in a valid state 12796 * 12797 * @return True if the specified Runnable was executed, false otherwise 12798 * 12799 * @hide 12800 */ 12801 public boolean executeHardwareAction(Runnable action) { 12802 //noinspection SimplifiableIfStatement 12803 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12804 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12805 } 12806 return false; 12807 } 12808 12809 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12810 } 12811 12812 /** 12813 * @return The number of times this view has been attached to a window 12814 */ 12815 protected int getWindowAttachCount() { 12816 return mWindowAttachCount; 12817 } 12818 12819 /** 12820 * Retrieve a unique token identifying the window this view is attached to. 12821 * @return Return the window's token for use in 12822 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12823 */ 12824 public IBinder getWindowToken() { 12825 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12826 } 12827 12828 /** 12829 * Retrieve the {@link WindowId} for the window this view is 12830 * currently attached to. 12831 */ 12832 public WindowId getWindowId() { 12833 if (mAttachInfo == null) { 12834 return null; 12835 } 12836 if (mAttachInfo.mWindowId == null) { 12837 try { 12838 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12839 mAttachInfo.mWindowToken); 12840 mAttachInfo.mWindowId = new WindowId( 12841 mAttachInfo.mIWindowId); 12842 } catch (RemoteException e) { 12843 } 12844 } 12845 return mAttachInfo.mWindowId; 12846 } 12847 12848 /** 12849 * Retrieve a unique token identifying the top-level "real" window of 12850 * the window that this view is attached to. That is, this is like 12851 * {@link #getWindowToken}, except if the window this view in is a panel 12852 * window (attached to another containing window), then the token of 12853 * the containing window is returned instead. 12854 * 12855 * @return Returns the associated window token, either 12856 * {@link #getWindowToken()} or the containing window's token. 12857 */ 12858 public IBinder getApplicationWindowToken() { 12859 AttachInfo ai = mAttachInfo; 12860 if (ai != null) { 12861 IBinder appWindowToken = ai.mPanelParentWindowToken; 12862 if (appWindowToken == null) { 12863 appWindowToken = ai.mWindowToken; 12864 } 12865 return appWindowToken; 12866 } 12867 return null; 12868 } 12869 12870 /** 12871 * Gets the logical display to which the view's window has been attached. 12872 * 12873 * @return The logical display, or null if the view is not currently attached to a window. 12874 */ 12875 public Display getDisplay() { 12876 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12877 } 12878 12879 /** 12880 * Retrieve private session object this view hierarchy is using to 12881 * communicate with the window manager. 12882 * @return the session object to communicate with the window manager 12883 */ 12884 /*package*/ IWindowSession getWindowSession() { 12885 return mAttachInfo != null ? mAttachInfo.mSession : null; 12886 } 12887 12888 /** 12889 * @param info the {@link android.view.View.AttachInfo} to associated with 12890 * this view 12891 */ 12892 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12893 //System.out.println("Attached! " + this); 12894 mAttachInfo = info; 12895 if (mOverlay != null) { 12896 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12897 } 12898 mWindowAttachCount++; 12899 // We will need to evaluate the drawable state at least once. 12900 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12901 if (mFloatingTreeObserver != null) { 12902 info.mTreeObserver.merge(mFloatingTreeObserver); 12903 mFloatingTreeObserver = null; 12904 } 12905 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12906 mAttachInfo.mScrollContainers.add(this); 12907 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12908 } 12909 performCollectViewAttributes(mAttachInfo, visibility); 12910 onAttachedToWindow(); 12911 12912 ListenerInfo li = mListenerInfo; 12913 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12914 li != null ? li.mOnAttachStateChangeListeners : null; 12915 if (listeners != null && listeners.size() > 0) { 12916 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12917 // perform the dispatching. The iterator is a safe guard against listeners that 12918 // could mutate the list by calling the various add/remove methods. This prevents 12919 // the array from being modified while we iterate it. 12920 for (OnAttachStateChangeListener listener : listeners) { 12921 listener.onViewAttachedToWindow(this); 12922 } 12923 } 12924 12925 int vis = info.mWindowVisibility; 12926 if (vis != GONE) { 12927 onWindowVisibilityChanged(vis); 12928 } 12929 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12930 // If nobody has evaluated the drawable state yet, then do it now. 12931 refreshDrawableState(); 12932 } 12933 needGlobalAttributesUpdate(false); 12934 } 12935 12936 void dispatchDetachedFromWindow() { 12937 AttachInfo info = mAttachInfo; 12938 if (info != null) { 12939 int vis = info.mWindowVisibility; 12940 if (vis != GONE) { 12941 onWindowVisibilityChanged(GONE); 12942 } 12943 } 12944 12945 onDetachedFromWindow(); 12946 12947 ListenerInfo li = mListenerInfo; 12948 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12949 li != null ? li.mOnAttachStateChangeListeners : null; 12950 if (listeners != null && listeners.size() > 0) { 12951 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12952 // perform the dispatching. The iterator is a safe guard against listeners that 12953 // could mutate the list by calling the various add/remove methods. This prevents 12954 // the array from being modified while we iterate it. 12955 for (OnAttachStateChangeListener listener : listeners) { 12956 listener.onViewDetachedFromWindow(this); 12957 } 12958 } 12959 12960 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12961 mAttachInfo.mScrollContainers.remove(this); 12962 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12963 } 12964 12965 mAttachInfo = null; 12966 if (mOverlay != null) { 12967 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12968 } 12969 } 12970 12971 /** 12972 * Cancel any deferred high-level input events that were previously posted to the event queue. 12973 * 12974 * <p>Many views post high-level events such as click handlers to the event queue 12975 * to run deferred in order to preserve a desired user experience - clearing visible 12976 * pressed states before executing, etc. This method will abort any events of this nature 12977 * that are currently in flight.</p> 12978 * 12979 * <p>Custom views that generate their own high-level deferred input events should override 12980 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 12981 * 12982 * <p>This will also cancel pending input events for any child views.</p> 12983 * 12984 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 12985 * This will not impact newer events posted after this call that may occur as a result of 12986 * lower-level input events still waiting in the queue. If you are trying to prevent 12987 * double-submitted events for the duration of some sort of asynchronous transaction 12988 * you should also take other steps to protect against unexpected double inputs e.g. calling 12989 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 12990 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 12991 */ 12992 public final void cancelPendingInputEvents() { 12993 dispatchCancelPendingInputEvents(); 12994 } 12995 12996 /** 12997 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 12998 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 12999 */ 13000 void dispatchCancelPendingInputEvents() { 13001 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13002 onCancelPendingInputEvents(); 13003 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13004 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13005 " did not call through to super.onCancelPendingInputEvents()"); 13006 } 13007 } 13008 13009 /** 13010 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13011 * a parent view. 13012 * 13013 * <p>This method is responsible for removing any pending high-level input events that were 13014 * posted to the event queue to run later. Custom view classes that post their own deferred 13015 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13016 * {@link android.os.Handler} should override this method, call 13017 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13018 * </p> 13019 */ 13020 public void onCancelPendingInputEvents() { 13021 removePerformClickCallback(); 13022 cancelLongPress(); 13023 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13024 } 13025 13026 /** 13027 * Store this view hierarchy's frozen state into the given container. 13028 * 13029 * @param container The SparseArray in which to save the view's state. 13030 * 13031 * @see #restoreHierarchyState(android.util.SparseArray) 13032 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13033 * @see #onSaveInstanceState() 13034 */ 13035 public void saveHierarchyState(SparseArray<Parcelable> container) { 13036 dispatchSaveInstanceState(container); 13037 } 13038 13039 /** 13040 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13041 * this view and its children. May be overridden to modify how freezing happens to a 13042 * view's children; for example, some views may want to not store state for their children. 13043 * 13044 * @param container The SparseArray in which to save the view's state. 13045 * 13046 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13047 * @see #saveHierarchyState(android.util.SparseArray) 13048 * @see #onSaveInstanceState() 13049 */ 13050 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13051 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13052 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13053 Parcelable state = onSaveInstanceState(); 13054 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13055 throw new IllegalStateException( 13056 "Derived class did not call super.onSaveInstanceState()"); 13057 } 13058 if (state != null) { 13059 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13060 // + ": " + state); 13061 container.put(mID, state); 13062 } 13063 } 13064 } 13065 13066 /** 13067 * Hook allowing a view to generate a representation of its internal state 13068 * that can later be used to create a new instance with that same state. 13069 * This state should only contain information that is not persistent or can 13070 * not be reconstructed later. For example, you will never store your 13071 * current position on screen because that will be computed again when a 13072 * new instance of the view is placed in its view hierarchy. 13073 * <p> 13074 * Some examples of things you may store here: the current cursor position 13075 * in a text view (but usually not the text itself since that is stored in a 13076 * content provider or other persistent storage), the currently selected 13077 * item in a list view. 13078 * 13079 * @return Returns a Parcelable object containing the view's current dynamic 13080 * state, or null if there is nothing interesting to save. The 13081 * default implementation returns null. 13082 * @see #onRestoreInstanceState(android.os.Parcelable) 13083 * @see #saveHierarchyState(android.util.SparseArray) 13084 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13085 * @see #setSaveEnabled(boolean) 13086 */ 13087 protected Parcelable onSaveInstanceState() { 13088 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13089 return BaseSavedState.EMPTY_STATE; 13090 } 13091 13092 /** 13093 * Restore this view hierarchy's frozen state from the given container. 13094 * 13095 * @param container The SparseArray which holds previously frozen states. 13096 * 13097 * @see #saveHierarchyState(android.util.SparseArray) 13098 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13099 * @see #onRestoreInstanceState(android.os.Parcelable) 13100 */ 13101 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13102 dispatchRestoreInstanceState(container); 13103 } 13104 13105 /** 13106 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13107 * state for this view and its children. May be overridden to modify how restoring 13108 * happens to a view's children; for example, some views may want to not store state 13109 * for their children. 13110 * 13111 * @param container The SparseArray which holds previously saved state. 13112 * 13113 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13114 * @see #restoreHierarchyState(android.util.SparseArray) 13115 * @see #onRestoreInstanceState(android.os.Parcelable) 13116 */ 13117 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13118 if (mID != NO_ID) { 13119 Parcelable state = container.get(mID); 13120 if (state != null) { 13121 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13122 // + ": " + state); 13123 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13124 onRestoreInstanceState(state); 13125 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13126 throw new IllegalStateException( 13127 "Derived class did not call super.onRestoreInstanceState()"); 13128 } 13129 } 13130 } 13131 } 13132 13133 /** 13134 * Hook allowing a view to re-apply a representation of its internal state that had previously 13135 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13136 * null state. 13137 * 13138 * @param state The frozen state that had previously been returned by 13139 * {@link #onSaveInstanceState}. 13140 * 13141 * @see #onSaveInstanceState() 13142 * @see #restoreHierarchyState(android.util.SparseArray) 13143 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13144 */ 13145 protected void onRestoreInstanceState(Parcelable state) { 13146 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13147 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13148 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13149 + "received " + state.getClass().toString() + " instead. This usually happens " 13150 + "when two views of different type have the same id in the same hierarchy. " 13151 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13152 + "other views do not use the same id."); 13153 } 13154 } 13155 13156 /** 13157 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13158 * 13159 * @return the drawing start time in milliseconds 13160 */ 13161 public long getDrawingTime() { 13162 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13163 } 13164 13165 /** 13166 * <p>Enables or disables the duplication of the parent's state into this view. When 13167 * duplication is enabled, this view gets its drawable state from its parent rather 13168 * than from its own internal properties.</p> 13169 * 13170 * <p>Note: in the current implementation, setting this property to true after the 13171 * view was added to a ViewGroup might have no effect at all. This property should 13172 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13173 * 13174 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13175 * property is enabled, an exception will be thrown.</p> 13176 * 13177 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13178 * parent, these states should not be affected by this method.</p> 13179 * 13180 * @param enabled True to enable duplication of the parent's drawable state, false 13181 * to disable it. 13182 * 13183 * @see #getDrawableState() 13184 * @see #isDuplicateParentStateEnabled() 13185 */ 13186 public void setDuplicateParentStateEnabled(boolean enabled) { 13187 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13188 } 13189 13190 /** 13191 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13192 * 13193 * @return True if this view's drawable state is duplicated from the parent, 13194 * false otherwise 13195 * 13196 * @see #getDrawableState() 13197 * @see #setDuplicateParentStateEnabled(boolean) 13198 */ 13199 public boolean isDuplicateParentStateEnabled() { 13200 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13201 } 13202 13203 /** 13204 * <p>Specifies the type of layer backing this view. The layer can be 13205 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13206 * {@link #LAYER_TYPE_HARDWARE}.</p> 13207 * 13208 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13209 * instance that controls how the layer is composed on screen. The following 13210 * properties of the paint are taken into account when composing the layer:</p> 13211 * <ul> 13212 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13213 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13214 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13215 * </ul> 13216 * 13217 * <p>If this view has an alpha value set to < 1.0 by calling 13218 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13219 * by this view's alpha value.</p> 13220 * 13221 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13222 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13223 * for more information on when and how to use layers.</p> 13224 * 13225 * @param layerType The type of layer to use with this view, must be one of 13226 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13227 * {@link #LAYER_TYPE_HARDWARE} 13228 * @param paint The paint used to compose the layer. This argument is optional 13229 * and can be null. It is ignored when the layer type is 13230 * {@link #LAYER_TYPE_NONE} 13231 * 13232 * @see #getLayerType() 13233 * @see #LAYER_TYPE_NONE 13234 * @see #LAYER_TYPE_SOFTWARE 13235 * @see #LAYER_TYPE_HARDWARE 13236 * @see #setAlpha(float) 13237 * 13238 * @attr ref android.R.styleable#View_layerType 13239 */ 13240 public void setLayerType(int layerType, Paint paint) { 13241 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13242 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13243 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13244 } 13245 13246 if (layerType == mLayerType) { 13247 if (layerType != LAYER_TYPE_NONE && paint != mLayerPaint) { 13248 mLayerPaint = paint == null ? new Paint() : paint; 13249 invalidateParentCaches(); 13250 invalidate(true); 13251 } 13252 return; 13253 } 13254 13255 // Destroy any previous software drawing cache if needed 13256 switch (mLayerType) { 13257 case LAYER_TYPE_HARDWARE: 13258 destroyLayer(false); 13259 // fall through - non-accelerated views may use software layer mechanism instead 13260 case LAYER_TYPE_SOFTWARE: 13261 destroyDrawingCache(); 13262 break; 13263 default: 13264 break; 13265 } 13266 13267 mLayerType = layerType; 13268 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13269 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13270 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13271 13272 invalidateParentCaches(); 13273 invalidate(true); 13274 } 13275 13276 /** 13277 * Updates the {@link Paint} object used with the current layer (used only if the current 13278 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13279 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13280 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13281 * ensure that the view gets redrawn immediately. 13282 * 13283 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13284 * instance that controls how the layer is composed on screen. The following 13285 * properties of the paint are taken into account when composing the layer:</p> 13286 * <ul> 13287 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13288 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13289 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13290 * </ul> 13291 * 13292 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13293 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13294 * 13295 * @param paint The paint used to compose the layer. This argument is optional 13296 * and can be null. It is ignored when the layer type is 13297 * {@link #LAYER_TYPE_NONE} 13298 * 13299 * @see #setLayerType(int, android.graphics.Paint) 13300 */ 13301 public void setLayerPaint(Paint paint) { 13302 int layerType = getLayerType(); 13303 if (layerType != LAYER_TYPE_NONE) { 13304 mLayerPaint = paint == null ? new Paint() : paint; 13305 if (layerType == LAYER_TYPE_HARDWARE) { 13306 HardwareLayer layer = getHardwareLayer(); 13307 if (layer != null) { 13308 layer.setLayerPaint(paint); 13309 } 13310 invalidateViewProperty(false, false); 13311 } else { 13312 invalidate(); 13313 } 13314 } 13315 } 13316 13317 /** 13318 * Indicates whether this view has a static layer. A view with layer type 13319 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13320 * dynamic. 13321 */ 13322 boolean hasStaticLayer() { 13323 return true; 13324 } 13325 13326 /** 13327 * Indicates what type of layer is currently associated with this view. By default 13328 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13329 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13330 * for more information on the different types of layers. 13331 * 13332 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13333 * {@link #LAYER_TYPE_HARDWARE} 13334 * 13335 * @see #setLayerType(int, android.graphics.Paint) 13336 * @see #buildLayer() 13337 * @see #LAYER_TYPE_NONE 13338 * @see #LAYER_TYPE_SOFTWARE 13339 * @see #LAYER_TYPE_HARDWARE 13340 */ 13341 public int getLayerType() { 13342 return mLayerType; 13343 } 13344 13345 /** 13346 * Forces this view's layer to be created and this view to be rendered 13347 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13348 * invoking this method will have no effect. 13349 * 13350 * This method can for instance be used to render a view into its layer before 13351 * starting an animation. If this view is complex, rendering into the layer 13352 * before starting the animation will avoid skipping frames. 13353 * 13354 * @throws IllegalStateException If this view is not attached to a window 13355 * 13356 * @see #setLayerType(int, android.graphics.Paint) 13357 */ 13358 public void buildLayer() { 13359 if (mLayerType == LAYER_TYPE_NONE) return; 13360 13361 final AttachInfo attachInfo = mAttachInfo; 13362 if (attachInfo == null) { 13363 throw new IllegalStateException("This view must be attached to a window first"); 13364 } 13365 13366 switch (mLayerType) { 13367 case LAYER_TYPE_HARDWARE: 13368 if (attachInfo.mHardwareRenderer != null && 13369 attachInfo.mHardwareRenderer.isEnabled() && 13370 attachInfo.mHardwareRenderer.validate()) { 13371 getHardwareLayer(); 13372 // TODO: We need a better way to handle this case 13373 // If views have registered pre-draw listeners they need 13374 // to be notified before we build the layer. Those listeners 13375 // may however rely on other events to happen first so we 13376 // cannot just invoke them here until they don't cancel the 13377 // current frame 13378 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13379 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13380 } 13381 } 13382 break; 13383 case LAYER_TYPE_SOFTWARE: 13384 buildDrawingCache(true); 13385 break; 13386 } 13387 } 13388 13389 /** 13390 * <p>Returns a hardware layer that can be used to draw this view again 13391 * without executing its draw method.</p> 13392 * 13393 * @return A HardwareLayer ready to render, or null if an error occurred. 13394 */ 13395 HardwareLayer getHardwareLayer() { 13396 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13397 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13398 return null; 13399 } 13400 13401 if (!mAttachInfo.mHardwareRenderer.validate()) return null; 13402 13403 final int width = mRight - mLeft; 13404 final int height = mBottom - mTop; 13405 13406 if (width == 0 || height == 0) { 13407 return null; 13408 } 13409 13410 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13411 if (mHardwareLayer == null) { 13412 mHardwareLayer = mAttachInfo.mHardwareRenderer.createHardwareLayer( 13413 width, height, isOpaque()); 13414 mLocalDirtyRect.set(0, 0, width, height); 13415 } else { 13416 if (mHardwareLayer.getWidth() != width || mHardwareLayer.getHeight() != height) { 13417 if (mHardwareLayer.resize(width, height)) { 13418 mLocalDirtyRect.set(0, 0, width, height); 13419 } 13420 } 13421 13422 // This should not be necessary but applications that change 13423 // the parameters of their background drawable without calling 13424 // this.setBackground(Drawable) can leave the view in a bad state 13425 // (for instance isOpaque() returns true, but the background is 13426 // not opaque.) 13427 computeOpaqueFlags(); 13428 13429 final boolean opaque = isOpaque(); 13430 if (mHardwareLayer.isValid() && mHardwareLayer.isOpaque() != opaque) { 13431 mHardwareLayer.setOpaque(opaque); 13432 mLocalDirtyRect.set(0, 0, width, height); 13433 } 13434 } 13435 13436 // The layer is not valid if the underlying GPU resources cannot be allocated 13437 if (!mHardwareLayer.isValid()) { 13438 return null; 13439 } 13440 13441 mHardwareLayer.setLayerPaint(mLayerPaint); 13442 mHardwareLayer.redrawLater(getHardwareLayerDisplayList(mHardwareLayer), mLocalDirtyRect); 13443 ViewRootImpl viewRoot = getViewRootImpl(); 13444 if (viewRoot != null) viewRoot.pushHardwareLayerUpdate(mHardwareLayer); 13445 13446 mLocalDirtyRect.setEmpty(); 13447 } 13448 13449 return mHardwareLayer; 13450 } 13451 13452 /** 13453 * Destroys this View's hardware layer if possible. 13454 * 13455 * @return True if the layer was destroyed, false otherwise. 13456 * 13457 * @see #setLayerType(int, android.graphics.Paint) 13458 * @see #LAYER_TYPE_HARDWARE 13459 */ 13460 boolean destroyLayer(boolean valid) { 13461 if (mHardwareLayer != null) { 13462 AttachInfo info = mAttachInfo; 13463 if (info != null && info.mHardwareRenderer != null && 13464 info.mHardwareRenderer.isEnabled() && 13465 (valid || info.mHardwareRenderer.validate())) { 13466 13467 info.mHardwareRenderer.cancelLayerUpdate(mHardwareLayer); 13468 mHardwareLayer.destroy(); 13469 mHardwareLayer = null; 13470 13471 invalidate(true); 13472 invalidateParentCaches(); 13473 } 13474 return true; 13475 } 13476 return false; 13477 } 13478 13479 /** 13480 * Destroys all hardware rendering resources. This method is invoked 13481 * when the system needs to reclaim resources. Upon execution of this 13482 * method, you should free any OpenGL resources created by the view. 13483 * 13484 * Note: you <strong>must</strong> call 13485 * <code>super.destroyHardwareResources()</code> when overriding 13486 * this method. 13487 * 13488 * @hide 13489 */ 13490 protected void destroyHardwareResources() { 13491 resetDisplayList(); 13492 destroyLayer(true); 13493 } 13494 13495 /** 13496 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13497 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13498 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13499 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13500 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13501 * null.</p> 13502 * 13503 * <p>Enabling the drawing cache is similar to 13504 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13505 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13506 * drawing cache has no effect on rendering because the system uses a different mechanism 13507 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13508 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13509 * for information on how to enable software and hardware layers.</p> 13510 * 13511 * <p>This API can be used to manually generate 13512 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13513 * {@link #getDrawingCache()}.</p> 13514 * 13515 * @param enabled true to enable the drawing cache, false otherwise 13516 * 13517 * @see #isDrawingCacheEnabled() 13518 * @see #getDrawingCache() 13519 * @see #buildDrawingCache() 13520 * @see #setLayerType(int, android.graphics.Paint) 13521 */ 13522 public void setDrawingCacheEnabled(boolean enabled) { 13523 mCachingFailed = false; 13524 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13525 } 13526 13527 /** 13528 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13529 * 13530 * @return true if the drawing cache is enabled 13531 * 13532 * @see #setDrawingCacheEnabled(boolean) 13533 * @see #getDrawingCache() 13534 */ 13535 @ViewDebug.ExportedProperty(category = "drawing") 13536 public boolean isDrawingCacheEnabled() { 13537 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13538 } 13539 13540 /** 13541 * Debugging utility which recursively outputs the dirty state of a view and its 13542 * descendants. 13543 * 13544 * @hide 13545 */ 13546 @SuppressWarnings({"UnusedDeclaration"}) 13547 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13548 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13549 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13550 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13551 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13552 if (clear) { 13553 mPrivateFlags &= clearMask; 13554 } 13555 if (this instanceof ViewGroup) { 13556 ViewGroup parent = (ViewGroup) this; 13557 final int count = parent.getChildCount(); 13558 for (int i = 0; i < count; i++) { 13559 final View child = parent.getChildAt(i); 13560 child.outputDirtyFlags(indent + " ", clear, clearMask); 13561 } 13562 } 13563 } 13564 13565 /** 13566 * This method is used by ViewGroup to cause its children to restore or recreate their 13567 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13568 * to recreate its own display list, which would happen if it went through the normal 13569 * draw/dispatchDraw mechanisms. 13570 * 13571 * @hide 13572 */ 13573 protected void dispatchGetDisplayList() {} 13574 13575 /** 13576 * A view that is not attached or hardware accelerated cannot create a display list. 13577 * This method checks these conditions and returns the appropriate result. 13578 * 13579 * @return true if view has the ability to create a display list, false otherwise. 13580 * 13581 * @hide 13582 */ 13583 public boolean canHaveDisplayList() { 13584 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13585 } 13586 13587 /** 13588 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13589 * Otherwise, the same display list will be returned (after having been rendered into 13590 * along the way, depending on the invalidation state of the view). 13591 * 13592 * @param displayList The previous version of this displayList, could be null. 13593 * @param isLayer Whether the requester of the display list is a layer. If so, 13594 * the view will avoid creating a layer inside the resulting display list. 13595 * @return A new or reused DisplayList object. 13596 */ 13597 private DisplayList getDisplayList(DisplayList displayList, boolean isLayer) { 13598 if (!canHaveDisplayList()) { 13599 return null; 13600 } 13601 13602 if (((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || 13603 displayList == null || !displayList.isValid() || 13604 (!isLayer && mRecreateDisplayList))) { 13605 // Don't need to recreate the display list, just need to tell our 13606 // children to restore/recreate theirs 13607 if (displayList != null && displayList.isValid() && 13608 !isLayer && !mRecreateDisplayList) { 13609 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13610 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13611 dispatchGetDisplayList(); 13612 13613 return displayList; 13614 } 13615 13616 if (!isLayer) { 13617 // If we got here, we're recreating it. Mark it as such to ensure that 13618 // we copy in child display lists into ours in drawChild() 13619 mRecreateDisplayList = true; 13620 } 13621 if (displayList == null) { 13622 displayList = DisplayList.create(getClass().getName()); 13623 // If we're creating a new display list, make sure our parent gets invalidated 13624 // since they will need to recreate their display list to account for this 13625 // new child display list. 13626 invalidateParentCaches(); 13627 } 13628 13629 boolean caching = false; 13630 int width = mRight - mLeft; 13631 int height = mBottom - mTop; 13632 int layerType = getLayerType(); 13633 13634 final HardwareCanvas canvas = displayList.start(width, height); 13635 13636 try { 13637 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13638 if (layerType == LAYER_TYPE_HARDWARE) { 13639 final HardwareLayer layer = getHardwareLayer(); 13640 if (layer != null && layer.isValid()) { 13641 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13642 } else { 13643 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13644 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13645 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13646 } 13647 caching = true; 13648 } else { 13649 buildDrawingCache(true); 13650 Bitmap cache = getDrawingCache(true); 13651 if (cache != null) { 13652 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13653 caching = true; 13654 } 13655 } 13656 } else { 13657 13658 computeScroll(); 13659 13660 canvas.translate(-mScrollX, -mScrollY); 13661 if (!isLayer) { 13662 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13663 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13664 } 13665 13666 // Fast path for layouts with no backgrounds 13667 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13668 dispatchDraw(canvas); 13669 if (mOverlay != null && !mOverlay.isEmpty()) { 13670 mOverlay.getOverlayView().draw(canvas); 13671 } 13672 } else { 13673 draw(canvas); 13674 } 13675 } 13676 } finally { 13677 displayList.end(); 13678 displayList.setCaching(caching); 13679 if (isLayer) { 13680 displayList.setLeftTopRightBottom(0, 0, width, height); 13681 } else { 13682 setDisplayListProperties(displayList); 13683 } 13684 } 13685 } else if (!isLayer) { 13686 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13687 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13688 } 13689 13690 return displayList; 13691 } 13692 13693 /** 13694 * Get the DisplayList for the HardwareLayer 13695 * 13696 * @param layer The HardwareLayer whose DisplayList we want 13697 * @return A DisplayList fopr the specified HardwareLayer 13698 */ 13699 private DisplayList getHardwareLayerDisplayList(HardwareLayer layer) { 13700 DisplayList displayList = getDisplayList(layer.getDisplayList(), true); 13701 layer.setDisplayList(displayList); 13702 return displayList; 13703 } 13704 13705 13706 /** 13707 * <p>Returns a display list that can be used to draw this view again 13708 * without executing its draw method.</p> 13709 * 13710 * @return A DisplayList ready to replay, or null if caching is not enabled. 13711 * 13712 * @hide 13713 */ 13714 public DisplayList getDisplayList() { 13715 mDisplayList = getDisplayList(mDisplayList, false); 13716 return mDisplayList; 13717 } 13718 13719 private void clearDisplayList() { 13720 if (mDisplayList != null) { 13721 mDisplayList.clear(); 13722 } 13723 13724 if (mBackgroundDisplayList != null) { 13725 mBackgroundDisplayList.clear(); 13726 } 13727 } 13728 13729 private void resetDisplayList() { 13730 if (mDisplayList != null) { 13731 mDisplayList.reset(); 13732 } 13733 13734 if (mBackgroundDisplayList != null) { 13735 mBackgroundDisplayList.reset(); 13736 } 13737 } 13738 13739 /** 13740 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13741 * 13742 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13743 * 13744 * @see #getDrawingCache(boolean) 13745 */ 13746 public Bitmap getDrawingCache() { 13747 return getDrawingCache(false); 13748 } 13749 13750 /** 13751 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13752 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13753 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13754 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13755 * request the drawing cache by calling this method and draw it on screen if the 13756 * returned bitmap is not null.</p> 13757 * 13758 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13759 * this method will create a bitmap of the same size as this view. Because this bitmap 13760 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13761 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13762 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13763 * size than the view. This implies that your application must be able to handle this 13764 * size.</p> 13765 * 13766 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13767 * the current density of the screen when the application is in compatibility 13768 * mode. 13769 * 13770 * @return A bitmap representing this view or null if cache is disabled. 13771 * 13772 * @see #setDrawingCacheEnabled(boolean) 13773 * @see #isDrawingCacheEnabled() 13774 * @see #buildDrawingCache(boolean) 13775 * @see #destroyDrawingCache() 13776 */ 13777 public Bitmap getDrawingCache(boolean autoScale) { 13778 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13779 return null; 13780 } 13781 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13782 buildDrawingCache(autoScale); 13783 } 13784 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13785 } 13786 13787 /** 13788 * <p>Frees the resources used by the drawing cache. If you call 13789 * {@link #buildDrawingCache()} manually without calling 13790 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13791 * should cleanup the cache with this method afterwards.</p> 13792 * 13793 * @see #setDrawingCacheEnabled(boolean) 13794 * @see #buildDrawingCache() 13795 * @see #getDrawingCache() 13796 */ 13797 public void destroyDrawingCache() { 13798 if (mDrawingCache != null) { 13799 mDrawingCache.recycle(); 13800 mDrawingCache = null; 13801 } 13802 if (mUnscaledDrawingCache != null) { 13803 mUnscaledDrawingCache.recycle(); 13804 mUnscaledDrawingCache = null; 13805 } 13806 } 13807 13808 /** 13809 * Setting a solid background color for the drawing cache's bitmaps will improve 13810 * performance and memory usage. Note, though that this should only be used if this 13811 * view will always be drawn on top of a solid color. 13812 * 13813 * @param color The background color to use for the drawing cache's bitmap 13814 * 13815 * @see #setDrawingCacheEnabled(boolean) 13816 * @see #buildDrawingCache() 13817 * @see #getDrawingCache() 13818 */ 13819 public void setDrawingCacheBackgroundColor(int color) { 13820 if (color != mDrawingCacheBackgroundColor) { 13821 mDrawingCacheBackgroundColor = color; 13822 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13823 } 13824 } 13825 13826 /** 13827 * @see #setDrawingCacheBackgroundColor(int) 13828 * 13829 * @return The background color to used for the drawing cache's bitmap 13830 */ 13831 public int getDrawingCacheBackgroundColor() { 13832 return mDrawingCacheBackgroundColor; 13833 } 13834 13835 /** 13836 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13837 * 13838 * @see #buildDrawingCache(boolean) 13839 */ 13840 public void buildDrawingCache() { 13841 buildDrawingCache(false); 13842 } 13843 13844 /** 13845 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13846 * 13847 * <p>If you call {@link #buildDrawingCache()} manually without calling 13848 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13849 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13850 * 13851 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13852 * this method will create a bitmap of the same size as this view. Because this bitmap 13853 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13854 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13855 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13856 * size than the view. This implies that your application must be able to handle this 13857 * size.</p> 13858 * 13859 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13860 * you do not need the drawing cache bitmap, calling this method will increase memory 13861 * usage and cause the view to be rendered in software once, thus negatively impacting 13862 * performance.</p> 13863 * 13864 * @see #getDrawingCache() 13865 * @see #destroyDrawingCache() 13866 */ 13867 public void buildDrawingCache(boolean autoScale) { 13868 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13869 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13870 mCachingFailed = false; 13871 13872 int width = mRight - mLeft; 13873 int height = mBottom - mTop; 13874 13875 final AttachInfo attachInfo = mAttachInfo; 13876 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13877 13878 if (autoScale && scalingRequired) { 13879 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13880 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13881 } 13882 13883 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13884 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13885 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13886 13887 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13888 final long drawingCacheSize = 13889 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13890 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13891 if (width > 0 && height > 0) { 13892 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13893 + projectedBitmapSize + " bytes, only " 13894 + drawingCacheSize + " available"); 13895 } 13896 destroyDrawingCache(); 13897 mCachingFailed = true; 13898 return; 13899 } 13900 13901 boolean clear = true; 13902 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13903 13904 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13905 Bitmap.Config quality; 13906 if (!opaque) { 13907 // Never pick ARGB_4444 because it looks awful 13908 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13909 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13910 case DRAWING_CACHE_QUALITY_AUTO: 13911 case DRAWING_CACHE_QUALITY_LOW: 13912 case DRAWING_CACHE_QUALITY_HIGH: 13913 default: 13914 quality = Bitmap.Config.ARGB_8888; 13915 break; 13916 } 13917 } else { 13918 // Optimization for translucent windows 13919 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13920 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13921 } 13922 13923 // Try to cleanup memory 13924 if (bitmap != null) bitmap.recycle(); 13925 13926 try { 13927 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13928 width, height, quality); 13929 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13930 if (autoScale) { 13931 mDrawingCache = bitmap; 13932 } else { 13933 mUnscaledDrawingCache = bitmap; 13934 } 13935 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13936 } catch (OutOfMemoryError e) { 13937 // If there is not enough memory to create the bitmap cache, just 13938 // ignore the issue as bitmap caches are not required to draw the 13939 // view hierarchy 13940 if (autoScale) { 13941 mDrawingCache = null; 13942 } else { 13943 mUnscaledDrawingCache = null; 13944 } 13945 mCachingFailed = true; 13946 return; 13947 } 13948 13949 clear = drawingCacheBackgroundColor != 0; 13950 } 13951 13952 Canvas canvas; 13953 if (attachInfo != null) { 13954 canvas = attachInfo.mCanvas; 13955 if (canvas == null) { 13956 canvas = new Canvas(); 13957 } 13958 canvas.setBitmap(bitmap); 13959 // Temporarily clobber the cached Canvas in case one of our children 13960 // is also using a drawing cache. Without this, the children would 13961 // steal the canvas by attaching their own bitmap to it and bad, bad 13962 // thing would happen (invisible views, corrupted drawings, etc.) 13963 attachInfo.mCanvas = null; 13964 } else { 13965 // This case should hopefully never or seldom happen 13966 canvas = new Canvas(bitmap); 13967 } 13968 13969 if (clear) { 13970 bitmap.eraseColor(drawingCacheBackgroundColor); 13971 } 13972 13973 computeScroll(); 13974 final int restoreCount = canvas.save(); 13975 13976 if (autoScale && scalingRequired) { 13977 final float scale = attachInfo.mApplicationScale; 13978 canvas.scale(scale, scale); 13979 } 13980 13981 canvas.translate(-mScrollX, -mScrollY); 13982 13983 mPrivateFlags |= PFLAG_DRAWN; 13984 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13985 mLayerType != LAYER_TYPE_NONE) { 13986 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13987 } 13988 13989 // Fast path for layouts with no backgrounds 13990 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13991 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13992 dispatchDraw(canvas); 13993 if (mOverlay != null && !mOverlay.isEmpty()) { 13994 mOverlay.getOverlayView().draw(canvas); 13995 } 13996 } else { 13997 draw(canvas); 13998 } 13999 14000 canvas.restoreToCount(restoreCount); 14001 canvas.setBitmap(null); 14002 14003 if (attachInfo != null) { 14004 // Restore the cached Canvas for our siblings 14005 attachInfo.mCanvas = canvas; 14006 } 14007 } 14008 } 14009 14010 /** 14011 * Create a snapshot of the view into a bitmap. We should probably make 14012 * some form of this public, but should think about the API. 14013 */ 14014 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14015 int width = mRight - mLeft; 14016 int height = mBottom - mTop; 14017 14018 final AttachInfo attachInfo = mAttachInfo; 14019 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14020 width = (int) ((width * scale) + 0.5f); 14021 height = (int) ((height * scale) + 0.5f); 14022 14023 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14024 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14025 if (bitmap == null) { 14026 throw new OutOfMemoryError(); 14027 } 14028 14029 Resources resources = getResources(); 14030 if (resources != null) { 14031 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14032 } 14033 14034 Canvas canvas; 14035 if (attachInfo != null) { 14036 canvas = attachInfo.mCanvas; 14037 if (canvas == null) { 14038 canvas = new Canvas(); 14039 } 14040 canvas.setBitmap(bitmap); 14041 // Temporarily clobber the cached Canvas in case one of our children 14042 // is also using a drawing cache. Without this, the children would 14043 // steal the canvas by attaching their own bitmap to it and bad, bad 14044 // things would happen (invisible views, corrupted drawings, etc.) 14045 attachInfo.mCanvas = null; 14046 } else { 14047 // This case should hopefully never or seldom happen 14048 canvas = new Canvas(bitmap); 14049 } 14050 14051 if ((backgroundColor & 0xff000000) != 0) { 14052 bitmap.eraseColor(backgroundColor); 14053 } 14054 14055 computeScroll(); 14056 final int restoreCount = canvas.save(); 14057 canvas.scale(scale, scale); 14058 canvas.translate(-mScrollX, -mScrollY); 14059 14060 // Temporarily remove the dirty mask 14061 int flags = mPrivateFlags; 14062 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14063 14064 // Fast path for layouts with no backgrounds 14065 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14066 dispatchDraw(canvas); 14067 if (mOverlay != null && !mOverlay.isEmpty()) { 14068 mOverlay.getOverlayView().draw(canvas); 14069 } 14070 } else { 14071 draw(canvas); 14072 } 14073 14074 mPrivateFlags = flags; 14075 14076 canvas.restoreToCount(restoreCount); 14077 canvas.setBitmap(null); 14078 14079 if (attachInfo != null) { 14080 // Restore the cached Canvas for our siblings 14081 attachInfo.mCanvas = canvas; 14082 } 14083 14084 return bitmap; 14085 } 14086 14087 /** 14088 * Indicates whether this View is currently in edit mode. A View is usually 14089 * in edit mode when displayed within a developer tool. For instance, if 14090 * this View is being drawn by a visual user interface builder, this method 14091 * should return true. 14092 * 14093 * Subclasses should check the return value of this method to provide 14094 * different behaviors if their normal behavior might interfere with the 14095 * host environment. For instance: the class spawns a thread in its 14096 * constructor, the drawing code relies on device-specific features, etc. 14097 * 14098 * This method is usually checked in the drawing code of custom widgets. 14099 * 14100 * @return True if this View is in edit mode, false otherwise. 14101 */ 14102 public boolean isInEditMode() { 14103 return false; 14104 } 14105 14106 /** 14107 * If the View draws content inside its padding and enables fading edges, 14108 * it needs to support padding offsets. Padding offsets are added to the 14109 * fading edges to extend the length of the fade so that it covers pixels 14110 * drawn inside the padding. 14111 * 14112 * Subclasses of this class should override this method if they need 14113 * to draw content inside the padding. 14114 * 14115 * @return True if padding offset must be applied, false otherwise. 14116 * 14117 * @see #getLeftPaddingOffset() 14118 * @see #getRightPaddingOffset() 14119 * @see #getTopPaddingOffset() 14120 * @see #getBottomPaddingOffset() 14121 * 14122 * @since CURRENT 14123 */ 14124 protected boolean isPaddingOffsetRequired() { 14125 return false; 14126 } 14127 14128 /** 14129 * Amount by which to extend the left fading region. Called only when 14130 * {@link #isPaddingOffsetRequired()} returns true. 14131 * 14132 * @return The left padding offset in pixels. 14133 * 14134 * @see #isPaddingOffsetRequired() 14135 * 14136 * @since CURRENT 14137 */ 14138 protected int getLeftPaddingOffset() { 14139 return 0; 14140 } 14141 14142 /** 14143 * Amount by which to extend the right fading region. Called only when 14144 * {@link #isPaddingOffsetRequired()} returns true. 14145 * 14146 * @return The right padding offset in pixels. 14147 * 14148 * @see #isPaddingOffsetRequired() 14149 * 14150 * @since CURRENT 14151 */ 14152 protected int getRightPaddingOffset() { 14153 return 0; 14154 } 14155 14156 /** 14157 * Amount by which to extend the top fading region. Called only when 14158 * {@link #isPaddingOffsetRequired()} returns true. 14159 * 14160 * @return The top padding offset in pixels. 14161 * 14162 * @see #isPaddingOffsetRequired() 14163 * 14164 * @since CURRENT 14165 */ 14166 protected int getTopPaddingOffset() { 14167 return 0; 14168 } 14169 14170 /** 14171 * Amount by which to extend the bottom fading region. Called only when 14172 * {@link #isPaddingOffsetRequired()} returns true. 14173 * 14174 * @return The bottom padding offset in pixels. 14175 * 14176 * @see #isPaddingOffsetRequired() 14177 * 14178 * @since CURRENT 14179 */ 14180 protected int getBottomPaddingOffset() { 14181 return 0; 14182 } 14183 14184 /** 14185 * @hide 14186 * @param offsetRequired 14187 */ 14188 protected int getFadeTop(boolean offsetRequired) { 14189 int top = mPaddingTop; 14190 if (offsetRequired) top += getTopPaddingOffset(); 14191 return top; 14192 } 14193 14194 /** 14195 * @hide 14196 * @param offsetRequired 14197 */ 14198 protected int getFadeHeight(boolean offsetRequired) { 14199 int padding = mPaddingTop; 14200 if (offsetRequired) padding += getTopPaddingOffset(); 14201 return mBottom - mTop - mPaddingBottom - padding; 14202 } 14203 14204 /** 14205 * <p>Indicates whether this view is attached to a hardware accelerated 14206 * window or not.</p> 14207 * 14208 * <p>Even if this method returns true, it does not mean that every call 14209 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14210 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14211 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14212 * window is hardware accelerated, 14213 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14214 * return false, and this method will return true.</p> 14215 * 14216 * @return True if the view is attached to a window and the window is 14217 * hardware accelerated; false in any other case. 14218 */ 14219 public boolean isHardwareAccelerated() { 14220 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14221 } 14222 14223 /** 14224 * Sets a rectangular area on this view to which the view will be clipped 14225 * when it is drawn. Setting the value to null will remove the clip bounds 14226 * and the view will draw normally, using its full bounds. 14227 * 14228 * @param clipBounds The rectangular area, in the local coordinates of 14229 * this view, to which future drawing operations will be clipped. 14230 */ 14231 public void setClipBounds(Rect clipBounds) { 14232 if (clipBounds != null) { 14233 if (clipBounds.equals(mClipBounds)) { 14234 return; 14235 } 14236 if (mClipBounds == null) { 14237 invalidate(); 14238 mClipBounds = new Rect(clipBounds); 14239 } else { 14240 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14241 Math.min(mClipBounds.top, clipBounds.top), 14242 Math.max(mClipBounds.right, clipBounds.right), 14243 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14244 mClipBounds.set(clipBounds); 14245 } 14246 } else { 14247 if (mClipBounds != null) { 14248 invalidate(); 14249 mClipBounds = null; 14250 } 14251 } 14252 } 14253 14254 /** 14255 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14256 * 14257 * @return A copy of the current clip bounds if clip bounds are set, 14258 * otherwise null. 14259 */ 14260 public Rect getClipBounds() { 14261 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14262 } 14263 14264 /** 14265 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14266 * case of an active Animation being run on the view. 14267 */ 14268 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14269 Animation a, boolean scalingRequired) { 14270 Transformation invalidationTransform; 14271 final int flags = parent.mGroupFlags; 14272 final boolean initialized = a.isInitialized(); 14273 if (!initialized) { 14274 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14275 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14276 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14277 onAnimationStart(); 14278 } 14279 14280 final Transformation t = parent.getChildTransformation(); 14281 boolean more = a.getTransformation(drawingTime, t, 1f); 14282 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14283 if (parent.mInvalidationTransformation == null) { 14284 parent.mInvalidationTransformation = new Transformation(); 14285 } 14286 invalidationTransform = parent.mInvalidationTransformation; 14287 a.getTransformation(drawingTime, invalidationTransform, 1f); 14288 } else { 14289 invalidationTransform = t; 14290 } 14291 14292 if (more) { 14293 if (!a.willChangeBounds()) { 14294 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14295 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14296 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14297 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14298 // The child need to draw an animation, potentially offscreen, so 14299 // make sure we do not cancel invalidate requests 14300 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14301 parent.invalidate(mLeft, mTop, mRight, mBottom); 14302 } 14303 } else { 14304 if (parent.mInvalidateRegion == null) { 14305 parent.mInvalidateRegion = new RectF(); 14306 } 14307 final RectF region = parent.mInvalidateRegion; 14308 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14309 invalidationTransform); 14310 14311 // The child need to draw an animation, potentially offscreen, so 14312 // make sure we do not cancel invalidate requests 14313 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14314 14315 final int left = mLeft + (int) region.left; 14316 final int top = mTop + (int) region.top; 14317 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14318 top + (int) (region.height() + .5f)); 14319 } 14320 } 14321 return more; 14322 } 14323 14324 /** 14325 * This method is called by getDisplayList() when a display list is created or re-rendered. 14326 * It sets or resets the current value of all properties on that display list (resetting is 14327 * necessary when a display list is being re-created, because we need to make sure that 14328 * previously-set transform values 14329 */ 14330 void setDisplayListProperties(DisplayList displayList) { 14331 if (displayList != null) { 14332 displayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 14333 displayList.setHasOverlappingRendering(hasOverlappingRendering()); 14334 if (mParent instanceof ViewGroup) { 14335 displayList.setClipToBounds( 14336 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14337 } 14338 if (this instanceof ViewGroup) { 14339 displayList.setIsolatedZVolume( 14340 (((ViewGroup) this).mGroupFlags & ViewGroup.FLAG_ISOLATED_Z_VOLUME) != 0); 14341 } 14342 displayList.setOutline(mOutline); 14343 float alpha = 1; 14344 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14345 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14346 ViewGroup parentVG = (ViewGroup) mParent; 14347 final Transformation t = parentVG.getChildTransformation(); 14348 if (parentVG.getChildStaticTransformation(this, t)) { 14349 final int transformType = t.getTransformationType(); 14350 if (transformType != Transformation.TYPE_IDENTITY) { 14351 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14352 alpha = t.getAlpha(); 14353 } 14354 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14355 displayList.setMatrix(t.getMatrix()); 14356 } 14357 } 14358 } 14359 } 14360 if (mTransformationInfo != null) { 14361 alpha *= getFinalAlpha(); 14362 if (alpha < 1) { 14363 final int multipliedAlpha = (int) (255 * alpha); 14364 if (onSetAlpha(multipliedAlpha)) { 14365 alpha = 1; 14366 } 14367 } 14368 displayList.setTransformationInfo(alpha, 14369 mTransformationInfo.mTranslationX, mTransformationInfo.mTranslationY, 14370 mTransformationInfo.mTranslationZ, 14371 mTransformationInfo.mRotation, mTransformationInfo.mRotationX, 14372 mTransformationInfo.mRotationY, mTransformationInfo.mScaleX, 14373 mTransformationInfo.mScaleY); 14374 if (mTransformationInfo.mCamera == null) { 14375 mTransformationInfo.mCamera = new Camera(); 14376 mTransformationInfo.matrix3D = new Matrix(); 14377 } 14378 displayList.setCameraDistance(mTransformationInfo.mCamera.getLocationZ()); 14379 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == PFLAG_PIVOT_EXPLICITLY_SET) { 14380 displayList.setPivotX(getPivotX()); 14381 displayList.setPivotY(getPivotY()); 14382 } 14383 } else if (alpha < 1) { 14384 displayList.setAlpha(alpha); 14385 } 14386 } 14387 } 14388 14389 /** 14390 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14391 * This draw() method is an implementation detail and is not intended to be overridden or 14392 * to be called from anywhere else other than ViewGroup.drawChild(). 14393 */ 14394 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14395 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14396 boolean more = false; 14397 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14398 final int flags = parent.mGroupFlags; 14399 14400 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14401 parent.getChildTransformation().clear(); 14402 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14403 } 14404 14405 Transformation transformToApply = null; 14406 boolean concatMatrix = false; 14407 14408 boolean scalingRequired = false; 14409 boolean caching; 14410 int layerType = getLayerType(); 14411 14412 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14413 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14414 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14415 caching = true; 14416 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14417 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14418 } else { 14419 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14420 } 14421 14422 final Animation a = getAnimation(); 14423 if (a != null) { 14424 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14425 concatMatrix = a.willChangeTransformationMatrix(); 14426 if (concatMatrix) { 14427 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14428 } 14429 transformToApply = parent.getChildTransformation(); 14430 } else { 14431 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == 14432 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && mDisplayList != null) { 14433 // No longer animating: clear out old animation matrix 14434 mDisplayList.setAnimationMatrix(null); 14435 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14436 } 14437 if (!useDisplayListProperties && 14438 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14439 final Transformation t = parent.getChildTransformation(); 14440 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14441 if (hasTransform) { 14442 final int transformType = t.getTransformationType(); 14443 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14444 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14445 } 14446 } 14447 } 14448 14449 concatMatrix |= !childHasIdentityMatrix; 14450 14451 // Sets the flag as early as possible to allow draw() implementations 14452 // to call invalidate() successfully when doing animations 14453 mPrivateFlags |= PFLAG_DRAWN; 14454 14455 if (!concatMatrix && 14456 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14457 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14458 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14459 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14460 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14461 return more; 14462 } 14463 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14464 14465 if (hardwareAccelerated) { 14466 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14467 // retain the flag's value temporarily in the mRecreateDisplayList flag 14468 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14469 mPrivateFlags &= ~PFLAG_INVALIDATED; 14470 } 14471 14472 DisplayList displayList = null; 14473 Bitmap cache = null; 14474 boolean hasDisplayList = false; 14475 if (caching) { 14476 if (!hardwareAccelerated) { 14477 if (layerType != LAYER_TYPE_NONE) { 14478 layerType = LAYER_TYPE_SOFTWARE; 14479 buildDrawingCache(true); 14480 } 14481 cache = getDrawingCache(true); 14482 } else { 14483 switch (layerType) { 14484 case LAYER_TYPE_SOFTWARE: 14485 if (useDisplayListProperties) { 14486 hasDisplayList = canHaveDisplayList(); 14487 } else { 14488 buildDrawingCache(true); 14489 cache = getDrawingCache(true); 14490 } 14491 break; 14492 case LAYER_TYPE_HARDWARE: 14493 if (useDisplayListProperties) { 14494 hasDisplayList = canHaveDisplayList(); 14495 } 14496 break; 14497 case LAYER_TYPE_NONE: 14498 // Delay getting the display list until animation-driven alpha values are 14499 // set up and possibly passed on to the view 14500 hasDisplayList = canHaveDisplayList(); 14501 break; 14502 } 14503 } 14504 } 14505 useDisplayListProperties &= hasDisplayList; 14506 if (useDisplayListProperties) { 14507 displayList = getDisplayList(); 14508 if (!displayList.isValid()) { 14509 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14510 // to getDisplayList(), the display list will be marked invalid and we should not 14511 // try to use it again. 14512 displayList = null; 14513 hasDisplayList = false; 14514 useDisplayListProperties = false; 14515 } 14516 } 14517 14518 int sx = 0; 14519 int sy = 0; 14520 if (!hasDisplayList) { 14521 computeScroll(); 14522 sx = mScrollX; 14523 sy = mScrollY; 14524 } 14525 14526 final boolean hasNoCache = cache == null || hasDisplayList; 14527 final boolean offsetForScroll = cache == null && !hasDisplayList && 14528 layerType != LAYER_TYPE_HARDWARE; 14529 14530 int restoreTo = -1; 14531 if (!useDisplayListProperties || transformToApply != null) { 14532 restoreTo = canvas.save(); 14533 } 14534 if (offsetForScroll) { 14535 canvas.translate(mLeft - sx, mTop - sy); 14536 } else { 14537 if (!useDisplayListProperties) { 14538 canvas.translate(mLeft, mTop); 14539 } 14540 if (scalingRequired) { 14541 if (useDisplayListProperties) { 14542 // TODO: Might not need this if we put everything inside the DL 14543 restoreTo = canvas.save(); 14544 } 14545 // mAttachInfo cannot be null, otherwise scalingRequired == false 14546 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14547 canvas.scale(scale, scale); 14548 } 14549 } 14550 14551 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14552 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14553 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14554 if (transformToApply != null || !childHasIdentityMatrix) { 14555 int transX = 0; 14556 int transY = 0; 14557 14558 if (offsetForScroll) { 14559 transX = -sx; 14560 transY = -sy; 14561 } 14562 14563 if (transformToApply != null) { 14564 if (concatMatrix) { 14565 if (useDisplayListProperties) { 14566 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14567 } else { 14568 // Undo the scroll translation, apply the transformation matrix, 14569 // then redo the scroll translate to get the correct result. 14570 canvas.translate(-transX, -transY); 14571 canvas.concat(transformToApply.getMatrix()); 14572 canvas.translate(transX, transY); 14573 } 14574 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14575 } 14576 14577 float transformAlpha = transformToApply.getAlpha(); 14578 if (transformAlpha < 1) { 14579 alpha *= transformAlpha; 14580 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14581 } 14582 } 14583 14584 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14585 canvas.translate(-transX, -transY); 14586 canvas.concat(getMatrix()); 14587 canvas.translate(transX, transY); 14588 } 14589 } 14590 14591 // Deal with alpha if it is or used to be <1 14592 if (alpha < 1 || 14593 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14594 if (alpha < 1) { 14595 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14596 } else { 14597 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14598 } 14599 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14600 if (hasNoCache) { 14601 final int multipliedAlpha = (int) (255 * alpha); 14602 if (!onSetAlpha(multipliedAlpha)) { 14603 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14604 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14605 layerType != LAYER_TYPE_NONE) { 14606 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14607 } 14608 if (useDisplayListProperties) { 14609 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14610 } else if (layerType == LAYER_TYPE_NONE) { 14611 final int scrollX = hasDisplayList ? 0 : sx; 14612 final int scrollY = hasDisplayList ? 0 : sy; 14613 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14614 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14615 } 14616 } else { 14617 // Alpha is handled by the child directly, clobber the layer's alpha 14618 mPrivateFlags |= PFLAG_ALPHA_SET; 14619 } 14620 } 14621 } 14622 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14623 onSetAlpha(255); 14624 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14625 } 14626 14627 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14628 !useDisplayListProperties && cache == null) { 14629 if (offsetForScroll) { 14630 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14631 } else { 14632 if (!scalingRequired || cache == null) { 14633 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14634 } else { 14635 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14636 } 14637 } 14638 } 14639 14640 if (!useDisplayListProperties && hasDisplayList) { 14641 displayList = getDisplayList(); 14642 if (!displayList.isValid()) { 14643 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14644 // to getDisplayList(), the display list will be marked invalid and we should not 14645 // try to use it again. 14646 displayList = null; 14647 hasDisplayList = false; 14648 } 14649 } 14650 14651 if (hasNoCache) { 14652 boolean layerRendered = false; 14653 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14654 final HardwareLayer layer = getHardwareLayer(); 14655 if (layer != null && layer.isValid()) { 14656 mLayerPaint.setAlpha((int) (alpha * 255)); 14657 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14658 layerRendered = true; 14659 } else { 14660 final int scrollX = hasDisplayList ? 0 : sx; 14661 final int scrollY = hasDisplayList ? 0 : sy; 14662 canvas.saveLayer(scrollX, scrollY, 14663 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14664 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14665 } 14666 } 14667 14668 if (!layerRendered) { 14669 if (!hasDisplayList) { 14670 // Fast path for layouts with no backgrounds 14671 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14672 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14673 dispatchDraw(canvas); 14674 } else { 14675 draw(canvas); 14676 } 14677 } else { 14678 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14679 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14680 } 14681 } 14682 } else if (cache != null) { 14683 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14684 Paint cachePaint; 14685 14686 if (layerType == LAYER_TYPE_NONE) { 14687 cachePaint = parent.mCachePaint; 14688 if (cachePaint == null) { 14689 cachePaint = new Paint(); 14690 cachePaint.setDither(false); 14691 parent.mCachePaint = cachePaint; 14692 } 14693 if (alpha < 1) { 14694 cachePaint.setAlpha((int) (alpha * 255)); 14695 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14696 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14697 cachePaint.setAlpha(255); 14698 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14699 } 14700 } else { 14701 cachePaint = mLayerPaint; 14702 cachePaint.setAlpha((int) (alpha * 255)); 14703 } 14704 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14705 } 14706 14707 if (restoreTo >= 0) { 14708 canvas.restoreToCount(restoreTo); 14709 } 14710 14711 if (a != null && !more) { 14712 if (!hardwareAccelerated && !a.getFillAfter()) { 14713 onSetAlpha(255); 14714 } 14715 parent.finishAnimatingView(this, a); 14716 } 14717 14718 if (more && hardwareAccelerated) { 14719 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14720 // alpha animations should cause the child to recreate its display list 14721 invalidate(true); 14722 } 14723 } 14724 14725 mRecreateDisplayList = false; 14726 14727 return more; 14728 } 14729 14730 /** 14731 * Manually render this view (and all of its children) to the given Canvas. 14732 * The view must have already done a full layout before this function is 14733 * called. When implementing a view, implement 14734 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14735 * If you do need to override this method, call the superclass version. 14736 * 14737 * @param canvas The Canvas to which the View is rendered. 14738 */ 14739 public void draw(Canvas canvas) { 14740 if (mClipBounds != null) { 14741 canvas.clipRect(mClipBounds); 14742 } 14743 final int privateFlags = mPrivateFlags; 14744 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14745 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14746 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14747 14748 /* 14749 * Draw traversal performs several drawing steps which must be executed 14750 * in the appropriate order: 14751 * 14752 * 1. Draw the background 14753 * 2. If necessary, save the canvas' layers to prepare for fading 14754 * 3. Draw view's content 14755 * 4. Draw children 14756 * 5. If necessary, draw the fading edges and restore layers 14757 * 6. Draw decorations (scrollbars for instance) 14758 */ 14759 14760 // Step 1, draw the background, if needed 14761 int saveCount; 14762 14763 if (!dirtyOpaque) { 14764 drawBackground(canvas); 14765 } 14766 14767 // skip step 2 & 5 if possible (common case) 14768 final int viewFlags = mViewFlags; 14769 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14770 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14771 if (!verticalEdges && !horizontalEdges) { 14772 // Step 3, draw the content 14773 if (!dirtyOpaque) onDraw(canvas); 14774 14775 // Step 4, draw the children 14776 dispatchDraw(canvas); 14777 14778 // Step 6, draw decorations (scrollbars) 14779 onDrawScrollBars(canvas); 14780 14781 if (mOverlay != null && !mOverlay.isEmpty()) { 14782 mOverlay.getOverlayView().dispatchDraw(canvas); 14783 } 14784 14785 // we're done... 14786 return; 14787 } 14788 14789 /* 14790 * Here we do the full fledged routine... 14791 * (this is an uncommon case where speed matters less, 14792 * this is why we repeat some of the tests that have been 14793 * done above) 14794 */ 14795 14796 boolean drawTop = false; 14797 boolean drawBottom = false; 14798 boolean drawLeft = false; 14799 boolean drawRight = false; 14800 14801 float topFadeStrength = 0.0f; 14802 float bottomFadeStrength = 0.0f; 14803 float leftFadeStrength = 0.0f; 14804 float rightFadeStrength = 0.0f; 14805 14806 // Step 2, save the canvas' layers 14807 int paddingLeft = mPaddingLeft; 14808 14809 final boolean offsetRequired = isPaddingOffsetRequired(); 14810 if (offsetRequired) { 14811 paddingLeft += getLeftPaddingOffset(); 14812 } 14813 14814 int left = mScrollX + paddingLeft; 14815 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14816 int top = mScrollY + getFadeTop(offsetRequired); 14817 int bottom = top + getFadeHeight(offsetRequired); 14818 14819 if (offsetRequired) { 14820 right += getRightPaddingOffset(); 14821 bottom += getBottomPaddingOffset(); 14822 } 14823 14824 final ScrollabilityCache scrollabilityCache = mScrollCache; 14825 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14826 int length = (int) fadeHeight; 14827 14828 // clip the fade length if top and bottom fades overlap 14829 // overlapping fades produce odd-looking artifacts 14830 if (verticalEdges && (top + length > bottom - length)) { 14831 length = (bottom - top) / 2; 14832 } 14833 14834 // also clip horizontal fades if necessary 14835 if (horizontalEdges && (left + length > right - length)) { 14836 length = (right - left) / 2; 14837 } 14838 14839 if (verticalEdges) { 14840 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14841 drawTop = topFadeStrength * fadeHeight > 1.0f; 14842 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14843 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14844 } 14845 14846 if (horizontalEdges) { 14847 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14848 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14849 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14850 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14851 } 14852 14853 saveCount = canvas.getSaveCount(); 14854 14855 int solidColor = getSolidColor(); 14856 if (solidColor == 0) { 14857 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14858 14859 if (drawTop) { 14860 canvas.saveLayer(left, top, right, top + length, null, flags); 14861 } 14862 14863 if (drawBottom) { 14864 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14865 } 14866 14867 if (drawLeft) { 14868 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14869 } 14870 14871 if (drawRight) { 14872 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14873 } 14874 } else { 14875 scrollabilityCache.setFadeColor(solidColor); 14876 } 14877 14878 // Step 3, draw the content 14879 if (!dirtyOpaque) onDraw(canvas); 14880 14881 // Step 4, draw the children 14882 dispatchDraw(canvas); 14883 14884 // Step 5, draw the fade effect and restore layers 14885 final Paint p = scrollabilityCache.paint; 14886 final Matrix matrix = scrollabilityCache.matrix; 14887 final Shader fade = scrollabilityCache.shader; 14888 14889 if (drawTop) { 14890 matrix.setScale(1, fadeHeight * topFadeStrength); 14891 matrix.postTranslate(left, top); 14892 fade.setLocalMatrix(matrix); 14893 canvas.drawRect(left, top, right, top + length, p); 14894 } 14895 14896 if (drawBottom) { 14897 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14898 matrix.postRotate(180); 14899 matrix.postTranslate(left, bottom); 14900 fade.setLocalMatrix(matrix); 14901 canvas.drawRect(left, bottom - length, right, bottom, p); 14902 } 14903 14904 if (drawLeft) { 14905 matrix.setScale(1, fadeHeight * leftFadeStrength); 14906 matrix.postRotate(-90); 14907 matrix.postTranslate(left, top); 14908 fade.setLocalMatrix(matrix); 14909 canvas.drawRect(left, top, left + length, bottom, p); 14910 } 14911 14912 if (drawRight) { 14913 matrix.setScale(1, fadeHeight * rightFadeStrength); 14914 matrix.postRotate(90); 14915 matrix.postTranslate(right, top); 14916 fade.setLocalMatrix(matrix); 14917 canvas.drawRect(right - length, top, right, bottom, p); 14918 } 14919 14920 canvas.restoreToCount(saveCount); 14921 14922 // Step 6, draw decorations (scrollbars) 14923 onDrawScrollBars(canvas); 14924 14925 if (mOverlay != null && !mOverlay.isEmpty()) { 14926 mOverlay.getOverlayView().dispatchDraw(canvas); 14927 } 14928 } 14929 14930 /** 14931 * Draws the background onto the specified canvas. 14932 * 14933 * @param canvas Canvas on which to draw the background 14934 */ 14935 private void drawBackground(Canvas canvas) { 14936 final Drawable background = mBackground; 14937 if (background == null) { 14938 return; 14939 } 14940 14941 if (mBackgroundSizeChanged) { 14942 // We should see the background invalidate itself, but just to be 14943 // careful we're going to clear the display list and force redraw. 14944 if (mBackgroundDisplayList != null) { 14945 mBackgroundDisplayList.clear(); 14946 } 14947 14948 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14949 mBackgroundSizeChanged = false; 14950 } 14951 14952 14953 // Attempt to use a display list if requested. 14954 if (canvas != null && canvas.isHardwareAccelerated()) { 14955 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 14956 14957 final DisplayList displayList = mBackgroundDisplayList; 14958 if (displayList != null && displayList.isValid()) { 14959 setBackgroundDisplayListProperties(displayList); 14960 ((HardwareCanvas) canvas).drawDisplayList(displayList); 14961 return; 14962 } 14963 } 14964 14965 final int scrollX = mScrollX; 14966 final int scrollY = mScrollY; 14967 if ((scrollX | scrollY) == 0) { 14968 background.draw(canvas); 14969 } else { 14970 canvas.translate(scrollX, scrollY); 14971 background.draw(canvas); 14972 canvas.translate(-scrollX, -scrollY); 14973 } 14974 } 14975 14976 /** 14977 * Set up background drawable display list properties. 14978 * 14979 * @param displayList Valid display list for the background drawable 14980 */ 14981 private void setBackgroundDisplayListProperties(DisplayList displayList) { 14982 displayList.setProjectBackwards((mPrivateFlags3 & PFLAG3_PROJECT_BACKGROUND) != 0); 14983 displayList.setTranslationX(mScrollX); 14984 displayList.setTranslationY(mScrollY); 14985 } 14986 14987 /** 14988 * Creates a new display list or updates the existing display list for the 14989 * specified Drawable. 14990 * 14991 * @param drawable Drawable for which to create a display list 14992 * @param displayList Existing display list, or {@code null} 14993 * @return A valid display list for the specified drawable 14994 */ 14995 private static DisplayList getDrawableDisplayList(Drawable drawable, DisplayList displayList) { 14996 if (displayList != null && displayList.isValid()) { 14997 return displayList; 14998 } 14999 15000 if (displayList == null) { 15001 displayList = DisplayList.create(drawable.getClass().getName()); 15002 } 15003 15004 final Rect bounds = drawable.getBounds(); 15005 final int width = bounds.width(); 15006 final int height = bounds.height(); 15007 final HardwareCanvas canvas = displayList.start(width, height); 15008 drawable.draw(canvas); 15009 displayList.end(); 15010 15011 // Set up drawable properties that are view-independent. 15012 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15013 displayList.setClipToBounds(false); 15014 return displayList; 15015 } 15016 15017 /** 15018 * Returns the overlay for this view, creating it if it does not yet exist. 15019 * Adding drawables to the overlay will cause them to be displayed whenever 15020 * the view itself is redrawn. Objects in the overlay should be actively 15021 * managed: remove them when they should not be displayed anymore. The 15022 * overlay will always have the same size as its host view. 15023 * 15024 * <p>Note: Overlays do not currently work correctly with {@link 15025 * SurfaceView} or {@link TextureView}; contents in overlays for these 15026 * types of views may not display correctly.</p> 15027 * 15028 * @return The ViewOverlay object for this view. 15029 * @see ViewOverlay 15030 */ 15031 public ViewOverlay getOverlay() { 15032 if (mOverlay == null) { 15033 mOverlay = new ViewOverlay(mContext, this); 15034 } 15035 return mOverlay; 15036 } 15037 15038 /** 15039 * Override this if your view is known to always be drawn on top of a solid color background, 15040 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15041 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15042 * should be set to 0xFF. 15043 * 15044 * @see #setVerticalFadingEdgeEnabled(boolean) 15045 * @see #setHorizontalFadingEdgeEnabled(boolean) 15046 * 15047 * @return The known solid color background for this view, or 0 if the color may vary 15048 */ 15049 @ViewDebug.ExportedProperty(category = "drawing") 15050 public int getSolidColor() { 15051 return 0; 15052 } 15053 15054 /** 15055 * Build a human readable string representation of the specified view flags. 15056 * 15057 * @param flags the view flags to convert to a string 15058 * @return a String representing the supplied flags 15059 */ 15060 private static String printFlags(int flags) { 15061 String output = ""; 15062 int numFlags = 0; 15063 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15064 output += "TAKES_FOCUS"; 15065 numFlags++; 15066 } 15067 15068 switch (flags & VISIBILITY_MASK) { 15069 case INVISIBLE: 15070 if (numFlags > 0) { 15071 output += " "; 15072 } 15073 output += "INVISIBLE"; 15074 // USELESS HERE numFlags++; 15075 break; 15076 case GONE: 15077 if (numFlags > 0) { 15078 output += " "; 15079 } 15080 output += "GONE"; 15081 // USELESS HERE numFlags++; 15082 break; 15083 default: 15084 break; 15085 } 15086 return output; 15087 } 15088 15089 /** 15090 * Build a human readable string representation of the specified private 15091 * view flags. 15092 * 15093 * @param privateFlags the private view flags to convert to a string 15094 * @return a String representing the supplied flags 15095 */ 15096 private static String printPrivateFlags(int privateFlags) { 15097 String output = ""; 15098 int numFlags = 0; 15099 15100 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15101 output += "WANTS_FOCUS"; 15102 numFlags++; 15103 } 15104 15105 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15106 if (numFlags > 0) { 15107 output += " "; 15108 } 15109 output += "FOCUSED"; 15110 numFlags++; 15111 } 15112 15113 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15114 if (numFlags > 0) { 15115 output += " "; 15116 } 15117 output += "SELECTED"; 15118 numFlags++; 15119 } 15120 15121 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15122 if (numFlags > 0) { 15123 output += " "; 15124 } 15125 output += "IS_ROOT_NAMESPACE"; 15126 numFlags++; 15127 } 15128 15129 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15130 if (numFlags > 0) { 15131 output += " "; 15132 } 15133 output += "HAS_BOUNDS"; 15134 numFlags++; 15135 } 15136 15137 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15138 if (numFlags > 0) { 15139 output += " "; 15140 } 15141 output += "DRAWN"; 15142 // USELESS HERE numFlags++; 15143 } 15144 return output; 15145 } 15146 15147 /** 15148 * <p>Indicates whether or not this view's layout will be requested during 15149 * the next hierarchy layout pass.</p> 15150 * 15151 * @return true if the layout will be forced during next layout pass 15152 */ 15153 public boolean isLayoutRequested() { 15154 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15155 } 15156 15157 /** 15158 * Return true if o is a ViewGroup that is laying out using optical bounds. 15159 * @hide 15160 */ 15161 public static boolean isLayoutModeOptical(Object o) { 15162 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15163 } 15164 15165 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15166 Insets parentInsets = mParent instanceof View ? 15167 ((View) mParent).getOpticalInsets() : Insets.NONE; 15168 Insets childInsets = getOpticalInsets(); 15169 return setFrame( 15170 left + parentInsets.left - childInsets.left, 15171 top + parentInsets.top - childInsets.top, 15172 right + parentInsets.left + childInsets.right, 15173 bottom + parentInsets.top + childInsets.bottom); 15174 } 15175 15176 /** 15177 * Assign a size and position to a view and all of its 15178 * descendants 15179 * 15180 * <p>This is the second phase of the layout mechanism. 15181 * (The first is measuring). In this phase, each parent calls 15182 * layout on all of its children to position them. 15183 * This is typically done using the child measurements 15184 * that were stored in the measure pass().</p> 15185 * 15186 * <p>Derived classes should not override this method. 15187 * Derived classes with children should override 15188 * onLayout. In that method, they should 15189 * call layout on each of their children.</p> 15190 * 15191 * @param l Left position, relative to parent 15192 * @param t Top position, relative to parent 15193 * @param r Right position, relative to parent 15194 * @param b Bottom position, relative to parent 15195 */ 15196 @SuppressWarnings({"unchecked"}) 15197 public void layout(int l, int t, int r, int b) { 15198 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15199 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15200 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15201 } 15202 15203 int oldL = mLeft; 15204 int oldT = mTop; 15205 int oldB = mBottom; 15206 int oldR = mRight; 15207 15208 boolean changed = isLayoutModeOptical(mParent) ? 15209 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15210 15211 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15212 onLayout(changed, l, t, r, b); 15213 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15214 15215 ListenerInfo li = mListenerInfo; 15216 if (li != null && li.mOnLayoutChangeListeners != null) { 15217 ArrayList<OnLayoutChangeListener> listenersCopy = 15218 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15219 int numListeners = listenersCopy.size(); 15220 for (int i = 0; i < numListeners; ++i) { 15221 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15222 } 15223 } 15224 } 15225 15226 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15227 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15228 } 15229 15230 /** 15231 * Called from layout when this view should 15232 * assign a size and position to each of its children. 15233 * 15234 * Derived classes with children should override 15235 * this method and call layout on each of 15236 * their children. 15237 * @param changed This is a new size or position for this view 15238 * @param left Left position, relative to parent 15239 * @param top Top position, relative to parent 15240 * @param right Right position, relative to parent 15241 * @param bottom Bottom position, relative to parent 15242 */ 15243 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15244 } 15245 15246 /** 15247 * Assign a size and position to this view. 15248 * 15249 * This is called from layout. 15250 * 15251 * @param left Left position, relative to parent 15252 * @param top Top position, relative to parent 15253 * @param right Right position, relative to parent 15254 * @param bottom Bottom position, relative to parent 15255 * @return true if the new size and position are different than the 15256 * previous ones 15257 * {@hide} 15258 */ 15259 protected boolean setFrame(int left, int top, int right, int bottom) { 15260 boolean changed = false; 15261 15262 if (DBG) { 15263 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15264 + right + "," + bottom + ")"); 15265 } 15266 15267 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15268 changed = true; 15269 15270 // Remember our drawn bit 15271 int drawn = mPrivateFlags & PFLAG_DRAWN; 15272 15273 int oldWidth = mRight - mLeft; 15274 int oldHeight = mBottom - mTop; 15275 int newWidth = right - left; 15276 int newHeight = bottom - top; 15277 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15278 15279 // Invalidate our old position 15280 invalidate(sizeChanged); 15281 15282 mLeft = left; 15283 mTop = top; 15284 mRight = right; 15285 mBottom = bottom; 15286 if (mDisplayList != null) { 15287 mDisplayList.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15288 } 15289 15290 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15291 15292 15293 if (sizeChanged) { 15294 if ((mPrivateFlags & PFLAG_PIVOT_EXPLICITLY_SET) == 0) { 15295 // A change in dimension means an auto-centered pivot point changes, too 15296 if (mTransformationInfo != null) { 15297 mTransformationInfo.mMatrixDirty = true; 15298 } 15299 } 15300 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15301 } 15302 15303 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15304 // If we are visible, force the DRAWN bit to on so that 15305 // this invalidate will go through (at least to our parent). 15306 // This is because someone may have invalidated this view 15307 // before this call to setFrame came in, thereby clearing 15308 // the DRAWN bit. 15309 mPrivateFlags |= PFLAG_DRAWN; 15310 invalidate(sizeChanged); 15311 // parent display list may need to be recreated based on a change in the bounds 15312 // of any child 15313 invalidateParentCaches(); 15314 } 15315 15316 // Reset drawn bit to original value (invalidate turns it off) 15317 mPrivateFlags |= drawn; 15318 15319 mBackgroundSizeChanged = true; 15320 15321 notifySubtreeAccessibilityStateChangedIfNeeded(); 15322 } 15323 return changed; 15324 } 15325 15326 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15327 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15328 if (mOverlay != null) { 15329 mOverlay.getOverlayView().setRight(newWidth); 15330 mOverlay.getOverlayView().setBottom(newHeight); 15331 } 15332 } 15333 15334 /** 15335 * Finalize inflating a view from XML. This is called as the last phase 15336 * of inflation, after all child views have been added. 15337 * 15338 * <p>Even if the subclass overrides onFinishInflate, they should always be 15339 * sure to call the super method, so that we get called. 15340 */ 15341 protected void onFinishInflate() { 15342 } 15343 15344 /** 15345 * Returns the resources associated with this view. 15346 * 15347 * @return Resources object. 15348 */ 15349 public Resources getResources() { 15350 return mResources; 15351 } 15352 15353 /** 15354 * Invalidates the specified Drawable. 15355 * 15356 * @param drawable the drawable to invalidate 15357 */ 15358 @Override 15359 public void invalidateDrawable(Drawable drawable) { 15360 if (verifyDrawable(drawable)) { 15361 if (drawable == mBackground && mBackgroundDisplayList != null) { 15362 // We'll need to redraw the display list. 15363 mBackgroundDisplayList.clear(); 15364 } 15365 15366 final Rect dirty = drawable.getBounds(); 15367 final int scrollX = mScrollX; 15368 final int scrollY = mScrollY; 15369 15370 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15371 dirty.right + scrollX, dirty.bottom + scrollY); 15372 } 15373 } 15374 15375 /** 15376 * Schedules an action on a drawable to occur at a specified time. 15377 * 15378 * @param who the recipient of the action 15379 * @param what the action to run on the drawable 15380 * @param when the time at which the action must occur. Uses the 15381 * {@link SystemClock#uptimeMillis} timebase. 15382 */ 15383 @Override 15384 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15385 if (verifyDrawable(who) && what != null) { 15386 final long delay = when - SystemClock.uptimeMillis(); 15387 if (mAttachInfo != null) { 15388 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15389 Choreographer.CALLBACK_ANIMATION, what, who, 15390 Choreographer.subtractFrameDelay(delay)); 15391 } else { 15392 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15393 } 15394 } 15395 } 15396 15397 /** 15398 * Cancels a scheduled action on a drawable. 15399 * 15400 * @param who the recipient of the action 15401 * @param what the action to cancel 15402 */ 15403 @Override 15404 public void unscheduleDrawable(Drawable who, Runnable what) { 15405 if (verifyDrawable(who) && what != null) { 15406 if (mAttachInfo != null) { 15407 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15408 Choreographer.CALLBACK_ANIMATION, what, who); 15409 } 15410 ViewRootImpl.getRunQueue().removeCallbacks(what); 15411 } 15412 } 15413 15414 /** 15415 * Unschedule any events associated with the given Drawable. This can be 15416 * used when selecting a new Drawable into a view, so that the previous 15417 * one is completely unscheduled. 15418 * 15419 * @param who The Drawable to unschedule. 15420 * 15421 * @see #drawableStateChanged 15422 */ 15423 public void unscheduleDrawable(Drawable who) { 15424 if (mAttachInfo != null && who != null) { 15425 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15426 Choreographer.CALLBACK_ANIMATION, null, who); 15427 } 15428 } 15429 15430 /** 15431 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15432 * that the View directionality can and will be resolved before its Drawables. 15433 * 15434 * Will call {@link View#onResolveDrawables} when resolution is done. 15435 * 15436 * @hide 15437 */ 15438 protected void resolveDrawables() { 15439 // Drawables resolution may need to happen before resolving the layout direction (which is 15440 // done only during the measure() call). 15441 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15442 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15443 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15444 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15445 // direction to be resolved as its resolved value will be the same as its raw value. 15446 if (!isLayoutDirectionResolved() && 15447 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15448 return; 15449 } 15450 15451 final int layoutDirection = isLayoutDirectionResolved() ? 15452 getLayoutDirection() : getRawLayoutDirection(); 15453 15454 if (mBackground != null) { 15455 mBackground.setLayoutDirection(layoutDirection); 15456 } 15457 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15458 onResolveDrawables(layoutDirection); 15459 } 15460 15461 /** 15462 * Called when layout direction has been resolved. 15463 * 15464 * The default implementation does nothing. 15465 * 15466 * @param layoutDirection The resolved layout direction. 15467 * 15468 * @see #LAYOUT_DIRECTION_LTR 15469 * @see #LAYOUT_DIRECTION_RTL 15470 * 15471 * @hide 15472 */ 15473 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15474 } 15475 15476 /** 15477 * @hide 15478 */ 15479 protected void resetResolvedDrawables() { 15480 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15481 } 15482 15483 private boolean isDrawablesResolved() { 15484 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15485 } 15486 15487 /** 15488 * If your view subclass is displaying its own Drawable objects, it should 15489 * override this function and return true for any Drawable it is 15490 * displaying. This allows animations for those drawables to be 15491 * scheduled. 15492 * 15493 * <p>Be sure to call through to the super class when overriding this 15494 * function. 15495 * 15496 * @param who The Drawable to verify. Return true if it is one you are 15497 * displaying, else return the result of calling through to the 15498 * super class. 15499 * 15500 * @return boolean If true than the Drawable is being displayed in the 15501 * view; else false and it is not allowed to animate. 15502 * 15503 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15504 * @see #drawableStateChanged() 15505 */ 15506 protected boolean verifyDrawable(Drawable who) { 15507 return who == mBackground; 15508 } 15509 15510 /** 15511 * This function is called whenever the state of the view changes in such 15512 * a way that it impacts the state of drawables being shown. 15513 * 15514 * <p>Be sure to call through to the superclass when overriding this 15515 * function. 15516 * 15517 * @see Drawable#setState(int[]) 15518 */ 15519 protected void drawableStateChanged() { 15520 final Drawable d = mBackground; 15521 if (d != null && d.isStateful()) { 15522 d.setState(getDrawableState()); 15523 } 15524 } 15525 15526 /** 15527 * Call this to force a view to update its drawable state. This will cause 15528 * drawableStateChanged to be called on this view. Views that are interested 15529 * in the new state should call getDrawableState. 15530 * 15531 * @see #drawableStateChanged 15532 * @see #getDrawableState 15533 */ 15534 public void refreshDrawableState() { 15535 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15536 drawableStateChanged(); 15537 15538 ViewParent parent = mParent; 15539 if (parent != null) { 15540 parent.childDrawableStateChanged(this); 15541 } 15542 } 15543 15544 /** 15545 * Return an array of resource IDs of the drawable states representing the 15546 * current state of the view. 15547 * 15548 * @return The current drawable state 15549 * 15550 * @see Drawable#setState(int[]) 15551 * @see #drawableStateChanged() 15552 * @see #onCreateDrawableState(int) 15553 */ 15554 public final int[] getDrawableState() { 15555 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15556 return mDrawableState; 15557 } else { 15558 mDrawableState = onCreateDrawableState(0); 15559 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15560 return mDrawableState; 15561 } 15562 } 15563 15564 /** 15565 * Generate the new {@link android.graphics.drawable.Drawable} state for 15566 * this view. This is called by the view 15567 * system when the cached Drawable state is determined to be invalid. To 15568 * retrieve the current state, you should use {@link #getDrawableState}. 15569 * 15570 * @param extraSpace if non-zero, this is the number of extra entries you 15571 * would like in the returned array in which you can place your own 15572 * states. 15573 * 15574 * @return Returns an array holding the current {@link Drawable} state of 15575 * the view. 15576 * 15577 * @see #mergeDrawableStates(int[], int[]) 15578 */ 15579 protected int[] onCreateDrawableState(int extraSpace) { 15580 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15581 mParent instanceof View) { 15582 return ((View) mParent).onCreateDrawableState(extraSpace); 15583 } 15584 15585 int[] drawableState; 15586 15587 int privateFlags = mPrivateFlags; 15588 15589 int viewStateIndex = 0; 15590 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15591 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15592 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15593 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15594 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15595 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15596 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15597 HardwareRenderer.isAvailable()) { 15598 // This is set if HW acceleration is requested, even if the current 15599 // process doesn't allow it. This is just to allow app preview 15600 // windows to better match their app. 15601 viewStateIndex |= VIEW_STATE_ACCELERATED; 15602 } 15603 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15604 15605 final int privateFlags2 = mPrivateFlags2; 15606 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15607 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15608 15609 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15610 15611 //noinspection ConstantIfStatement 15612 if (false) { 15613 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15614 Log.i("View", toString() 15615 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15616 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15617 + " fo=" + hasFocus() 15618 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15619 + " wf=" + hasWindowFocus() 15620 + ": " + Arrays.toString(drawableState)); 15621 } 15622 15623 if (extraSpace == 0) { 15624 return drawableState; 15625 } 15626 15627 final int[] fullState; 15628 if (drawableState != null) { 15629 fullState = new int[drawableState.length + extraSpace]; 15630 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15631 } else { 15632 fullState = new int[extraSpace]; 15633 } 15634 15635 return fullState; 15636 } 15637 15638 /** 15639 * Merge your own state values in <var>additionalState</var> into the base 15640 * state values <var>baseState</var> that were returned by 15641 * {@link #onCreateDrawableState(int)}. 15642 * 15643 * @param baseState The base state values returned by 15644 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15645 * own additional state values. 15646 * 15647 * @param additionalState The additional state values you would like 15648 * added to <var>baseState</var>; this array is not modified. 15649 * 15650 * @return As a convenience, the <var>baseState</var> array you originally 15651 * passed into the function is returned. 15652 * 15653 * @see #onCreateDrawableState(int) 15654 */ 15655 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15656 final int N = baseState.length; 15657 int i = N - 1; 15658 while (i >= 0 && baseState[i] == 0) { 15659 i--; 15660 } 15661 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15662 return baseState; 15663 } 15664 15665 /** 15666 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15667 * on all Drawable objects associated with this view. 15668 */ 15669 public void jumpDrawablesToCurrentState() { 15670 if (mBackground != null) { 15671 mBackground.jumpToCurrentState(); 15672 } 15673 } 15674 15675 /** 15676 * Sets the background color for this view. 15677 * @param color the color of the background 15678 */ 15679 @RemotableViewMethod 15680 public void setBackgroundColor(int color) { 15681 if (mBackground instanceof ColorDrawable) { 15682 ((ColorDrawable) mBackground.mutate()).setColor(color); 15683 computeOpaqueFlags(); 15684 mBackgroundResource = 0; 15685 } else { 15686 setBackground(new ColorDrawable(color)); 15687 } 15688 } 15689 15690 /** 15691 * Set the background to a given resource. The resource should refer to 15692 * a Drawable object or 0 to remove the background. 15693 * @param resid The identifier of the resource. 15694 * 15695 * @attr ref android.R.styleable#View_background 15696 */ 15697 @RemotableViewMethod 15698 public void setBackgroundResource(int resid) { 15699 if (resid != 0 && resid == mBackgroundResource) { 15700 return; 15701 } 15702 15703 Drawable d= null; 15704 if (resid != 0) { 15705 d = mContext.getDrawable(resid); 15706 } 15707 setBackground(d); 15708 15709 mBackgroundResource = resid; 15710 } 15711 15712 /** 15713 * Set the background to a given Drawable, or remove the background. If the 15714 * background has padding, this View's padding is set to the background's 15715 * padding. However, when a background is removed, this View's padding isn't 15716 * touched. If setting the padding is desired, please use 15717 * {@link #setPadding(int, int, int, int)}. 15718 * 15719 * @param background The Drawable to use as the background, or null to remove the 15720 * background 15721 */ 15722 public void setBackground(Drawable background) { 15723 //noinspection deprecation 15724 setBackgroundDrawable(background); 15725 } 15726 15727 /** 15728 * @deprecated use {@link #setBackground(Drawable)} instead 15729 */ 15730 @Deprecated 15731 public void setBackgroundDrawable(Drawable background) { 15732 computeOpaqueFlags(); 15733 15734 if (background == mBackground) { 15735 return; 15736 } 15737 15738 boolean requestLayout = false; 15739 15740 mBackgroundResource = 0; 15741 15742 /* 15743 * Regardless of whether we're setting a new background or not, we want 15744 * to clear the previous drawable. 15745 */ 15746 if (mBackground != null) { 15747 mBackground.setCallback(null); 15748 unscheduleDrawable(mBackground); 15749 } 15750 15751 if (background != null) { 15752 Rect padding = sThreadLocal.get(); 15753 if (padding == null) { 15754 padding = new Rect(); 15755 sThreadLocal.set(padding); 15756 } 15757 resetResolvedDrawables(); 15758 background.setLayoutDirection(getLayoutDirection()); 15759 if (background.getPadding(padding)) { 15760 resetResolvedPadding(); 15761 switch (background.getLayoutDirection()) { 15762 case LAYOUT_DIRECTION_RTL: 15763 mUserPaddingLeftInitial = padding.right; 15764 mUserPaddingRightInitial = padding.left; 15765 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15766 break; 15767 case LAYOUT_DIRECTION_LTR: 15768 default: 15769 mUserPaddingLeftInitial = padding.left; 15770 mUserPaddingRightInitial = padding.right; 15771 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15772 } 15773 mLeftPaddingDefined = false; 15774 mRightPaddingDefined = false; 15775 } 15776 15777 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15778 // if it has a different minimum size, we should layout again 15779 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15780 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15781 requestLayout = true; 15782 } 15783 15784 background.setCallback(this); 15785 if (background.isStateful()) { 15786 background.setState(getDrawableState()); 15787 } 15788 background.setVisible(getVisibility() == VISIBLE, false); 15789 mBackground = background; 15790 15791 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15792 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15793 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15794 requestLayout = true; 15795 } 15796 } else { 15797 /* Remove the background */ 15798 mBackground = null; 15799 15800 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15801 /* 15802 * This view ONLY drew the background before and we're removing 15803 * the background, so now it won't draw anything 15804 * (hence we SKIP_DRAW) 15805 */ 15806 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15807 mPrivateFlags |= PFLAG_SKIP_DRAW; 15808 } 15809 15810 /* 15811 * When the background is set, we try to apply its padding to this 15812 * View. When the background is removed, we don't touch this View's 15813 * padding. This is noted in the Javadocs. Hence, we don't need to 15814 * requestLayout(), the invalidate() below is sufficient. 15815 */ 15816 15817 // The old background's minimum size could have affected this 15818 // View's layout, so let's requestLayout 15819 requestLayout = true; 15820 } 15821 15822 computeOpaqueFlags(); 15823 15824 if (requestLayout) { 15825 requestLayout(); 15826 } 15827 15828 mBackgroundSizeChanged = true; 15829 invalidate(true); 15830 } 15831 15832 /** 15833 * Gets the background drawable 15834 * 15835 * @return The drawable used as the background for this view, if any. 15836 * 15837 * @see #setBackground(Drawable) 15838 * 15839 * @attr ref android.R.styleable#View_background 15840 */ 15841 public Drawable getBackground() { 15842 return mBackground; 15843 } 15844 15845 /** 15846 * Sets the padding. The view may add on the space required to display 15847 * the scrollbars, depending on the style and visibility of the scrollbars. 15848 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15849 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15850 * from the values set in this call. 15851 * 15852 * @attr ref android.R.styleable#View_padding 15853 * @attr ref android.R.styleable#View_paddingBottom 15854 * @attr ref android.R.styleable#View_paddingLeft 15855 * @attr ref android.R.styleable#View_paddingRight 15856 * @attr ref android.R.styleable#View_paddingTop 15857 * @param left the left padding in pixels 15858 * @param top the top padding in pixels 15859 * @param right the right padding in pixels 15860 * @param bottom the bottom padding in pixels 15861 */ 15862 public void setPadding(int left, int top, int right, int bottom) { 15863 resetResolvedPadding(); 15864 15865 mUserPaddingStart = UNDEFINED_PADDING; 15866 mUserPaddingEnd = UNDEFINED_PADDING; 15867 15868 mUserPaddingLeftInitial = left; 15869 mUserPaddingRightInitial = right; 15870 15871 mLeftPaddingDefined = true; 15872 mRightPaddingDefined = true; 15873 15874 internalSetPadding(left, top, right, bottom); 15875 } 15876 15877 /** 15878 * @hide 15879 */ 15880 protected void internalSetPadding(int left, int top, int right, int bottom) { 15881 mUserPaddingLeft = left; 15882 mUserPaddingRight = right; 15883 mUserPaddingBottom = bottom; 15884 15885 final int viewFlags = mViewFlags; 15886 boolean changed = false; 15887 15888 // Common case is there are no scroll bars. 15889 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15890 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15891 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15892 ? 0 : getVerticalScrollbarWidth(); 15893 switch (mVerticalScrollbarPosition) { 15894 case SCROLLBAR_POSITION_DEFAULT: 15895 if (isLayoutRtl()) { 15896 left += offset; 15897 } else { 15898 right += offset; 15899 } 15900 break; 15901 case SCROLLBAR_POSITION_RIGHT: 15902 right += offset; 15903 break; 15904 case SCROLLBAR_POSITION_LEFT: 15905 left += offset; 15906 break; 15907 } 15908 } 15909 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15910 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15911 ? 0 : getHorizontalScrollbarHeight(); 15912 } 15913 } 15914 15915 if (mPaddingLeft != left) { 15916 changed = true; 15917 mPaddingLeft = left; 15918 } 15919 if (mPaddingTop != top) { 15920 changed = true; 15921 mPaddingTop = top; 15922 } 15923 if (mPaddingRight != right) { 15924 changed = true; 15925 mPaddingRight = right; 15926 } 15927 if (mPaddingBottom != bottom) { 15928 changed = true; 15929 mPaddingBottom = bottom; 15930 } 15931 15932 if (changed) { 15933 requestLayout(); 15934 } 15935 } 15936 15937 /** 15938 * Sets the relative padding. The view may add on the space required to display 15939 * the scrollbars, depending on the style and visibility of the scrollbars. 15940 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15941 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15942 * from the values set in this call. 15943 * 15944 * @attr ref android.R.styleable#View_padding 15945 * @attr ref android.R.styleable#View_paddingBottom 15946 * @attr ref android.R.styleable#View_paddingStart 15947 * @attr ref android.R.styleable#View_paddingEnd 15948 * @attr ref android.R.styleable#View_paddingTop 15949 * @param start the start padding in pixels 15950 * @param top the top padding in pixels 15951 * @param end the end padding in pixels 15952 * @param bottom the bottom padding in pixels 15953 */ 15954 public void setPaddingRelative(int start, int top, int end, int bottom) { 15955 resetResolvedPadding(); 15956 15957 mUserPaddingStart = start; 15958 mUserPaddingEnd = end; 15959 mLeftPaddingDefined = true; 15960 mRightPaddingDefined = true; 15961 15962 switch(getLayoutDirection()) { 15963 case LAYOUT_DIRECTION_RTL: 15964 mUserPaddingLeftInitial = end; 15965 mUserPaddingRightInitial = start; 15966 internalSetPadding(end, top, start, bottom); 15967 break; 15968 case LAYOUT_DIRECTION_LTR: 15969 default: 15970 mUserPaddingLeftInitial = start; 15971 mUserPaddingRightInitial = end; 15972 internalSetPadding(start, top, end, bottom); 15973 } 15974 } 15975 15976 /** 15977 * Returns the top padding of this view. 15978 * 15979 * @return the top padding in pixels 15980 */ 15981 public int getPaddingTop() { 15982 return mPaddingTop; 15983 } 15984 15985 /** 15986 * Returns the bottom padding of this view. If there are inset and enabled 15987 * scrollbars, this value may include the space required to display the 15988 * scrollbars as well. 15989 * 15990 * @return the bottom padding in pixels 15991 */ 15992 public int getPaddingBottom() { 15993 return mPaddingBottom; 15994 } 15995 15996 /** 15997 * Returns the left padding of this view. If there are inset and enabled 15998 * scrollbars, this value may include the space required to display the 15999 * scrollbars as well. 16000 * 16001 * @return the left padding in pixels 16002 */ 16003 public int getPaddingLeft() { 16004 if (!isPaddingResolved()) { 16005 resolvePadding(); 16006 } 16007 return mPaddingLeft; 16008 } 16009 16010 /** 16011 * Returns the start padding of this view depending on its resolved layout direction. 16012 * If there are inset and enabled scrollbars, this value may include the space 16013 * required to display the scrollbars as well. 16014 * 16015 * @return the start padding in pixels 16016 */ 16017 public int getPaddingStart() { 16018 if (!isPaddingResolved()) { 16019 resolvePadding(); 16020 } 16021 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16022 mPaddingRight : mPaddingLeft; 16023 } 16024 16025 /** 16026 * Returns the right padding of this view. If there are inset and enabled 16027 * scrollbars, this value may include the space required to display the 16028 * scrollbars as well. 16029 * 16030 * @return the right padding in pixels 16031 */ 16032 public int getPaddingRight() { 16033 if (!isPaddingResolved()) { 16034 resolvePadding(); 16035 } 16036 return mPaddingRight; 16037 } 16038 16039 /** 16040 * Returns the end padding of this view depending on its resolved layout direction. 16041 * If there are inset and enabled scrollbars, this value may include the space 16042 * required to display the scrollbars as well. 16043 * 16044 * @return the end padding in pixels 16045 */ 16046 public int getPaddingEnd() { 16047 if (!isPaddingResolved()) { 16048 resolvePadding(); 16049 } 16050 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16051 mPaddingLeft : mPaddingRight; 16052 } 16053 16054 /** 16055 * Return if the padding as been set thru relative values 16056 * {@link #setPaddingRelative(int, int, int, int)} or thru 16057 * @attr ref android.R.styleable#View_paddingStart or 16058 * @attr ref android.R.styleable#View_paddingEnd 16059 * 16060 * @return true if the padding is relative or false if it is not. 16061 */ 16062 public boolean isPaddingRelative() { 16063 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16064 } 16065 16066 Insets computeOpticalInsets() { 16067 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16068 } 16069 16070 /** 16071 * @hide 16072 */ 16073 public void resetPaddingToInitialValues() { 16074 if (isRtlCompatibilityMode()) { 16075 mPaddingLeft = mUserPaddingLeftInitial; 16076 mPaddingRight = mUserPaddingRightInitial; 16077 return; 16078 } 16079 if (isLayoutRtl()) { 16080 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16081 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16082 } else { 16083 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16084 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16085 } 16086 } 16087 16088 /** 16089 * @hide 16090 */ 16091 public Insets getOpticalInsets() { 16092 if (mLayoutInsets == null) { 16093 mLayoutInsets = computeOpticalInsets(); 16094 } 16095 return mLayoutInsets; 16096 } 16097 16098 /** 16099 * Changes the selection state of this view. A view can be selected or not. 16100 * Note that selection is not the same as focus. Views are typically 16101 * selected in the context of an AdapterView like ListView or GridView; 16102 * the selected view is the view that is highlighted. 16103 * 16104 * @param selected true if the view must be selected, false otherwise 16105 */ 16106 public void setSelected(boolean selected) { 16107 //noinspection DoubleNegation 16108 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16109 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16110 if (!selected) resetPressedState(); 16111 invalidate(true); 16112 refreshDrawableState(); 16113 dispatchSetSelected(selected); 16114 notifyViewAccessibilityStateChangedIfNeeded( 16115 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16116 } 16117 } 16118 16119 /** 16120 * Dispatch setSelected to all of this View's children. 16121 * 16122 * @see #setSelected(boolean) 16123 * 16124 * @param selected The new selected state 16125 */ 16126 protected void dispatchSetSelected(boolean selected) { 16127 } 16128 16129 /** 16130 * Indicates the selection state of this view. 16131 * 16132 * @return true if the view is selected, false otherwise 16133 */ 16134 @ViewDebug.ExportedProperty 16135 public boolean isSelected() { 16136 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16137 } 16138 16139 /** 16140 * Changes the activated state of this view. A view can be activated or not. 16141 * Note that activation is not the same as selection. Selection is 16142 * a transient property, representing the view (hierarchy) the user is 16143 * currently interacting with. Activation is a longer-term state that the 16144 * user can move views in and out of. For example, in a list view with 16145 * single or multiple selection enabled, the views in the current selection 16146 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16147 * here.) The activated state is propagated down to children of the view it 16148 * is set on. 16149 * 16150 * @param activated true if the view must be activated, false otherwise 16151 */ 16152 public void setActivated(boolean activated) { 16153 //noinspection DoubleNegation 16154 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16155 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16156 invalidate(true); 16157 refreshDrawableState(); 16158 dispatchSetActivated(activated); 16159 } 16160 } 16161 16162 /** 16163 * Dispatch setActivated to all of this View's children. 16164 * 16165 * @see #setActivated(boolean) 16166 * 16167 * @param activated The new activated state 16168 */ 16169 protected void dispatchSetActivated(boolean activated) { 16170 } 16171 16172 /** 16173 * Indicates the activation state of this view. 16174 * 16175 * @return true if the view is activated, false otherwise 16176 */ 16177 @ViewDebug.ExportedProperty 16178 public boolean isActivated() { 16179 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16180 } 16181 16182 /** 16183 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16184 * observer can be used to get notifications when global events, like 16185 * layout, happen. 16186 * 16187 * The returned ViewTreeObserver observer is not guaranteed to remain 16188 * valid for the lifetime of this View. If the caller of this method keeps 16189 * a long-lived reference to ViewTreeObserver, it should always check for 16190 * the return value of {@link ViewTreeObserver#isAlive()}. 16191 * 16192 * @return The ViewTreeObserver for this view's hierarchy. 16193 */ 16194 public ViewTreeObserver getViewTreeObserver() { 16195 if (mAttachInfo != null) { 16196 return mAttachInfo.mTreeObserver; 16197 } 16198 if (mFloatingTreeObserver == null) { 16199 mFloatingTreeObserver = new ViewTreeObserver(); 16200 } 16201 return mFloatingTreeObserver; 16202 } 16203 16204 /** 16205 * <p>Finds the topmost view in the current view hierarchy.</p> 16206 * 16207 * @return the topmost view containing this view 16208 */ 16209 public View getRootView() { 16210 if (mAttachInfo != null) { 16211 final View v = mAttachInfo.mRootView; 16212 if (v != null) { 16213 return v; 16214 } 16215 } 16216 16217 View parent = this; 16218 16219 while (parent.mParent != null && parent.mParent instanceof View) { 16220 parent = (View) parent.mParent; 16221 } 16222 16223 return parent; 16224 } 16225 16226 /** 16227 * Transforms a motion event from view-local coordinates to on-screen 16228 * coordinates. 16229 * 16230 * @param ev the view-local motion event 16231 * @return false if the transformation could not be applied 16232 * @hide 16233 */ 16234 public boolean toGlobalMotionEvent(MotionEvent ev) { 16235 final AttachInfo info = mAttachInfo; 16236 if (info == null) { 16237 return false; 16238 } 16239 16240 final Matrix m = info.mTmpMatrix; 16241 m.set(Matrix.IDENTITY_MATRIX); 16242 transformMatrixToGlobal(m); 16243 ev.transform(m); 16244 return true; 16245 } 16246 16247 /** 16248 * Transforms a motion event from on-screen coordinates to view-local 16249 * coordinates. 16250 * 16251 * @param ev the on-screen motion event 16252 * @return false if the transformation could not be applied 16253 * @hide 16254 */ 16255 public boolean toLocalMotionEvent(MotionEvent ev) { 16256 final AttachInfo info = mAttachInfo; 16257 if (info == null) { 16258 return false; 16259 } 16260 16261 final Matrix m = info.mTmpMatrix; 16262 m.set(Matrix.IDENTITY_MATRIX); 16263 transformMatrixToLocal(m); 16264 ev.transform(m); 16265 return true; 16266 } 16267 16268 /** 16269 * Modifies the input matrix such that it maps view-local coordinates to 16270 * on-screen coordinates. 16271 * 16272 * @param m input matrix to modify 16273 */ 16274 void transformMatrixToGlobal(Matrix m) { 16275 final ViewParent parent = mParent; 16276 if (parent instanceof View) { 16277 final View vp = (View) parent; 16278 vp.transformMatrixToGlobal(m); 16279 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16280 } else if (parent instanceof ViewRootImpl) { 16281 final ViewRootImpl vr = (ViewRootImpl) parent; 16282 vr.transformMatrixToGlobal(m); 16283 m.postTranslate(0, -vr.mCurScrollY); 16284 } 16285 16286 m.postTranslate(mLeft, mTop); 16287 16288 if (!hasIdentityMatrix()) { 16289 m.postConcat(getMatrix()); 16290 } 16291 } 16292 16293 /** 16294 * Modifies the input matrix such that it maps on-screen coordinates to 16295 * view-local coordinates. 16296 * 16297 * @param m input matrix to modify 16298 */ 16299 void transformMatrixToLocal(Matrix m) { 16300 final ViewParent parent = mParent; 16301 if (parent instanceof View) { 16302 final View vp = (View) parent; 16303 vp.transformMatrixToLocal(m); 16304 m.preTranslate(vp.mScrollX, vp.mScrollY); 16305 } else if (parent instanceof ViewRootImpl) { 16306 final ViewRootImpl vr = (ViewRootImpl) parent; 16307 vr.transformMatrixToLocal(m); 16308 m.preTranslate(0, vr.mCurScrollY); 16309 } 16310 16311 m.preTranslate(-mLeft, -mTop); 16312 16313 if (!hasIdentityMatrix()) { 16314 m.preConcat(getInverseMatrix()); 16315 } 16316 } 16317 16318 /** 16319 * <p>Computes the coordinates of this view on the screen. The argument 16320 * must be an array of two integers. After the method returns, the array 16321 * contains the x and y location in that order.</p> 16322 * 16323 * @param location an array of two integers in which to hold the coordinates 16324 */ 16325 public void getLocationOnScreen(int[] location) { 16326 getLocationInWindow(location); 16327 16328 final AttachInfo info = mAttachInfo; 16329 if (info != null) { 16330 location[0] += info.mWindowLeft; 16331 location[1] += info.mWindowTop; 16332 } 16333 } 16334 16335 /** 16336 * <p>Computes the coordinates of this view in its window. The argument 16337 * must be an array of two integers. After the method returns, the array 16338 * contains the x and y location in that order.</p> 16339 * 16340 * @param location an array of two integers in which to hold the coordinates 16341 */ 16342 public void getLocationInWindow(int[] location) { 16343 if (location == null || location.length < 2) { 16344 throw new IllegalArgumentException("location must be an array of two integers"); 16345 } 16346 16347 if (mAttachInfo == null) { 16348 // When the view is not attached to a window, this method does not make sense 16349 location[0] = location[1] = 0; 16350 return; 16351 } 16352 16353 float[] position = mAttachInfo.mTmpTransformLocation; 16354 position[0] = position[1] = 0.0f; 16355 16356 if (!hasIdentityMatrix()) { 16357 getMatrix().mapPoints(position); 16358 } 16359 16360 position[0] += mLeft; 16361 position[1] += mTop; 16362 16363 ViewParent viewParent = mParent; 16364 while (viewParent instanceof View) { 16365 final View view = (View) viewParent; 16366 16367 position[0] -= view.mScrollX; 16368 position[1] -= view.mScrollY; 16369 16370 if (!view.hasIdentityMatrix()) { 16371 view.getMatrix().mapPoints(position); 16372 } 16373 16374 position[0] += view.mLeft; 16375 position[1] += view.mTop; 16376 16377 viewParent = view.mParent; 16378 } 16379 16380 if (viewParent instanceof ViewRootImpl) { 16381 // *cough* 16382 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16383 position[1] -= vr.mCurScrollY; 16384 } 16385 16386 location[0] = (int) (position[0] + 0.5f); 16387 location[1] = (int) (position[1] + 0.5f); 16388 } 16389 16390 /** 16391 * {@hide} 16392 * @param id the id of the view to be found 16393 * @return the view of the specified id, null if cannot be found 16394 */ 16395 protected View findViewTraversal(int id) { 16396 if (id == mID) { 16397 return this; 16398 } 16399 return null; 16400 } 16401 16402 /** 16403 * {@hide} 16404 * @param tag the tag of the view to be found 16405 * @return the view of specified tag, null if cannot be found 16406 */ 16407 protected View findViewWithTagTraversal(Object tag) { 16408 if (tag != null && tag.equals(mTag)) { 16409 return this; 16410 } 16411 return null; 16412 } 16413 16414 /** 16415 * {@hide} 16416 * @param predicate The predicate to evaluate. 16417 * @param childToSkip If not null, ignores this child during the recursive traversal. 16418 * @return The first view that matches the predicate or null. 16419 */ 16420 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16421 if (predicate.apply(this)) { 16422 return this; 16423 } 16424 return null; 16425 } 16426 16427 /** 16428 * Look for a child view with the given id. If this view has the given 16429 * id, return this view. 16430 * 16431 * @param id The id to search for. 16432 * @return The view that has the given id in the hierarchy or null 16433 */ 16434 public final View findViewById(int id) { 16435 if (id < 0) { 16436 return null; 16437 } 16438 return findViewTraversal(id); 16439 } 16440 16441 /** 16442 * Finds a view by its unuque and stable accessibility id. 16443 * 16444 * @param accessibilityId The searched accessibility id. 16445 * @return The found view. 16446 */ 16447 final View findViewByAccessibilityId(int accessibilityId) { 16448 if (accessibilityId < 0) { 16449 return null; 16450 } 16451 return findViewByAccessibilityIdTraversal(accessibilityId); 16452 } 16453 16454 /** 16455 * Performs the traversal to find a view by its unuque and stable accessibility id. 16456 * 16457 * <strong>Note:</strong>This method does not stop at the root namespace 16458 * boundary since the user can touch the screen at an arbitrary location 16459 * potentially crossing the root namespace bounday which will send an 16460 * accessibility event to accessibility services and they should be able 16461 * to obtain the event source. Also accessibility ids are guaranteed to be 16462 * unique in the window. 16463 * 16464 * @param accessibilityId The accessibility id. 16465 * @return The found view. 16466 * 16467 * @hide 16468 */ 16469 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16470 if (getAccessibilityViewId() == accessibilityId) { 16471 return this; 16472 } 16473 return null; 16474 } 16475 16476 /** 16477 * Look for a child view with the given tag. If this view has the given 16478 * tag, return this view. 16479 * 16480 * @param tag The tag to search for, using "tag.equals(getTag())". 16481 * @return The View that has the given tag in the hierarchy or null 16482 */ 16483 public final View findViewWithTag(Object tag) { 16484 if (tag == null) { 16485 return null; 16486 } 16487 return findViewWithTagTraversal(tag); 16488 } 16489 16490 /** 16491 * {@hide} 16492 * Look for a child view that matches the specified predicate. 16493 * If this view matches the predicate, return this view. 16494 * 16495 * @param predicate The predicate to evaluate. 16496 * @return The first view that matches the predicate or null. 16497 */ 16498 public final View findViewByPredicate(Predicate<View> predicate) { 16499 return findViewByPredicateTraversal(predicate, null); 16500 } 16501 16502 /** 16503 * {@hide} 16504 * Look for a child view that matches the specified predicate, 16505 * starting with the specified view and its descendents and then 16506 * recusively searching the ancestors and siblings of that view 16507 * until this view is reached. 16508 * 16509 * This method is useful in cases where the predicate does not match 16510 * a single unique view (perhaps multiple views use the same id) 16511 * and we are trying to find the view that is "closest" in scope to the 16512 * starting view. 16513 * 16514 * @param start The view to start from. 16515 * @param predicate The predicate to evaluate. 16516 * @return The first view that matches the predicate or null. 16517 */ 16518 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16519 View childToSkip = null; 16520 for (;;) { 16521 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16522 if (view != null || start == this) { 16523 return view; 16524 } 16525 16526 ViewParent parent = start.getParent(); 16527 if (parent == null || !(parent instanceof View)) { 16528 return null; 16529 } 16530 16531 childToSkip = start; 16532 start = (View) parent; 16533 } 16534 } 16535 16536 /** 16537 * Sets the identifier for this view. The identifier does not have to be 16538 * unique in this view's hierarchy. The identifier should be a positive 16539 * number. 16540 * 16541 * @see #NO_ID 16542 * @see #getId() 16543 * @see #findViewById(int) 16544 * 16545 * @param id a number used to identify the view 16546 * 16547 * @attr ref android.R.styleable#View_id 16548 */ 16549 public void setId(int id) { 16550 mID = id; 16551 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16552 mID = generateViewId(); 16553 } 16554 } 16555 16556 /** 16557 * {@hide} 16558 * 16559 * @param isRoot true if the view belongs to the root namespace, false 16560 * otherwise 16561 */ 16562 public void setIsRootNamespace(boolean isRoot) { 16563 if (isRoot) { 16564 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16565 } else { 16566 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16567 } 16568 } 16569 16570 /** 16571 * {@hide} 16572 * 16573 * @return true if the view belongs to the root namespace, false otherwise 16574 */ 16575 public boolean isRootNamespace() { 16576 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16577 } 16578 16579 /** 16580 * Returns this view's identifier. 16581 * 16582 * @return a positive integer used to identify the view or {@link #NO_ID} 16583 * if the view has no ID 16584 * 16585 * @see #setId(int) 16586 * @see #findViewById(int) 16587 * @attr ref android.R.styleable#View_id 16588 */ 16589 @ViewDebug.CapturedViewProperty 16590 public int getId() { 16591 return mID; 16592 } 16593 16594 /** 16595 * Returns this view's tag. 16596 * 16597 * @return the Object stored in this view as a tag, or {@code null} if not 16598 * set 16599 * 16600 * @see #setTag(Object) 16601 * @see #getTag(int) 16602 */ 16603 @ViewDebug.ExportedProperty 16604 public Object getTag() { 16605 return mTag; 16606 } 16607 16608 /** 16609 * Sets the tag associated with this view. A tag can be used to mark 16610 * a view in its hierarchy and does not have to be unique within the 16611 * hierarchy. Tags can also be used to store data within a view without 16612 * resorting to another data structure. 16613 * 16614 * @param tag an Object to tag the view with 16615 * 16616 * @see #getTag() 16617 * @see #setTag(int, Object) 16618 */ 16619 public void setTag(final Object tag) { 16620 mTag = tag; 16621 } 16622 16623 /** 16624 * Returns the tag associated with this view and the specified key. 16625 * 16626 * @param key The key identifying the tag 16627 * 16628 * @return the Object stored in this view as a tag, or {@code null} if not 16629 * set 16630 * 16631 * @see #setTag(int, Object) 16632 * @see #getTag() 16633 */ 16634 public Object getTag(int key) { 16635 if (mKeyedTags != null) return mKeyedTags.get(key); 16636 return null; 16637 } 16638 16639 /** 16640 * Sets a tag associated with this view and a key. A tag can be used 16641 * to mark a view in its hierarchy and does not have to be unique within 16642 * the hierarchy. Tags can also be used to store data within a view 16643 * without resorting to another data structure. 16644 * 16645 * The specified key should be an id declared in the resources of the 16646 * application to ensure it is unique (see the <a 16647 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16648 * Keys identified as belonging to 16649 * the Android framework or not associated with any package will cause 16650 * an {@link IllegalArgumentException} to be thrown. 16651 * 16652 * @param key The key identifying the tag 16653 * @param tag An Object to tag the view with 16654 * 16655 * @throws IllegalArgumentException If they specified key is not valid 16656 * 16657 * @see #setTag(Object) 16658 * @see #getTag(int) 16659 */ 16660 public void setTag(int key, final Object tag) { 16661 // If the package id is 0x00 or 0x01, it's either an undefined package 16662 // or a framework id 16663 if ((key >>> 24) < 2) { 16664 throw new IllegalArgumentException("The key must be an application-specific " 16665 + "resource id."); 16666 } 16667 16668 setKeyedTag(key, tag); 16669 } 16670 16671 /** 16672 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16673 * framework id. 16674 * 16675 * @hide 16676 */ 16677 public void setTagInternal(int key, Object tag) { 16678 if ((key >>> 24) != 0x1) { 16679 throw new IllegalArgumentException("The key must be a framework-specific " 16680 + "resource id."); 16681 } 16682 16683 setKeyedTag(key, tag); 16684 } 16685 16686 private void setKeyedTag(int key, Object tag) { 16687 if (mKeyedTags == null) { 16688 mKeyedTags = new SparseArray<Object>(2); 16689 } 16690 16691 mKeyedTags.put(key, tag); 16692 } 16693 16694 /** 16695 * Prints information about this view in the log output, with the tag 16696 * {@link #VIEW_LOG_TAG}. 16697 * 16698 * @hide 16699 */ 16700 public void debug() { 16701 debug(0); 16702 } 16703 16704 /** 16705 * Prints information about this view in the log output, with the tag 16706 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16707 * indentation defined by the <code>depth</code>. 16708 * 16709 * @param depth the indentation level 16710 * 16711 * @hide 16712 */ 16713 protected void debug(int depth) { 16714 String output = debugIndent(depth - 1); 16715 16716 output += "+ " + this; 16717 int id = getId(); 16718 if (id != -1) { 16719 output += " (id=" + id + ")"; 16720 } 16721 Object tag = getTag(); 16722 if (tag != null) { 16723 output += " (tag=" + tag + ")"; 16724 } 16725 Log.d(VIEW_LOG_TAG, output); 16726 16727 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16728 output = debugIndent(depth) + " FOCUSED"; 16729 Log.d(VIEW_LOG_TAG, output); 16730 } 16731 16732 output = debugIndent(depth); 16733 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16734 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16735 + "} "; 16736 Log.d(VIEW_LOG_TAG, output); 16737 16738 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16739 || mPaddingBottom != 0) { 16740 output = debugIndent(depth); 16741 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16742 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16743 Log.d(VIEW_LOG_TAG, output); 16744 } 16745 16746 output = debugIndent(depth); 16747 output += "mMeasureWidth=" + mMeasuredWidth + 16748 " mMeasureHeight=" + mMeasuredHeight; 16749 Log.d(VIEW_LOG_TAG, output); 16750 16751 output = debugIndent(depth); 16752 if (mLayoutParams == null) { 16753 output += "BAD! no layout params"; 16754 } else { 16755 output = mLayoutParams.debug(output); 16756 } 16757 Log.d(VIEW_LOG_TAG, output); 16758 16759 output = debugIndent(depth); 16760 output += "flags={"; 16761 output += View.printFlags(mViewFlags); 16762 output += "}"; 16763 Log.d(VIEW_LOG_TAG, output); 16764 16765 output = debugIndent(depth); 16766 output += "privateFlags={"; 16767 output += View.printPrivateFlags(mPrivateFlags); 16768 output += "}"; 16769 Log.d(VIEW_LOG_TAG, output); 16770 } 16771 16772 /** 16773 * Creates a string of whitespaces used for indentation. 16774 * 16775 * @param depth the indentation level 16776 * @return a String containing (depth * 2 + 3) * 2 white spaces 16777 * 16778 * @hide 16779 */ 16780 protected static String debugIndent(int depth) { 16781 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16782 for (int i = 0; i < (depth * 2) + 3; i++) { 16783 spaces.append(' ').append(' '); 16784 } 16785 return spaces.toString(); 16786 } 16787 16788 /** 16789 * <p>Return the offset of the widget's text baseline from the widget's top 16790 * boundary. If this widget does not support baseline alignment, this 16791 * method returns -1. </p> 16792 * 16793 * @return the offset of the baseline within the widget's bounds or -1 16794 * if baseline alignment is not supported 16795 */ 16796 @ViewDebug.ExportedProperty(category = "layout") 16797 public int getBaseline() { 16798 return -1; 16799 } 16800 16801 /** 16802 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16803 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16804 * a layout pass. 16805 * 16806 * @return whether the view hierarchy is currently undergoing a layout pass 16807 */ 16808 public boolean isInLayout() { 16809 ViewRootImpl viewRoot = getViewRootImpl(); 16810 return (viewRoot != null && viewRoot.isInLayout()); 16811 } 16812 16813 /** 16814 * Call this when something has changed which has invalidated the 16815 * layout of this view. This will schedule a layout pass of the view 16816 * tree. This should not be called while the view hierarchy is currently in a layout 16817 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16818 * end of the current layout pass (and then layout will run again) or after the current 16819 * frame is drawn and the next layout occurs. 16820 * 16821 * <p>Subclasses which override this method should call the superclass method to 16822 * handle possible request-during-layout errors correctly.</p> 16823 */ 16824 public void requestLayout() { 16825 if (mMeasureCache != null) mMeasureCache.clear(); 16826 16827 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16828 // Only trigger request-during-layout logic if this is the view requesting it, 16829 // not the views in its parent hierarchy 16830 ViewRootImpl viewRoot = getViewRootImpl(); 16831 if (viewRoot != null && viewRoot.isInLayout()) { 16832 if (!viewRoot.requestLayoutDuringLayout(this)) { 16833 return; 16834 } 16835 } 16836 mAttachInfo.mViewRequestingLayout = this; 16837 } 16838 16839 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16840 mPrivateFlags |= PFLAG_INVALIDATED; 16841 16842 if (mParent != null && !mParent.isLayoutRequested()) { 16843 mParent.requestLayout(); 16844 } 16845 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16846 mAttachInfo.mViewRequestingLayout = null; 16847 } 16848 } 16849 16850 /** 16851 * Forces this view to be laid out during the next layout pass. 16852 * This method does not call requestLayout() or forceLayout() 16853 * on the parent. 16854 */ 16855 public void forceLayout() { 16856 if (mMeasureCache != null) mMeasureCache.clear(); 16857 16858 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16859 mPrivateFlags |= PFLAG_INVALIDATED; 16860 } 16861 16862 /** 16863 * <p> 16864 * This is called to find out how big a view should be. The parent 16865 * supplies constraint information in the width and height parameters. 16866 * </p> 16867 * 16868 * <p> 16869 * The actual measurement work of a view is performed in 16870 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16871 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16872 * </p> 16873 * 16874 * 16875 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16876 * parent 16877 * @param heightMeasureSpec Vertical space requirements as imposed by the 16878 * parent 16879 * 16880 * @see #onMeasure(int, int) 16881 */ 16882 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16883 boolean optical = isLayoutModeOptical(this); 16884 if (optical != isLayoutModeOptical(mParent)) { 16885 Insets insets = getOpticalInsets(); 16886 int oWidth = insets.left + insets.right; 16887 int oHeight = insets.top + insets.bottom; 16888 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16889 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16890 } 16891 16892 // Suppress sign extension for the low bytes 16893 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16894 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16895 16896 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16897 widthMeasureSpec != mOldWidthMeasureSpec || 16898 heightMeasureSpec != mOldHeightMeasureSpec) { 16899 16900 // first clears the measured dimension flag 16901 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16902 16903 resolveRtlPropertiesIfNeeded(); 16904 16905 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16906 mMeasureCache.indexOfKey(key); 16907 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16908 // measure ourselves, this should set the measured dimension flag back 16909 onMeasure(widthMeasureSpec, heightMeasureSpec); 16910 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16911 } else { 16912 long value = mMeasureCache.valueAt(cacheIndex); 16913 // Casting a long to int drops the high 32 bits, no mask needed 16914 setMeasuredDimension((int) (value >> 32), (int) value); 16915 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16916 } 16917 16918 // flag not set, setMeasuredDimension() was not invoked, we raise 16919 // an exception to warn the developer 16920 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16921 throw new IllegalStateException("onMeasure() did not set the" 16922 + " measured dimension by calling" 16923 + " setMeasuredDimension()"); 16924 } 16925 16926 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16927 } 16928 16929 mOldWidthMeasureSpec = widthMeasureSpec; 16930 mOldHeightMeasureSpec = heightMeasureSpec; 16931 16932 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16933 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16934 } 16935 16936 /** 16937 * <p> 16938 * Measure the view and its content to determine the measured width and the 16939 * measured height. This method is invoked by {@link #measure(int, int)} and 16940 * should be overriden by subclasses to provide accurate and efficient 16941 * measurement of their contents. 16942 * </p> 16943 * 16944 * <p> 16945 * <strong>CONTRACT:</strong> When overriding this method, you 16946 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16947 * measured width and height of this view. Failure to do so will trigger an 16948 * <code>IllegalStateException</code>, thrown by 16949 * {@link #measure(int, int)}. Calling the superclass' 16950 * {@link #onMeasure(int, int)} is a valid use. 16951 * </p> 16952 * 16953 * <p> 16954 * The base class implementation of measure defaults to the background size, 16955 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16956 * override {@link #onMeasure(int, int)} to provide better measurements of 16957 * their content. 16958 * </p> 16959 * 16960 * <p> 16961 * If this method is overridden, it is the subclass's responsibility to make 16962 * sure the measured height and width are at least the view's minimum height 16963 * and width ({@link #getSuggestedMinimumHeight()} and 16964 * {@link #getSuggestedMinimumWidth()}). 16965 * </p> 16966 * 16967 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16968 * The requirements are encoded with 16969 * {@link android.view.View.MeasureSpec}. 16970 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16971 * The requirements are encoded with 16972 * {@link android.view.View.MeasureSpec}. 16973 * 16974 * @see #getMeasuredWidth() 16975 * @see #getMeasuredHeight() 16976 * @see #setMeasuredDimension(int, int) 16977 * @see #getSuggestedMinimumHeight() 16978 * @see #getSuggestedMinimumWidth() 16979 * @see android.view.View.MeasureSpec#getMode(int) 16980 * @see android.view.View.MeasureSpec#getSize(int) 16981 */ 16982 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16983 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16984 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16985 } 16986 16987 /** 16988 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16989 * measured width and measured height. Failing to do so will trigger an 16990 * exception at measurement time.</p> 16991 * 16992 * @param measuredWidth The measured width of this view. May be a complex 16993 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16994 * {@link #MEASURED_STATE_TOO_SMALL}. 16995 * @param measuredHeight The measured height of this view. May be a complex 16996 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16997 * {@link #MEASURED_STATE_TOO_SMALL}. 16998 */ 16999 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17000 boolean optical = isLayoutModeOptical(this); 17001 if (optical != isLayoutModeOptical(mParent)) { 17002 Insets insets = getOpticalInsets(); 17003 int opticalWidth = insets.left + insets.right; 17004 int opticalHeight = insets.top + insets.bottom; 17005 17006 measuredWidth += optical ? opticalWidth : -opticalWidth; 17007 measuredHeight += optical ? opticalHeight : -opticalHeight; 17008 } 17009 mMeasuredWidth = measuredWidth; 17010 mMeasuredHeight = measuredHeight; 17011 17012 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17013 } 17014 17015 /** 17016 * Merge two states as returned by {@link #getMeasuredState()}. 17017 * @param curState The current state as returned from a view or the result 17018 * of combining multiple views. 17019 * @param newState The new view state to combine. 17020 * @return Returns a new integer reflecting the combination of the two 17021 * states. 17022 */ 17023 public static int combineMeasuredStates(int curState, int newState) { 17024 return curState | newState; 17025 } 17026 17027 /** 17028 * Version of {@link #resolveSizeAndState(int, int, int)} 17029 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17030 */ 17031 public static int resolveSize(int size, int measureSpec) { 17032 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17033 } 17034 17035 /** 17036 * Utility to reconcile a desired size and state, with constraints imposed 17037 * by a MeasureSpec. Will take the desired size, unless a different size 17038 * is imposed by the constraints. The returned value is a compound integer, 17039 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17040 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17041 * size is smaller than the size the view wants to be. 17042 * 17043 * @param size How big the view wants to be 17044 * @param measureSpec Constraints imposed by the parent 17045 * @return Size information bit mask as defined by 17046 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17047 */ 17048 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17049 int result = size; 17050 int specMode = MeasureSpec.getMode(measureSpec); 17051 int specSize = MeasureSpec.getSize(measureSpec); 17052 switch (specMode) { 17053 case MeasureSpec.UNSPECIFIED: 17054 result = size; 17055 break; 17056 case MeasureSpec.AT_MOST: 17057 if (specSize < size) { 17058 result = specSize | MEASURED_STATE_TOO_SMALL; 17059 } else { 17060 result = size; 17061 } 17062 break; 17063 case MeasureSpec.EXACTLY: 17064 result = specSize; 17065 break; 17066 } 17067 return result | (childMeasuredState&MEASURED_STATE_MASK); 17068 } 17069 17070 /** 17071 * Utility to return a default size. Uses the supplied size if the 17072 * MeasureSpec imposed no constraints. Will get larger if allowed 17073 * by the MeasureSpec. 17074 * 17075 * @param size Default size for this view 17076 * @param measureSpec Constraints imposed by the parent 17077 * @return The size this view should be. 17078 */ 17079 public static int getDefaultSize(int size, int measureSpec) { 17080 int result = size; 17081 int specMode = MeasureSpec.getMode(measureSpec); 17082 int specSize = MeasureSpec.getSize(measureSpec); 17083 17084 switch (specMode) { 17085 case MeasureSpec.UNSPECIFIED: 17086 result = size; 17087 break; 17088 case MeasureSpec.AT_MOST: 17089 case MeasureSpec.EXACTLY: 17090 result = specSize; 17091 break; 17092 } 17093 return result; 17094 } 17095 17096 /** 17097 * Returns the suggested minimum height that the view should use. This 17098 * returns the maximum of the view's minimum height 17099 * and the background's minimum height 17100 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17101 * <p> 17102 * When being used in {@link #onMeasure(int, int)}, the caller should still 17103 * ensure the returned height is within the requirements of the parent. 17104 * 17105 * @return The suggested minimum height of the view. 17106 */ 17107 protected int getSuggestedMinimumHeight() { 17108 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17109 17110 } 17111 17112 /** 17113 * Returns the suggested minimum width that the view should use. This 17114 * returns the maximum of the view's minimum width) 17115 * and the background's minimum width 17116 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17117 * <p> 17118 * When being used in {@link #onMeasure(int, int)}, the caller should still 17119 * ensure the returned width is within the requirements of the parent. 17120 * 17121 * @return The suggested minimum width of the view. 17122 */ 17123 protected int getSuggestedMinimumWidth() { 17124 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17125 } 17126 17127 /** 17128 * Returns the minimum height of the view. 17129 * 17130 * @return the minimum height the view will try to be. 17131 * 17132 * @see #setMinimumHeight(int) 17133 * 17134 * @attr ref android.R.styleable#View_minHeight 17135 */ 17136 public int getMinimumHeight() { 17137 return mMinHeight; 17138 } 17139 17140 /** 17141 * Sets the minimum height of the view. It is not guaranteed the view will 17142 * be able to achieve this minimum height (for example, if its parent layout 17143 * constrains it with less available height). 17144 * 17145 * @param minHeight The minimum height the view will try to be. 17146 * 17147 * @see #getMinimumHeight() 17148 * 17149 * @attr ref android.R.styleable#View_minHeight 17150 */ 17151 public void setMinimumHeight(int minHeight) { 17152 mMinHeight = minHeight; 17153 requestLayout(); 17154 } 17155 17156 /** 17157 * Returns the minimum width of the view. 17158 * 17159 * @return the minimum width the view will try to be. 17160 * 17161 * @see #setMinimumWidth(int) 17162 * 17163 * @attr ref android.R.styleable#View_minWidth 17164 */ 17165 public int getMinimumWidth() { 17166 return mMinWidth; 17167 } 17168 17169 /** 17170 * Sets the minimum width of the view. It is not guaranteed the view will 17171 * be able to achieve this minimum width (for example, if its parent layout 17172 * constrains it with less available width). 17173 * 17174 * @param minWidth The minimum width the view will try to be. 17175 * 17176 * @see #getMinimumWidth() 17177 * 17178 * @attr ref android.R.styleable#View_minWidth 17179 */ 17180 public void setMinimumWidth(int minWidth) { 17181 mMinWidth = minWidth; 17182 requestLayout(); 17183 17184 } 17185 17186 /** 17187 * Get the animation currently associated with this view. 17188 * 17189 * @return The animation that is currently playing or 17190 * scheduled to play for this view. 17191 */ 17192 public Animation getAnimation() { 17193 return mCurrentAnimation; 17194 } 17195 17196 /** 17197 * Start the specified animation now. 17198 * 17199 * @param animation the animation to start now 17200 */ 17201 public void startAnimation(Animation animation) { 17202 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17203 setAnimation(animation); 17204 invalidateParentCaches(); 17205 invalidate(true); 17206 } 17207 17208 /** 17209 * Cancels any animations for this view. 17210 */ 17211 public void clearAnimation() { 17212 if (mCurrentAnimation != null) { 17213 mCurrentAnimation.detach(); 17214 } 17215 mCurrentAnimation = null; 17216 invalidateParentIfNeeded(); 17217 } 17218 17219 /** 17220 * Sets the next animation to play for this view. 17221 * If you want the animation to play immediately, use 17222 * {@link #startAnimation(android.view.animation.Animation)} instead. 17223 * This method provides allows fine-grained 17224 * control over the start time and invalidation, but you 17225 * must make sure that 1) the animation has a start time set, and 17226 * 2) the view's parent (which controls animations on its children) 17227 * will be invalidated when the animation is supposed to 17228 * start. 17229 * 17230 * @param animation The next animation, or null. 17231 */ 17232 public void setAnimation(Animation animation) { 17233 mCurrentAnimation = animation; 17234 17235 if (animation != null) { 17236 // If the screen is off assume the animation start time is now instead of 17237 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17238 // would cause the animation to start when the screen turns back on 17239 if (mAttachInfo != null && !mAttachInfo.mScreenOn && 17240 animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17241 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17242 } 17243 animation.reset(); 17244 } 17245 } 17246 17247 /** 17248 * Invoked by a parent ViewGroup to notify the start of the animation 17249 * currently associated with this view. If you override this method, 17250 * always call super.onAnimationStart(); 17251 * 17252 * @see #setAnimation(android.view.animation.Animation) 17253 * @see #getAnimation() 17254 */ 17255 protected void onAnimationStart() { 17256 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17257 } 17258 17259 /** 17260 * Invoked by a parent ViewGroup to notify the end of the animation 17261 * currently associated with this view. If you override this method, 17262 * always call super.onAnimationEnd(); 17263 * 17264 * @see #setAnimation(android.view.animation.Animation) 17265 * @see #getAnimation() 17266 */ 17267 protected void onAnimationEnd() { 17268 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17269 } 17270 17271 /** 17272 * Invoked if there is a Transform that involves alpha. Subclass that can 17273 * draw themselves with the specified alpha should return true, and then 17274 * respect that alpha when their onDraw() is called. If this returns false 17275 * then the view may be redirected to draw into an offscreen buffer to 17276 * fulfill the request, which will look fine, but may be slower than if the 17277 * subclass handles it internally. The default implementation returns false. 17278 * 17279 * @param alpha The alpha (0..255) to apply to the view's drawing 17280 * @return true if the view can draw with the specified alpha. 17281 */ 17282 protected boolean onSetAlpha(int alpha) { 17283 return false; 17284 } 17285 17286 /** 17287 * This is used by the RootView to perform an optimization when 17288 * the view hierarchy contains one or several SurfaceView. 17289 * SurfaceView is always considered transparent, but its children are not, 17290 * therefore all View objects remove themselves from the global transparent 17291 * region (passed as a parameter to this function). 17292 * 17293 * @param region The transparent region for this ViewAncestor (window). 17294 * 17295 * @return Returns true if the effective visibility of the view at this 17296 * point is opaque, regardless of the transparent region; returns false 17297 * if it is possible for underlying windows to be seen behind the view. 17298 * 17299 * {@hide} 17300 */ 17301 public boolean gatherTransparentRegion(Region region) { 17302 final AttachInfo attachInfo = mAttachInfo; 17303 if (region != null && attachInfo != null) { 17304 final int pflags = mPrivateFlags; 17305 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17306 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17307 // remove it from the transparent region. 17308 final int[] location = attachInfo.mTransparentLocation; 17309 getLocationInWindow(location); 17310 region.op(location[0], location[1], location[0] + mRight - mLeft, 17311 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17312 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17313 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17314 // exists, so we remove the background drawable's non-transparent 17315 // parts from this transparent region. 17316 applyDrawableToTransparentRegion(mBackground, region); 17317 } 17318 } 17319 return true; 17320 } 17321 17322 /** 17323 * Play a sound effect for this view. 17324 * 17325 * <p>The framework will play sound effects for some built in actions, such as 17326 * clicking, but you may wish to play these effects in your widget, 17327 * for instance, for internal navigation. 17328 * 17329 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17330 * {@link #isSoundEffectsEnabled()} is true. 17331 * 17332 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17333 */ 17334 public void playSoundEffect(int soundConstant) { 17335 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17336 return; 17337 } 17338 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17339 } 17340 17341 /** 17342 * BZZZTT!!1! 17343 * 17344 * <p>Provide haptic feedback to the user for this view. 17345 * 17346 * <p>The framework will provide haptic feedback for some built in actions, 17347 * such as long presses, but you may wish to provide feedback for your 17348 * own widget. 17349 * 17350 * <p>The feedback will only be performed if 17351 * {@link #isHapticFeedbackEnabled()} is true. 17352 * 17353 * @param feedbackConstant One of the constants defined in 17354 * {@link HapticFeedbackConstants} 17355 */ 17356 public boolean performHapticFeedback(int feedbackConstant) { 17357 return performHapticFeedback(feedbackConstant, 0); 17358 } 17359 17360 /** 17361 * BZZZTT!!1! 17362 * 17363 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17364 * 17365 * @param feedbackConstant One of the constants defined in 17366 * {@link HapticFeedbackConstants} 17367 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17368 */ 17369 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17370 if (mAttachInfo == null) { 17371 return false; 17372 } 17373 //noinspection SimplifiableIfStatement 17374 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17375 && !isHapticFeedbackEnabled()) { 17376 return false; 17377 } 17378 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17379 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17380 } 17381 17382 /** 17383 * Request that the visibility of the status bar or other screen/window 17384 * decorations be changed. 17385 * 17386 * <p>This method is used to put the over device UI into temporary modes 17387 * where the user's attention is focused more on the application content, 17388 * by dimming or hiding surrounding system affordances. This is typically 17389 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17390 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17391 * to be placed behind the action bar (and with these flags other system 17392 * affordances) so that smooth transitions between hiding and showing them 17393 * can be done. 17394 * 17395 * <p>Two representative examples of the use of system UI visibility is 17396 * implementing a content browsing application (like a magazine reader) 17397 * and a video playing application. 17398 * 17399 * <p>The first code shows a typical implementation of a View in a content 17400 * browsing application. In this implementation, the application goes 17401 * into a content-oriented mode by hiding the status bar and action bar, 17402 * and putting the navigation elements into lights out mode. The user can 17403 * then interact with content while in this mode. Such an application should 17404 * provide an easy way for the user to toggle out of the mode (such as to 17405 * check information in the status bar or access notifications). In the 17406 * implementation here, this is done simply by tapping on the content. 17407 * 17408 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17409 * content} 17410 * 17411 * <p>This second code sample shows a typical implementation of a View 17412 * in a video playing application. In this situation, while the video is 17413 * playing the application would like to go into a complete full-screen mode, 17414 * to use as much of the display as possible for the video. When in this state 17415 * the user can not interact with the application; the system intercepts 17416 * touching on the screen to pop the UI out of full screen mode. See 17417 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17418 * 17419 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17420 * content} 17421 * 17422 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17423 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17424 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17425 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17426 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17427 */ 17428 public void setSystemUiVisibility(int visibility) { 17429 if (visibility != mSystemUiVisibility) { 17430 mSystemUiVisibility = visibility; 17431 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17432 mParent.recomputeViewAttributes(this); 17433 } 17434 } 17435 } 17436 17437 /** 17438 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17439 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17440 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17441 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17442 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17443 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17444 */ 17445 public int getSystemUiVisibility() { 17446 return mSystemUiVisibility; 17447 } 17448 17449 /** 17450 * Returns the current system UI visibility that is currently set for 17451 * the entire window. This is the combination of the 17452 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17453 * views in the window. 17454 */ 17455 public int getWindowSystemUiVisibility() { 17456 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17457 } 17458 17459 /** 17460 * Override to find out when the window's requested system UI visibility 17461 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17462 * This is different from the callbacks received through 17463 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17464 * in that this is only telling you about the local request of the window, 17465 * not the actual values applied by the system. 17466 */ 17467 public void onWindowSystemUiVisibilityChanged(int visible) { 17468 } 17469 17470 /** 17471 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17472 * the view hierarchy. 17473 */ 17474 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17475 onWindowSystemUiVisibilityChanged(visible); 17476 } 17477 17478 /** 17479 * Set a listener to receive callbacks when the visibility of the system bar changes. 17480 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17481 */ 17482 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17483 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17484 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17485 mParent.recomputeViewAttributes(this); 17486 } 17487 } 17488 17489 /** 17490 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17491 * the view hierarchy. 17492 */ 17493 public void dispatchSystemUiVisibilityChanged(int visibility) { 17494 ListenerInfo li = mListenerInfo; 17495 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17496 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17497 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17498 } 17499 } 17500 17501 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17502 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17503 if (val != mSystemUiVisibility) { 17504 setSystemUiVisibility(val); 17505 return true; 17506 } 17507 return false; 17508 } 17509 17510 /** @hide */ 17511 public void setDisabledSystemUiVisibility(int flags) { 17512 if (mAttachInfo != null) { 17513 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17514 mAttachInfo.mDisabledSystemUiVisibility = flags; 17515 if (mParent != null) { 17516 mParent.recomputeViewAttributes(this); 17517 } 17518 } 17519 } 17520 } 17521 17522 /** 17523 * Creates an image that the system displays during the drag and drop 17524 * operation. This is called a "drag shadow". The default implementation 17525 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17526 * appearance as the given View. The default also positions the center of the drag shadow 17527 * directly under the touch point. If no View is provided (the constructor with no parameters 17528 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17529 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17530 * default is an invisible drag shadow. 17531 * <p> 17532 * You are not required to use the View you provide to the constructor as the basis of the 17533 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17534 * anything you want as the drag shadow. 17535 * </p> 17536 * <p> 17537 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17538 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17539 * size and position of the drag shadow. It uses this data to construct a 17540 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17541 * so that your application can draw the shadow image in the Canvas. 17542 * </p> 17543 * 17544 * <div class="special reference"> 17545 * <h3>Developer Guides</h3> 17546 * <p>For a guide to implementing drag and drop features, read the 17547 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17548 * </div> 17549 */ 17550 public static class DragShadowBuilder { 17551 private final WeakReference<View> mView; 17552 17553 /** 17554 * Constructs a shadow image builder based on a View. By default, the resulting drag 17555 * shadow will have the same appearance and dimensions as the View, with the touch point 17556 * over the center of the View. 17557 * @param view A View. Any View in scope can be used. 17558 */ 17559 public DragShadowBuilder(View view) { 17560 mView = new WeakReference<View>(view); 17561 } 17562 17563 /** 17564 * Construct a shadow builder object with no associated View. This 17565 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17566 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17567 * to supply the drag shadow's dimensions and appearance without 17568 * reference to any View object. If they are not overridden, then the result is an 17569 * invisible drag shadow. 17570 */ 17571 public DragShadowBuilder() { 17572 mView = new WeakReference<View>(null); 17573 } 17574 17575 /** 17576 * Returns the View object that had been passed to the 17577 * {@link #View.DragShadowBuilder(View)} 17578 * constructor. If that View parameter was {@code null} or if the 17579 * {@link #View.DragShadowBuilder()} 17580 * constructor was used to instantiate the builder object, this method will return 17581 * null. 17582 * 17583 * @return The View object associate with this builder object. 17584 */ 17585 @SuppressWarnings({"JavadocReference"}) 17586 final public View getView() { 17587 return mView.get(); 17588 } 17589 17590 /** 17591 * Provides the metrics for the shadow image. These include the dimensions of 17592 * the shadow image, and the point within that shadow that should 17593 * be centered under the touch location while dragging. 17594 * <p> 17595 * The default implementation sets the dimensions of the shadow to be the 17596 * same as the dimensions of the View itself and centers the shadow under 17597 * the touch point. 17598 * </p> 17599 * 17600 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17601 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17602 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17603 * image. 17604 * 17605 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17606 * shadow image that should be underneath the touch point during the drag and drop 17607 * operation. Your application must set {@link android.graphics.Point#x} to the 17608 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17609 */ 17610 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17611 final View view = mView.get(); 17612 if (view != null) { 17613 shadowSize.set(view.getWidth(), view.getHeight()); 17614 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17615 } else { 17616 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17617 } 17618 } 17619 17620 /** 17621 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17622 * based on the dimensions it received from the 17623 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17624 * 17625 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17626 */ 17627 public void onDrawShadow(Canvas canvas) { 17628 final View view = mView.get(); 17629 if (view != null) { 17630 view.draw(canvas); 17631 } else { 17632 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17633 } 17634 } 17635 } 17636 17637 /** 17638 * Starts a drag and drop operation. When your application calls this method, it passes a 17639 * {@link android.view.View.DragShadowBuilder} object to the system. The 17640 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17641 * to get metrics for the drag shadow, and then calls the object's 17642 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17643 * <p> 17644 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17645 * drag events to all the View objects in your application that are currently visible. It does 17646 * this either by calling the View object's drag listener (an implementation of 17647 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17648 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17649 * Both are passed a {@link android.view.DragEvent} object that has a 17650 * {@link android.view.DragEvent#getAction()} value of 17651 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17652 * </p> 17653 * <p> 17654 * Your application can invoke startDrag() on any attached View object. The View object does not 17655 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17656 * be related to the View the user selected for dragging. 17657 * </p> 17658 * @param data A {@link android.content.ClipData} object pointing to the data to be 17659 * transferred by the drag and drop operation. 17660 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17661 * drag shadow. 17662 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17663 * drop operation. This Object is put into every DragEvent object sent by the system during the 17664 * current drag. 17665 * <p> 17666 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17667 * to the target Views. For example, it can contain flags that differentiate between a 17668 * a copy operation and a move operation. 17669 * </p> 17670 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17671 * so the parameter should be set to 0. 17672 * @return {@code true} if the method completes successfully, or 17673 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17674 * do a drag, and so no drag operation is in progress. 17675 */ 17676 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17677 Object myLocalState, int flags) { 17678 if (ViewDebug.DEBUG_DRAG) { 17679 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17680 } 17681 boolean okay = false; 17682 17683 Point shadowSize = new Point(); 17684 Point shadowTouchPoint = new Point(); 17685 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17686 17687 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17688 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17689 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17690 } 17691 17692 if (ViewDebug.DEBUG_DRAG) { 17693 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17694 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17695 } 17696 Surface surface = new Surface(); 17697 try { 17698 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17699 flags, shadowSize.x, shadowSize.y, surface); 17700 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17701 + " surface=" + surface); 17702 if (token != null) { 17703 Canvas canvas = surface.lockCanvas(null); 17704 try { 17705 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17706 shadowBuilder.onDrawShadow(canvas); 17707 } finally { 17708 surface.unlockCanvasAndPost(canvas); 17709 } 17710 17711 final ViewRootImpl root = getViewRootImpl(); 17712 17713 // Cache the local state object for delivery with DragEvents 17714 root.setLocalDragState(myLocalState); 17715 17716 // repurpose 'shadowSize' for the last touch point 17717 root.getLastTouchPoint(shadowSize); 17718 17719 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17720 shadowSize.x, shadowSize.y, 17721 shadowTouchPoint.x, shadowTouchPoint.y, data); 17722 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17723 17724 // Off and running! Release our local surface instance; the drag 17725 // shadow surface is now managed by the system process. 17726 surface.release(); 17727 } 17728 } catch (Exception e) { 17729 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17730 surface.destroy(); 17731 } 17732 17733 return okay; 17734 } 17735 17736 /** 17737 * Handles drag events sent by the system following a call to 17738 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17739 *<p> 17740 * When the system calls this method, it passes a 17741 * {@link android.view.DragEvent} object. A call to 17742 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17743 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17744 * operation. 17745 * @param event The {@link android.view.DragEvent} sent by the system. 17746 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17747 * in DragEvent, indicating the type of drag event represented by this object. 17748 * @return {@code true} if the method was successful, otherwise {@code false}. 17749 * <p> 17750 * The method should return {@code true} in response to an action type of 17751 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17752 * operation. 17753 * </p> 17754 * <p> 17755 * The method should also return {@code true} in response to an action type of 17756 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17757 * {@code false} if it didn't. 17758 * </p> 17759 */ 17760 public boolean onDragEvent(DragEvent event) { 17761 return false; 17762 } 17763 17764 /** 17765 * Detects if this View is enabled and has a drag event listener. 17766 * If both are true, then it calls the drag event listener with the 17767 * {@link android.view.DragEvent} it received. If the drag event listener returns 17768 * {@code true}, then dispatchDragEvent() returns {@code true}. 17769 * <p> 17770 * For all other cases, the method calls the 17771 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17772 * method and returns its result. 17773 * </p> 17774 * <p> 17775 * This ensures that a drag event is always consumed, even if the View does not have a drag 17776 * event listener. However, if the View has a listener and the listener returns true, then 17777 * onDragEvent() is not called. 17778 * </p> 17779 */ 17780 public boolean dispatchDragEvent(DragEvent event) { 17781 ListenerInfo li = mListenerInfo; 17782 //noinspection SimplifiableIfStatement 17783 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17784 && li.mOnDragListener.onDrag(this, event)) { 17785 return true; 17786 } 17787 return onDragEvent(event); 17788 } 17789 17790 boolean canAcceptDrag() { 17791 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17792 } 17793 17794 /** 17795 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17796 * it is ever exposed at all. 17797 * @hide 17798 */ 17799 public void onCloseSystemDialogs(String reason) { 17800 } 17801 17802 /** 17803 * Given a Drawable whose bounds have been set to draw into this view, 17804 * update a Region being computed for 17805 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17806 * that any non-transparent parts of the Drawable are removed from the 17807 * given transparent region. 17808 * 17809 * @param dr The Drawable whose transparency is to be applied to the region. 17810 * @param region A Region holding the current transparency information, 17811 * where any parts of the region that are set are considered to be 17812 * transparent. On return, this region will be modified to have the 17813 * transparency information reduced by the corresponding parts of the 17814 * Drawable that are not transparent. 17815 * {@hide} 17816 */ 17817 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17818 if (DBG) { 17819 Log.i("View", "Getting transparent region for: " + this); 17820 } 17821 final Region r = dr.getTransparentRegion(); 17822 final Rect db = dr.getBounds(); 17823 final AttachInfo attachInfo = mAttachInfo; 17824 if (r != null && attachInfo != null) { 17825 final int w = getRight()-getLeft(); 17826 final int h = getBottom()-getTop(); 17827 if (db.left > 0) { 17828 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17829 r.op(0, 0, db.left, h, Region.Op.UNION); 17830 } 17831 if (db.right < w) { 17832 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17833 r.op(db.right, 0, w, h, Region.Op.UNION); 17834 } 17835 if (db.top > 0) { 17836 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17837 r.op(0, 0, w, db.top, Region.Op.UNION); 17838 } 17839 if (db.bottom < h) { 17840 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17841 r.op(0, db.bottom, w, h, Region.Op.UNION); 17842 } 17843 final int[] location = attachInfo.mTransparentLocation; 17844 getLocationInWindow(location); 17845 r.translate(location[0], location[1]); 17846 region.op(r, Region.Op.INTERSECT); 17847 } else { 17848 region.op(db, Region.Op.DIFFERENCE); 17849 } 17850 } 17851 17852 private void checkForLongClick(int delayOffset) { 17853 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17854 mHasPerformedLongPress = false; 17855 17856 if (mPendingCheckForLongPress == null) { 17857 mPendingCheckForLongPress = new CheckForLongPress(); 17858 } 17859 mPendingCheckForLongPress.rememberWindowAttachCount(); 17860 postDelayed(mPendingCheckForLongPress, 17861 ViewConfiguration.getLongPressTimeout() - delayOffset); 17862 } 17863 } 17864 17865 /** 17866 * Inflate a view from an XML resource. This convenience method wraps the {@link 17867 * LayoutInflater} class, which provides a full range of options for view inflation. 17868 * 17869 * @param context The Context object for your activity or application. 17870 * @param resource The resource ID to inflate 17871 * @param root A view group that will be the parent. Used to properly inflate the 17872 * layout_* parameters. 17873 * @see LayoutInflater 17874 */ 17875 public static View inflate(Context context, int resource, ViewGroup root) { 17876 LayoutInflater factory = LayoutInflater.from(context); 17877 return factory.inflate(resource, root); 17878 } 17879 17880 /** 17881 * Scroll the view with standard behavior for scrolling beyond the normal 17882 * content boundaries. Views that call this method should override 17883 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17884 * results of an over-scroll operation. 17885 * 17886 * Views can use this method to handle any touch or fling-based scrolling. 17887 * 17888 * @param deltaX Change in X in pixels 17889 * @param deltaY Change in Y in pixels 17890 * @param scrollX Current X scroll value in pixels before applying deltaX 17891 * @param scrollY Current Y scroll value in pixels before applying deltaY 17892 * @param scrollRangeX Maximum content scroll range along the X axis 17893 * @param scrollRangeY Maximum content scroll range along the Y axis 17894 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17895 * along the X axis. 17896 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17897 * along the Y axis. 17898 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17899 * @return true if scrolling was clamped to an over-scroll boundary along either 17900 * axis, false otherwise. 17901 */ 17902 @SuppressWarnings({"UnusedParameters"}) 17903 protected boolean overScrollBy(int deltaX, int deltaY, 17904 int scrollX, int scrollY, 17905 int scrollRangeX, int scrollRangeY, 17906 int maxOverScrollX, int maxOverScrollY, 17907 boolean isTouchEvent) { 17908 final int overScrollMode = mOverScrollMode; 17909 final boolean canScrollHorizontal = 17910 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17911 final boolean canScrollVertical = 17912 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17913 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17914 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17915 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17916 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17917 17918 int newScrollX = scrollX + deltaX; 17919 if (!overScrollHorizontal) { 17920 maxOverScrollX = 0; 17921 } 17922 17923 int newScrollY = scrollY + deltaY; 17924 if (!overScrollVertical) { 17925 maxOverScrollY = 0; 17926 } 17927 17928 // Clamp values if at the limits and record 17929 final int left = -maxOverScrollX; 17930 final int right = maxOverScrollX + scrollRangeX; 17931 final int top = -maxOverScrollY; 17932 final int bottom = maxOverScrollY + scrollRangeY; 17933 17934 boolean clampedX = false; 17935 if (newScrollX > right) { 17936 newScrollX = right; 17937 clampedX = true; 17938 } else if (newScrollX < left) { 17939 newScrollX = left; 17940 clampedX = true; 17941 } 17942 17943 boolean clampedY = false; 17944 if (newScrollY > bottom) { 17945 newScrollY = bottom; 17946 clampedY = true; 17947 } else if (newScrollY < top) { 17948 newScrollY = top; 17949 clampedY = true; 17950 } 17951 17952 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17953 17954 return clampedX || clampedY; 17955 } 17956 17957 /** 17958 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17959 * respond to the results of an over-scroll operation. 17960 * 17961 * @param scrollX New X scroll value in pixels 17962 * @param scrollY New Y scroll value in pixels 17963 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17964 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17965 */ 17966 protected void onOverScrolled(int scrollX, int scrollY, 17967 boolean clampedX, boolean clampedY) { 17968 // Intentionally empty. 17969 } 17970 17971 /** 17972 * Returns the over-scroll mode for this view. The result will be 17973 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17974 * (allow over-scrolling only if the view content is larger than the container), 17975 * or {@link #OVER_SCROLL_NEVER}. 17976 * 17977 * @return This view's over-scroll mode. 17978 */ 17979 public int getOverScrollMode() { 17980 return mOverScrollMode; 17981 } 17982 17983 /** 17984 * Set the over-scroll mode for this view. Valid over-scroll modes are 17985 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17986 * (allow over-scrolling only if the view content is larger than the container), 17987 * or {@link #OVER_SCROLL_NEVER}. 17988 * 17989 * Setting the over-scroll mode of a view will have an effect only if the 17990 * view is capable of scrolling. 17991 * 17992 * @param overScrollMode The new over-scroll mode for this view. 17993 */ 17994 public void setOverScrollMode(int overScrollMode) { 17995 if (overScrollMode != OVER_SCROLL_ALWAYS && 17996 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17997 overScrollMode != OVER_SCROLL_NEVER) { 17998 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17999 } 18000 mOverScrollMode = overScrollMode; 18001 } 18002 18003 /** 18004 * Gets a scale factor that determines the distance the view should scroll 18005 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18006 * @return The vertical scroll scale factor. 18007 * @hide 18008 */ 18009 protected float getVerticalScrollFactor() { 18010 if (mVerticalScrollFactor == 0) { 18011 TypedValue outValue = new TypedValue(); 18012 if (!mContext.getTheme().resolveAttribute( 18013 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18014 throw new IllegalStateException( 18015 "Expected theme to define listPreferredItemHeight."); 18016 } 18017 mVerticalScrollFactor = outValue.getDimension( 18018 mContext.getResources().getDisplayMetrics()); 18019 } 18020 return mVerticalScrollFactor; 18021 } 18022 18023 /** 18024 * Gets a scale factor that determines the distance the view should scroll 18025 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18026 * @return The horizontal scroll scale factor. 18027 * @hide 18028 */ 18029 protected float getHorizontalScrollFactor() { 18030 // TODO: Should use something else. 18031 return getVerticalScrollFactor(); 18032 } 18033 18034 /** 18035 * Return the value specifying the text direction or policy that was set with 18036 * {@link #setTextDirection(int)}. 18037 * 18038 * @return the defined text direction. It can be one of: 18039 * 18040 * {@link #TEXT_DIRECTION_INHERIT}, 18041 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18042 * {@link #TEXT_DIRECTION_ANY_RTL}, 18043 * {@link #TEXT_DIRECTION_LTR}, 18044 * {@link #TEXT_DIRECTION_RTL}, 18045 * {@link #TEXT_DIRECTION_LOCALE} 18046 * 18047 * @attr ref android.R.styleable#View_textDirection 18048 * 18049 * @hide 18050 */ 18051 @ViewDebug.ExportedProperty(category = "text", mapping = { 18052 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18053 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18054 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18055 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18056 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18057 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18058 }) 18059 public int getRawTextDirection() { 18060 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18061 } 18062 18063 /** 18064 * Set the text direction. 18065 * 18066 * @param textDirection the direction to set. Should be one of: 18067 * 18068 * {@link #TEXT_DIRECTION_INHERIT}, 18069 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18070 * {@link #TEXT_DIRECTION_ANY_RTL}, 18071 * {@link #TEXT_DIRECTION_LTR}, 18072 * {@link #TEXT_DIRECTION_RTL}, 18073 * {@link #TEXT_DIRECTION_LOCALE} 18074 * 18075 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18076 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18077 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18078 * 18079 * @attr ref android.R.styleable#View_textDirection 18080 */ 18081 public void setTextDirection(int textDirection) { 18082 if (getRawTextDirection() != textDirection) { 18083 // Reset the current text direction and the resolved one 18084 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18085 resetResolvedTextDirection(); 18086 // Set the new text direction 18087 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18088 // Do resolution 18089 resolveTextDirection(); 18090 // Notify change 18091 onRtlPropertiesChanged(getLayoutDirection()); 18092 // Refresh 18093 requestLayout(); 18094 invalidate(true); 18095 } 18096 } 18097 18098 /** 18099 * Return the resolved text direction. 18100 * 18101 * @return the resolved text direction. Returns one of: 18102 * 18103 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18104 * {@link #TEXT_DIRECTION_ANY_RTL}, 18105 * {@link #TEXT_DIRECTION_LTR}, 18106 * {@link #TEXT_DIRECTION_RTL}, 18107 * {@link #TEXT_DIRECTION_LOCALE} 18108 * 18109 * @attr ref android.R.styleable#View_textDirection 18110 */ 18111 @ViewDebug.ExportedProperty(category = "text", mapping = { 18112 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18113 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18114 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18115 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18116 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18117 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18118 }) 18119 public int getTextDirection() { 18120 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18121 } 18122 18123 /** 18124 * Resolve the text direction. 18125 * 18126 * @return true if resolution has been done, false otherwise. 18127 * 18128 * @hide 18129 */ 18130 public boolean resolveTextDirection() { 18131 // Reset any previous text direction resolution 18132 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18133 18134 if (hasRtlSupport()) { 18135 // Set resolved text direction flag depending on text direction flag 18136 final int textDirection = getRawTextDirection(); 18137 switch(textDirection) { 18138 case TEXT_DIRECTION_INHERIT: 18139 if (!canResolveTextDirection()) { 18140 // We cannot do the resolution if there is no parent, so use the default one 18141 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18142 // Resolution will need to happen again later 18143 return false; 18144 } 18145 18146 // Parent has not yet resolved, so we still return the default 18147 try { 18148 if (!mParent.isTextDirectionResolved()) { 18149 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18150 // Resolution will need to happen again later 18151 return false; 18152 } 18153 } catch (AbstractMethodError e) { 18154 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18155 " does not fully implement ViewParent", e); 18156 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18157 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18158 return true; 18159 } 18160 18161 // Set current resolved direction to the same value as the parent's one 18162 int parentResolvedDirection; 18163 try { 18164 parentResolvedDirection = mParent.getTextDirection(); 18165 } catch (AbstractMethodError e) { 18166 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18167 " does not fully implement ViewParent", e); 18168 parentResolvedDirection = TEXT_DIRECTION_LTR; 18169 } 18170 switch (parentResolvedDirection) { 18171 case TEXT_DIRECTION_FIRST_STRONG: 18172 case TEXT_DIRECTION_ANY_RTL: 18173 case TEXT_DIRECTION_LTR: 18174 case TEXT_DIRECTION_RTL: 18175 case TEXT_DIRECTION_LOCALE: 18176 mPrivateFlags2 |= 18177 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18178 break; 18179 default: 18180 // Default resolved direction is "first strong" heuristic 18181 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18182 } 18183 break; 18184 case TEXT_DIRECTION_FIRST_STRONG: 18185 case TEXT_DIRECTION_ANY_RTL: 18186 case TEXT_DIRECTION_LTR: 18187 case TEXT_DIRECTION_RTL: 18188 case TEXT_DIRECTION_LOCALE: 18189 // Resolved direction is the same as text direction 18190 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18191 break; 18192 default: 18193 // Default resolved direction is "first strong" heuristic 18194 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18195 } 18196 } else { 18197 // Default resolved direction is "first strong" heuristic 18198 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18199 } 18200 18201 // Set to resolved 18202 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18203 return true; 18204 } 18205 18206 /** 18207 * Check if text direction resolution can be done. 18208 * 18209 * @return true if text direction resolution can be done otherwise return false. 18210 */ 18211 public boolean canResolveTextDirection() { 18212 switch (getRawTextDirection()) { 18213 case TEXT_DIRECTION_INHERIT: 18214 if (mParent != null) { 18215 try { 18216 return mParent.canResolveTextDirection(); 18217 } catch (AbstractMethodError e) { 18218 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18219 " does not fully implement ViewParent", e); 18220 } 18221 } 18222 return false; 18223 18224 default: 18225 return true; 18226 } 18227 } 18228 18229 /** 18230 * Reset resolved text direction. Text direction will be resolved during a call to 18231 * {@link #onMeasure(int, int)}. 18232 * 18233 * @hide 18234 */ 18235 public void resetResolvedTextDirection() { 18236 // Reset any previous text direction resolution 18237 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18238 // Set to default value 18239 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18240 } 18241 18242 /** 18243 * @return true if text direction is inherited. 18244 * 18245 * @hide 18246 */ 18247 public boolean isTextDirectionInherited() { 18248 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18249 } 18250 18251 /** 18252 * @return true if text direction is resolved. 18253 */ 18254 public boolean isTextDirectionResolved() { 18255 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18256 } 18257 18258 /** 18259 * Return the value specifying the text alignment or policy that was set with 18260 * {@link #setTextAlignment(int)}. 18261 * 18262 * @return the defined text alignment. It can be one of: 18263 * 18264 * {@link #TEXT_ALIGNMENT_INHERIT}, 18265 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18266 * {@link #TEXT_ALIGNMENT_CENTER}, 18267 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18268 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18269 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18270 * {@link #TEXT_ALIGNMENT_VIEW_END} 18271 * 18272 * @attr ref android.R.styleable#View_textAlignment 18273 * 18274 * @hide 18275 */ 18276 @ViewDebug.ExportedProperty(category = "text", mapping = { 18277 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18278 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18279 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18280 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18281 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18282 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18283 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18284 }) 18285 @TextAlignment 18286 public int getRawTextAlignment() { 18287 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18288 } 18289 18290 /** 18291 * Set the text alignment. 18292 * 18293 * @param textAlignment The text alignment to set. Should be one of 18294 * 18295 * {@link #TEXT_ALIGNMENT_INHERIT}, 18296 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18297 * {@link #TEXT_ALIGNMENT_CENTER}, 18298 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18299 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18300 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18301 * {@link #TEXT_ALIGNMENT_VIEW_END} 18302 * 18303 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18304 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18305 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18306 * 18307 * @attr ref android.R.styleable#View_textAlignment 18308 */ 18309 public void setTextAlignment(@TextAlignment int textAlignment) { 18310 if (textAlignment != getRawTextAlignment()) { 18311 // Reset the current and resolved text alignment 18312 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18313 resetResolvedTextAlignment(); 18314 // Set the new text alignment 18315 mPrivateFlags2 |= 18316 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18317 // Do resolution 18318 resolveTextAlignment(); 18319 // Notify change 18320 onRtlPropertiesChanged(getLayoutDirection()); 18321 // Refresh 18322 requestLayout(); 18323 invalidate(true); 18324 } 18325 } 18326 18327 /** 18328 * Return the resolved text alignment. 18329 * 18330 * @return the resolved text alignment. Returns one of: 18331 * 18332 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18333 * {@link #TEXT_ALIGNMENT_CENTER}, 18334 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18335 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18336 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18337 * {@link #TEXT_ALIGNMENT_VIEW_END} 18338 * 18339 * @attr ref android.R.styleable#View_textAlignment 18340 */ 18341 @ViewDebug.ExportedProperty(category = "text", mapping = { 18342 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18343 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18344 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18345 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18346 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18347 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18348 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18349 }) 18350 @TextAlignment 18351 public int getTextAlignment() { 18352 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18353 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18354 } 18355 18356 /** 18357 * Resolve the text alignment. 18358 * 18359 * @return true if resolution has been done, false otherwise. 18360 * 18361 * @hide 18362 */ 18363 public boolean resolveTextAlignment() { 18364 // Reset any previous text alignment resolution 18365 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18366 18367 if (hasRtlSupport()) { 18368 // Set resolved text alignment flag depending on text alignment flag 18369 final int textAlignment = getRawTextAlignment(); 18370 switch (textAlignment) { 18371 case TEXT_ALIGNMENT_INHERIT: 18372 // Check if we can resolve the text alignment 18373 if (!canResolveTextAlignment()) { 18374 // We cannot do the resolution if there is no parent so use the default 18375 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18376 // Resolution will need to happen again later 18377 return false; 18378 } 18379 18380 // Parent has not yet resolved, so we still return the default 18381 try { 18382 if (!mParent.isTextAlignmentResolved()) { 18383 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18384 // Resolution will need to happen again later 18385 return false; 18386 } 18387 } catch (AbstractMethodError e) { 18388 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18389 " does not fully implement ViewParent", e); 18390 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18391 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18392 return true; 18393 } 18394 18395 int parentResolvedTextAlignment; 18396 try { 18397 parentResolvedTextAlignment = mParent.getTextAlignment(); 18398 } catch (AbstractMethodError e) { 18399 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18400 " does not fully implement ViewParent", e); 18401 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18402 } 18403 switch (parentResolvedTextAlignment) { 18404 case TEXT_ALIGNMENT_GRAVITY: 18405 case TEXT_ALIGNMENT_TEXT_START: 18406 case TEXT_ALIGNMENT_TEXT_END: 18407 case TEXT_ALIGNMENT_CENTER: 18408 case TEXT_ALIGNMENT_VIEW_START: 18409 case TEXT_ALIGNMENT_VIEW_END: 18410 // Resolved text alignment is the same as the parent resolved 18411 // text alignment 18412 mPrivateFlags2 |= 18413 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18414 break; 18415 default: 18416 // Use default resolved text alignment 18417 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18418 } 18419 break; 18420 case TEXT_ALIGNMENT_GRAVITY: 18421 case TEXT_ALIGNMENT_TEXT_START: 18422 case TEXT_ALIGNMENT_TEXT_END: 18423 case TEXT_ALIGNMENT_CENTER: 18424 case TEXT_ALIGNMENT_VIEW_START: 18425 case TEXT_ALIGNMENT_VIEW_END: 18426 // Resolved text alignment is the same as text alignment 18427 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18428 break; 18429 default: 18430 // Use default resolved text alignment 18431 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18432 } 18433 } else { 18434 // Use default resolved text alignment 18435 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18436 } 18437 18438 // Set the resolved 18439 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18440 return true; 18441 } 18442 18443 /** 18444 * Check if text alignment resolution can be done. 18445 * 18446 * @return true if text alignment resolution can be done otherwise return false. 18447 */ 18448 public boolean canResolveTextAlignment() { 18449 switch (getRawTextAlignment()) { 18450 case TEXT_DIRECTION_INHERIT: 18451 if (mParent != null) { 18452 try { 18453 return mParent.canResolveTextAlignment(); 18454 } catch (AbstractMethodError e) { 18455 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18456 " does not fully implement ViewParent", e); 18457 } 18458 } 18459 return false; 18460 18461 default: 18462 return true; 18463 } 18464 } 18465 18466 /** 18467 * Reset resolved text alignment. Text alignment will be resolved during a call to 18468 * {@link #onMeasure(int, int)}. 18469 * 18470 * @hide 18471 */ 18472 public void resetResolvedTextAlignment() { 18473 // Reset any previous text alignment resolution 18474 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18475 // Set to default 18476 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18477 } 18478 18479 /** 18480 * @return true if text alignment is inherited. 18481 * 18482 * @hide 18483 */ 18484 public boolean isTextAlignmentInherited() { 18485 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18486 } 18487 18488 /** 18489 * @return true if text alignment is resolved. 18490 */ 18491 public boolean isTextAlignmentResolved() { 18492 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18493 } 18494 18495 /** 18496 * Generate a value suitable for use in {@link #setId(int)}. 18497 * This value will not collide with ID values generated at build time by aapt for R.id. 18498 * 18499 * @return a generated ID value 18500 */ 18501 public static int generateViewId() { 18502 for (;;) { 18503 final int result = sNextGeneratedId.get(); 18504 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18505 int newValue = result + 1; 18506 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18507 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18508 return result; 18509 } 18510 } 18511 } 18512 18513 // 18514 // Properties 18515 // 18516 /** 18517 * A Property wrapper around the <code>alpha</code> functionality handled by the 18518 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18519 */ 18520 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18521 @Override 18522 public void setValue(View object, float value) { 18523 object.setAlpha(value); 18524 } 18525 18526 @Override 18527 public Float get(View object) { 18528 return object.getAlpha(); 18529 } 18530 }; 18531 18532 /** 18533 * A Property wrapper around the <code>translationX</code> functionality handled by the 18534 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18535 */ 18536 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18537 @Override 18538 public void setValue(View object, float value) { 18539 object.setTranslationX(value); 18540 } 18541 18542 @Override 18543 public Float get(View object) { 18544 return object.getTranslationX(); 18545 } 18546 }; 18547 18548 /** 18549 * A Property wrapper around the <code>translationY</code> functionality handled by the 18550 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18551 */ 18552 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18553 @Override 18554 public void setValue(View object, float value) { 18555 object.setTranslationY(value); 18556 } 18557 18558 @Override 18559 public Float get(View object) { 18560 return object.getTranslationY(); 18561 } 18562 }; 18563 18564 /** 18565 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18566 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18567 */ 18568 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18569 @Override 18570 public void setValue(View object, float value) { 18571 object.setTranslationZ(value); 18572 } 18573 18574 @Override 18575 public Float get(View object) { 18576 return object.getTranslationZ(); 18577 } 18578 }; 18579 18580 /** 18581 * A Property wrapper around the <code>x</code> functionality handled by the 18582 * {@link View#setX(float)} and {@link View#getX()} methods. 18583 */ 18584 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18585 @Override 18586 public void setValue(View object, float value) { 18587 object.setX(value); 18588 } 18589 18590 @Override 18591 public Float get(View object) { 18592 return object.getX(); 18593 } 18594 }; 18595 18596 /** 18597 * A Property wrapper around the <code>y</code> functionality handled by the 18598 * {@link View#setY(float)} and {@link View#getY()} methods. 18599 */ 18600 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18601 @Override 18602 public void setValue(View object, float value) { 18603 object.setY(value); 18604 } 18605 18606 @Override 18607 public Float get(View object) { 18608 return object.getY(); 18609 } 18610 }; 18611 18612 /** 18613 * A Property wrapper around the <code>rotation</code> functionality handled by the 18614 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 18615 */ 18616 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 18617 @Override 18618 public void setValue(View object, float value) { 18619 object.setRotation(value); 18620 } 18621 18622 @Override 18623 public Float get(View object) { 18624 return object.getRotation(); 18625 } 18626 }; 18627 18628 /** 18629 * A Property wrapper around the <code>rotationX</code> functionality handled by the 18630 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 18631 */ 18632 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 18633 @Override 18634 public void setValue(View object, float value) { 18635 object.setRotationX(value); 18636 } 18637 18638 @Override 18639 public Float get(View object) { 18640 return object.getRotationX(); 18641 } 18642 }; 18643 18644 /** 18645 * A Property wrapper around the <code>rotationY</code> functionality handled by the 18646 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 18647 */ 18648 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 18649 @Override 18650 public void setValue(View object, float value) { 18651 object.setRotationY(value); 18652 } 18653 18654 @Override 18655 public Float get(View object) { 18656 return object.getRotationY(); 18657 } 18658 }; 18659 18660 /** 18661 * A Property wrapper around the <code>scaleX</code> functionality handled by the 18662 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 18663 */ 18664 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 18665 @Override 18666 public void setValue(View object, float value) { 18667 object.setScaleX(value); 18668 } 18669 18670 @Override 18671 public Float get(View object) { 18672 return object.getScaleX(); 18673 } 18674 }; 18675 18676 /** 18677 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18678 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18679 */ 18680 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18681 @Override 18682 public void setValue(View object, float value) { 18683 object.setScaleY(value); 18684 } 18685 18686 @Override 18687 public Float get(View object) { 18688 return object.getScaleY(); 18689 } 18690 }; 18691 18692 /** 18693 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18694 * Each MeasureSpec represents a requirement for either the width or the height. 18695 * A MeasureSpec is comprised of a size and a mode. There are three possible 18696 * modes: 18697 * <dl> 18698 * <dt>UNSPECIFIED</dt> 18699 * <dd> 18700 * The parent has not imposed any constraint on the child. It can be whatever size 18701 * it wants. 18702 * </dd> 18703 * 18704 * <dt>EXACTLY</dt> 18705 * <dd> 18706 * The parent has determined an exact size for the child. The child is going to be 18707 * given those bounds regardless of how big it wants to be. 18708 * </dd> 18709 * 18710 * <dt>AT_MOST</dt> 18711 * <dd> 18712 * The child can be as large as it wants up to the specified size. 18713 * </dd> 18714 * </dl> 18715 * 18716 * MeasureSpecs are implemented as ints to reduce object allocation. This class 18717 * is provided to pack and unpack the <size, mode> tuple into the int. 18718 */ 18719 public static class MeasureSpec { 18720 private static final int MODE_SHIFT = 30; 18721 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 18722 18723 /** 18724 * Measure specification mode: The parent has not imposed any constraint 18725 * on the child. It can be whatever size it wants. 18726 */ 18727 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 18728 18729 /** 18730 * Measure specification mode: The parent has determined an exact size 18731 * for the child. The child is going to be given those bounds regardless 18732 * of how big it wants to be. 18733 */ 18734 public static final int EXACTLY = 1 << MODE_SHIFT; 18735 18736 /** 18737 * Measure specification mode: The child can be as large as it wants up 18738 * to the specified size. 18739 */ 18740 public static final int AT_MOST = 2 << MODE_SHIFT; 18741 18742 /** 18743 * Creates a measure specification based on the supplied size and mode. 18744 * 18745 * The mode must always be one of the following: 18746 * <ul> 18747 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 18748 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 18749 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 18750 * </ul> 18751 * 18752 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 18753 * implementation was such that the order of arguments did not matter 18754 * and overflow in either value could impact the resulting MeasureSpec. 18755 * {@link android.widget.RelativeLayout} was affected by this bug. 18756 * Apps targeting API levels greater than 17 will get the fixed, more strict 18757 * behavior.</p> 18758 * 18759 * @param size the size of the measure specification 18760 * @param mode the mode of the measure specification 18761 * @return the measure specification based on size and mode 18762 */ 18763 public static int makeMeasureSpec(int size, int mode) { 18764 if (sUseBrokenMakeMeasureSpec) { 18765 return size + mode; 18766 } else { 18767 return (size & ~MODE_MASK) | (mode & MODE_MASK); 18768 } 18769 } 18770 18771 /** 18772 * Extracts the mode from the supplied measure specification. 18773 * 18774 * @param measureSpec the measure specification to extract the mode from 18775 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 18776 * {@link android.view.View.MeasureSpec#AT_MOST} or 18777 * {@link android.view.View.MeasureSpec#EXACTLY} 18778 */ 18779 public static int getMode(int measureSpec) { 18780 return (measureSpec & MODE_MASK); 18781 } 18782 18783 /** 18784 * Extracts the size from the supplied measure specification. 18785 * 18786 * @param measureSpec the measure specification to extract the size from 18787 * @return the size in pixels defined in the supplied measure specification 18788 */ 18789 public static int getSize(int measureSpec) { 18790 return (measureSpec & ~MODE_MASK); 18791 } 18792 18793 static int adjust(int measureSpec, int delta) { 18794 return makeMeasureSpec(getSize(measureSpec + delta), getMode(measureSpec)); 18795 } 18796 18797 /** 18798 * Returns a String representation of the specified measure 18799 * specification. 18800 * 18801 * @param measureSpec the measure specification to convert to a String 18802 * @return a String with the following format: "MeasureSpec: MODE SIZE" 18803 */ 18804 public static String toString(int measureSpec) { 18805 int mode = getMode(measureSpec); 18806 int size = getSize(measureSpec); 18807 18808 StringBuilder sb = new StringBuilder("MeasureSpec: "); 18809 18810 if (mode == UNSPECIFIED) 18811 sb.append("UNSPECIFIED "); 18812 else if (mode == EXACTLY) 18813 sb.append("EXACTLY "); 18814 else if (mode == AT_MOST) 18815 sb.append("AT_MOST "); 18816 else 18817 sb.append(mode).append(" "); 18818 18819 sb.append(size); 18820 return sb.toString(); 18821 } 18822 } 18823 18824 class CheckForLongPress implements Runnable { 18825 18826 private int mOriginalWindowAttachCount; 18827 18828 public void run() { 18829 if (isPressed() && (mParent != null) 18830 && mOriginalWindowAttachCount == mWindowAttachCount) { 18831 if (performLongClick()) { 18832 mHasPerformedLongPress = true; 18833 } 18834 } 18835 } 18836 18837 public void rememberWindowAttachCount() { 18838 mOriginalWindowAttachCount = mWindowAttachCount; 18839 } 18840 } 18841 18842 private final class CheckForTap implements Runnable { 18843 public void run() { 18844 mPrivateFlags &= ~PFLAG_PREPRESSED; 18845 setPressed(true); 18846 checkForLongClick(ViewConfiguration.getTapTimeout()); 18847 } 18848 } 18849 18850 private final class PerformClick implements Runnable { 18851 public void run() { 18852 performClick(); 18853 } 18854 } 18855 18856 /** @hide */ 18857 public void hackTurnOffWindowResizeAnim(boolean off) { 18858 mAttachInfo.mTurnOffWindowResizeAnim = off; 18859 } 18860 18861 /** 18862 * This method returns a ViewPropertyAnimator object, which can be used to animate 18863 * specific properties on this View. 18864 * 18865 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 18866 */ 18867 public ViewPropertyAnimator animate() { 18868 if (mAnimator == null) { 18869 mAnimator = new ViewPropertyAnimator(this); 18870 } 18871 return mAnimator; 18872 } 18873 18874 /** 18875 * Interface definition for a callback to be invoked when a hardware key event is 18876 * dispatched to this view. The callback will be invoked before the key event is 18877 * given to the view. This is only useful for hardware keyboards; a software input 18878 * method has no obligation to trigger this listener. 18879 */ 18880 public interface OnKeyListener { 18881 /** 18882 * Called when a hardware key is dispatched to a view. This allows listeners to 18883 * get a chance to respond before the target view. 18884 * <p>Key presses in software keyboards will generally NOT trigger this method, 18885 * although some may elect to do so in some situations. Do not assume a 18886 * software input method has to be key-based; even if it is, it may use key presses 18887 * in a different way than you expect, so there is no way to reliably catch soft 18888 * input key presses. 18889 * 18890 * @param v The view the key has been dispatched to. 18891 * @param keyCode The code for the physical key that was pressed 18892 * @param event The KeyEvent object containing full information about 18893 * the event. 18894 * @return True if the listener has consumed the event, false otherwise. 18895 */ 18896 boolean onKey(View v, int keyCode, KeyEvent event); 18897 } 18898 18899 /** 18900 * Interface definition for a callback to be invoked when a touch event is 18901 * dispatched to this view. The callback will be invoked before the touch 18902 * event is given to the view. 18903 */ 18904 public interface OnTouchListener { 18905 /** 18906 * Called when a touch event is dispatched to a view. This allows listeners to 18907 * get a chance to respond before the target view. 18908 * 18909 * @param v The view the touch event has been dispatched to. 18910 * @param event The MotionEvent object containing full information about 18911 * the event. 18912 * @return True if the listener has consumed the event, false otherwise. 18913 */ 18914 boolean onTouch(View v, MotionEvent event); 18915 } 18916 18917 /** 18918 * Interface definition for a callback to be invoked when a hover event is 18919 * dispatched to this view. The callback will be invoked before the hover 18920 * event is given to the view. 18921 */ 18922 public interface OnHoverListener { 18923 /** 18924 * Called when a hover event is dispatched to a view. This allows listeners to 18925 * get a chance to respond before the target view. 18926 * 18927 * @param v The view the hover event has been dispatched to. 18928 * @param event The MotionEvent object containing full information about 18929 * the event. 18930 * @return True if the listener has consumed the event, false otherwise. 18931 */ 18932 boolean onHover(View v, MotionEvent event); 18933 } 18934 18935 /** 18936 * Interface definition for a callback to be invoked when a generic motion event is 18937 * dispatched to this view. The callback will be invoked before the generic motion 18938 * event is given to the view. 18939 */ 18940 public interface OnGenericMotionListener { 18941 /** 18942 * Called when a generic motion event is dispatched to a view. This allows listeners to 18943 * get a chance to respond before the target view. 18944 * 18945 * @param v The view the generic motion event has been dispatched to. 18946 * @param event The MotionEvent object containing full information about 18947 * the event. 18948 * @return True if the listener has consumed the event, false otherwise. 18949 */ 18950 boolean onGenericMotion(View v, MotionEvent event); 18951 } 18952 18953 /** 18954 * Interface definition for a callback to be invoked when a view has been clicked and held. 18955 */ 18956 public interface OnLongClickListener { 18957 /** 18958 * Called when a view has been clicked and held. 18959 * 18960 * @param v The view that was clicked and held. 18961 * 18962 * @return true if the callback consumed the long click, false otherwise. 18963 */ 18964 boolean onLongClick(View v); 18965 } 18966 18967 /** 18968 * Interface definition for a callback to be invoked when a drag is being dispatched 18969 * to this view. The callback will be invoked before the hosting view's own 18970 * onDrag(event) method. If the listener wants to fall back to the hosting view's 18971 * onDrag(event) behavior, it should return 'false' from this callback. 18972 * 18973 * <div class="special reference"> 18974 * <h3>Developer Guides</h3> 18975 * <p>For a guide to implementing drag and drop features, read the 18976 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18977 * </div> 18978 */ 18979 public interface OnDragListener { 18980 /** 18981 * Called when a drag event is dispatched to a view. This allows listeners 18982 * to get a chance to override base View behavior. 18983 * 18984 * @param v The View that received the drag event. 18985 * @param event The {@link android.view.DragEvent} object for the drag event. 18986 * @return {@code true} if the drag event was handled successfully, or {@code false} 18987 * if the drag event was not handled. Note that {@code false} will trigger the View 18988 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 18989 */ 18990 boolean onDrag(View v, DragEvent event); 18991 } 18992 18993 /** 18994 * Interface definition for a callback to be invoked when the focus state of 18995 * a view changed. 18996 */ 18997 public interface OnFocusChangeListener { 18998 /** 18999 * Called when the focus state of a view has changed. 19000 * 19001 * @param v The view whose state has changed. 19002 * @param hasFocus The new focus state of v. 19003 */ 19004 void onFocusChange(View v, boolean hasFocus); 19005 } 19006 19007 /** 19008 * Interface definition for a callback to be invoked when a view is clicked. 19009 */ 19010 public interface OnClickListener { 19011 /** 19012 * Called when a view has been clicked. 19013 * 19014 * @param v The view that was clicked. 19015 */ 19016 void onClick(View v); 19017 } 19018 19019 /** 19020 * Interface definition for a callback to be invoked when the context menu 19021 * for this view is being built. 19022 */ 19023 public interface OnCreateContextMenuListener { 19024 /** 19025 * Called when the context menu for this view is being built. It is not 19026 * safe to hold onto the menu after this method returns. 19027 * 19028 * @param menu The context menu that is being built 19029 * @param v The view for which the context menu is being built 19030 * @param menuInfo Extra information about the item for which the 19031 * context menu should be shown. This information will vary 19032 * depending on the class of v. 19033 */ 19034 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19035 } 19036 19037 /** 19038 * Interface definition for a callback to be invoked when the status bar changes 19039 * visibility. This reports <strong>global</strong> changes to the system UI 19040 * state, not what the application is requesting. 19041 * 19042 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19043 */ 19044 public interface OnSystemUiVisibilityChangeListener { 19045 /** 19046 * Called when the status bar changes visibility because of a call to 19047 * {@link View#setSystemUiVisibility(int)}. 19048 * 19049 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19050 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19051 * This tells you the <strong>global</strong> state of these UI visibility 19052 * flags, not what your app is currently applying. 19053 */ 19054 public void onSystemUiVisibilityChange(int visibility); 19055 } 19056 19057 /** 19058 * Interface definition for a callback to be invoked when this view is attached 19059 * or detached from its window. 19060 */ 19061 public interface OnAttachStateChangeListener { 19062 /** 19063 * Called when the view is attached to a window. 19064 * @param v The view that was attached 19065 */ 19066 public void onViewAttachedToWindow(View v); 19067 /** 19068 * Called when the view is detached from a window. 19069 * @param v The view that was detached 19070 */ 19071 public void onViewDetachedFromWindow(View v); 19072 } 19073 19074 private final class UnsetPressedState implements Runnable { 19075 public void run() { 19076 setPressed(false); 19077 } 19078 } 19079 19080 /** 19081 * Base class for derived classes that want to save and restore their own 19082 * state in {@link android.view.View#onSaveInstanceState()}. 19083 */ 19084 public static class BaseSavedState extends AbsSavedState { 19085 /** 19086 * Constructor used when reading from a parcel. Reads the state of the superclass. 19087 * 19088 * @param source 19089 */ 19090 public BaseSavedState(Parcel source) { 19091 super(source); 19092 } 19093 19094 /** 19095 * Constructor called by derived classes when creating their SavedState objects 19096 * 19097 * @param superState The state of the superclass of this view 19098 */ 19099 public BaseSavedState(Parcelable superState) { 19100 super(superState); 19101 } 19102 19103 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19104 new Parcelable.Creator<BaseSavedState>() { 19105 public BaseSavedState createFromParcel(Parcel in) { 19106 return new BaseSavedState(in); 19107 } 19108 19109 public BaseSavedState[] newArray(int size) { 19110 return new BaseSavedState[size]; 19111 } 19112 }; 19113 } 19114 19115 /** 19116 * A set of information given to a view when it is attached to its parent 19117 * window. 19118 */ 19119 static class AttachInfo { 19120 interface Callbacks { 19121 void playSoundEffect(int effectId); 19122 boolean performHapticFeedback(int effectId, boolean always); 19123 } 19124 19125 /** 19126 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19127 * to a Handler. This class contains the target (View) to invalidate and 19128 * the coordinates of the dirty rectangle. 19129 * 19130 * For performance purposes, this class also implements a pool of up to 19131 * POOL_LIMIT objects that get reused. This reduces memory allocations 19132 * whenever possible. 19133 */ 19134 static class InvalidateInfo { 19135 private static final int POOL_LIMIT = 10; 19136 19137 private static final SynchronizedPool<InvalidateInfo> sPool = 19138 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19139 19140 View target; 19141 19142 int left; 19143 int top; 19144 int right; 19145 int bottom; 19146 19147 public static InvalidateInfo obtain() { 19148 InvalidateInfo instance = sPool.acquire(); 19149 return (instance != null) ? instance : new InvalidateInfo(); 19150 } 19151 19152 public void recycle() { 19153 target = null; 19154 sPool.release(this); 19155 } 19156 } 19157 19158 final IWindowSession mSession; 19159 19160 final IWindow mWindow; 19161 19162 final IBinder mWindowToken; 19163 19164 final Display mDisplay; 19165 19166 final Callbacks mRootCallbacks; 19167 19168 IWindowId mIWindowId; 19169 WindowId mWindowId; 19170 19171 /** 19172 * The top view of the hierarchy. 19173 */ 19174 View mRootView; 19175 19176 IBinder mPanelParentWindowToken; 19177 19178 boolean mHardwareAccelerated; 19179 boolean mHardwareAccelerationRequested; 19180 HardwareRenderer mHardwareRenderer; 19181 19182 boolean mScreenOn; 19183 19184 /** 19185 * Scale factor used by the compatibility mode 19186 */ 19187 float mApplicationScale; 19188 19189 /** 19190 * Indicates whether the application is in compatibility mode 19191 */ 19192 boolean mScalingRequired; 19193 19194 /** 19195 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19196 */ 19197 boolean mTurnOffWindowResizeAnim; 19198 19199 /** 19200 * Left position of this view's window 19201 */ 19202 int mWindowLeft; 19203 19204 /** 19205 * Top position of this view's window 19206 */ 19207 int mWindowTop; 19208 19209 /** 19210 * Indicates whether views need to use 32-bit drawing caches 19211 */ 19212 boolean mUse32BitDrawingCache; 19213 19214 /** 19215 * For windows that are full-screen but using insets to layout inside 19216 * of the screen areas, these are the current insets to appear inside 19217 * the overscan area of the display. 19218 */ 19219 final Rect mOverscanInsets = new Rect(); 19220 19221 /** 19222 * For windows that are full-screen but using insets to layout inside 19223 * of the screen decorations, these are the current insets for the 19224 * content of the window. 19225 */ 19226 final Rect mContentInsets = new Rect(); 19227 19228 /** 19229 * For windows that are full-screen but using insets to layout inside 19230 * of the screen decorations, these are the current insets for the 19231 * actual visible parts of the window. 19232 */ 19233 final Rect mVisibleInsets = new Rect(); 19234 19235 /** 19236 * The internal insets given by this window. This value is 19237 * supplied by the client (through 19238 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19239 * be given to the window manager when changed to be used in laying 19240 * out windows behind it. 19241 */ 19242 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19243 = new ViewTreeObserver.InternalInsetsInfo(); 19244 19245 /** 19246 * Set to true when mGivenInternalInsets is non-empty. 19247 */ 19248 boolean mHasNonEmptyGivenInternalInsets; 19249 19250 /** 19251 * All views in the window's hierarchy that serve as scroll containers, 19252 * used to determine if the window can be resized or must be panned 19253 * to adjust for a soft input area. 19254 */ 19255 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19256 19257 final KeyEvent.DispatcherState mKeyDispatchState 19258 = new KeyEvent.DispatcherState(); 19259 19260 /** 19261 * Indicates whether the view's window currently has the focus. 19262 */ 19263 boolean mHasWindowFocus; 19264 19265 /** 19266 * The current visibility of the window. 19267 */ 19268 int mWindowVisibility; 19269 19270 /** 19271 * Indicates the time at which drawing started to occur. 19272 */ 19273 long mDrawingTime; 19274 19275 /** 19276 * Indicates whether or not ignoring the DIRTY_MASK flags. 19277 */ 19278 boolean mIgnoreDirtyState; 19279 19280 /** 19281 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19282 * to avoid clearing that flag prematurely. 19283 */ 19284 boolean mSetIgnoreDirtyState = false; 19285 19286 /** 19287 * Indicates whether the view's window is currently in touch mode. 19288 */ 19289 boolean mInTouchMode; 19290 19291 /** 19292 * Indicates that ViewAncestor should trigger a global layout change 19293 * the next time it performs a traversal 19294 */ 19295 boolean mRecomputeGlobalAttributes; 19296 19297 /** 19298 * Always report new attributes at next traversal. 19299 */ 19300 boolean mForceReportNewAttributes; 19301 19302 /** 19303 * Set during a traveral if any views want to keep the screen on. 19304 */ 19305 boolean mKeepScreenOn; 19306 19307 /** 19308 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19309 */ 19310 int mSystemUiVisibility; 19311 19312 /** 19313 * Hack to force certain system UI visibility flags to be cleared. 19314 */ 19315 int mDisabledSystemUiVisibility; 19316 19317 /** 19318 * Last global system UI visibility reported by the window manager. 19319 */ 19320 int mGlobalSystemUiVisibility; 19321 19322 /** 19323 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19324 * attached. 19325 */ 19326 boolean mHasSystemUiListeners; 19327 19328 /** 19329 * Set if the window has requested to extend into the overscan region 19330 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19331 */ 19332 boolean mOverscanRequested; 19333 19334 /** 19335 * Set if the visibility of any views has changed. 19336 */ 19337 boolean mViewVisibilityChanged; 19338 19339 /** 19340 * Set to true if a view has been scrolled. 19341 */ 19342 boolean mViewScrollChanged; 19343 19344 /** 19345 * Global to the view hierarchy used as a temporary for dealing with 19346 * x/y points in the transparent region computations. 19347 */ 19348 final int[] mTransparentLocation = new int[2]; 19349 19350 /** 19351 * Global to the view hierarchy used as a temporary for dealing with 19352 * x/y points in the ViewGroup.invalidateChild implementation. 19353 */ 19354 final int[] mInvalidateChildLocation = new int[2]; 19355 19356 19357 /** 19358 * Global to the view hierarchy used as a temporary for dealing with 19359 * x/y location when view is transformed. 19360 */ 19361 final float[] mTmpTransformLocation = new float[2]; 19362 19363 /** 19364 * The view tree observer used to dispatch global events like 19365 * layout, pre-draw, touch mode change, etc. 19366 */ 19367 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19368 19369 /** 19370 * A Canvas used by the view hierarchy to perform bitmap caching. 19371 */ 19372 Canvas mCanvas; 19373 19374 /** 19375 * The view root impl. 19376 */ 19377 final ViewRootImpl mViewRootImpl; 19378 19379 /** 19380 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19381 * handler can be used to pump events in the UI events queue. 19382 */ 19383 final Handler mHandler; 19384 19385 /** 19386 * Temporary for use in computing invalidate rectangles while 19387 * calling up the hierarchy. 19388 */ 19389 final Rect mTmpInvalRect = new Rect(); 19390 19391 /** 19392 * Temporary for use in computing hit areas with transformed views 19393 */ 19394 final RectF mTmpTransformRect = new RectF(); 19395 19396 /** 19397 * Temporary for use in transforming invalidation rect 19398 */ 19399 final Matrix mTmpMatrix = new Matrix(); 19400 19401 /** 19402 * Temporary for use in transforming invalidation rect 19403 */ 19404 final Transformation mTmpTransformation = new Transformation(); 19405 19406 /** 19407 * Temporary list for use in collecting focusable descendents of a view. 19408 */ 19409 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19410 19411 /** 19412 * The id of the window for accessibility purposes. 19413 */ 19414 int mAccessibilityWindowId = View.NO_ID; 19415 19416 /** 19417 * Flags related to accessibility processing. 19418 * 19419 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19420 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19421 */ 19422 int mAccessibilityFetchFlags; 19423 19424 /** 19425 * The drawable for highlighting accessibility focus. 19426 */ 19427 Drawable mAccessibilityFocusDrawable; 19428 19429 /** 19430 * Show where the margins, bounds and layout bounds are for each view. 19431 */ 19432 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19433 19434 /** 19435 * Point used to compute visible regions. 19436 */ 19437 final Point mPoint = new Point(); 19438 19439 /** 19440 * Used to track which View originated a requestLayout() call, used when 19441 * requestLayout() is called during layout. 19442 */ 19443 View mViewRequestingLayout; 19444 19445 /** 19446 * Creates a new set of attachment information with the specified 19447 * events handler and thread. 19448 * 19449 * @param handler the events handler the view must use 19450 */ 19451 AttachInfo(IWindowSession session, IWindow window, Display display, 19452 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19453 mSession = session; 19454 mWindow = window; 19455 mWindowToken = window.asBinder(); 19456 mDisplay = display; 19457 mViewRootImpl = viewRootImpl; 19458 mHandler = handler; 19459 mRootCallbacks = effectPlayer; 19460 } 19461 } 19462 19463 /** 19464 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19465 * is supported. This avoids keeping too many unused fields in most 19466 * instances of View.</p> 19467 */ 19468 private static class ScrollabilityCache implements Runnable { 19469 19470 /** 19471 * Scrollbars are not visible 19472 */ 19473 public static final int OFF = 0; 19474 19475 /** 19476 * Scrollbars are visible 19477 */ 19478 public static final int ON = 1; 19479 19480 /** 19481 * Scrollbars are fading away 19482 */ 19483 public static final int FADING = 2; 19484 19485 public boolean fadeScrollBars; 19486 19487 public int fadingEdgeLength; 19488 public int scrollBarDefaultDelayBeforeFade; 19489 public int scrollBarFadeDuration; 19490 19491 public int scrollBarSize; 19492 public ScrollBarDrawable scrollBar; 19493 public float[] interpolatorValues; 19494 public View host; 19495 19496 public final Paint paint; 19497 public final Matrix matrix; 19498 public Shader shader; 19499 19500 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19501 19502 private static final float[] OPAQUE = { 255 }; 19503 private static final float[] TRANSPARENT = { 0.0f }; 19504 19505 /** 19506 * When fading should start. This time moves into the future every time 19507 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19508 */ 19509 public long fadeStartTime; 19510 19511 19512 /** 19513 * The current state of the scrollbars: ON, OFF, or FADING 19514 */ 19515 public int state = OFF; 19516 19517 private int mLastColor; 19518 19519 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19520 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19521 scrollBarSize = configuration.getScaledScrollBarSize(); 19522 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19523 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19524 19525 paint = new Paint(); 19526 matrix = new Matrix(); 19527 // use use a height of 1, and then wack the matrix each time we 19528 // actually use it. 19529 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19530 paint.setShader(shader); 19531 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19532 19533 this.host = host; 19534 } 19535 19536 public void setFadeColor(int color) { 19537 if (color != mLastColor) { 19538 mLastColor = color; 19539 19540 if (color != 0) { 19541 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 19542 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 19543 paint.setShader(shader); 19544 // Restore the default transfer mode (src_over) 19545 paint.setXfermode(null); 19546 } else { 19547 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19548 paint.setShader(shader); 19549 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19550 } 19551 } 19552 } 19553 19554 public void run() { 19555 long now = AnimationUtils.currentAnimationTimeMillis(); 19556 if (now >= fadeStartTime) { 19557 19558 // the animation fades the scrollbars out by changing 19559 // the opacity (alpha) from fully opaque to fully 19560 // transparent 19561 int nextFrame = (int) now; 19562 int framesCount = 0; 19563 19564 Interpolator interpolator = scrollBarInterpolator; 19565 19566 // Start opaque 19567 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 19568 19569 // End transparent 19570 nextFrame += scrollBarFadeDuration; 19571 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 19572 19573 state = FADING; 19574 19575 // Kick off the fade animation 19576 host.invalidate(true); 19577 } 19578 } 19579 } 19580 19581 /** 19582 * Resuable callback for sending 19583 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 19584 */ 19585 private class SendViewScrolledAccessibilityEvent implements Runnable { 19586 public volatile boolean mIsPending; 19587 19588 public void run() { 19589 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 19590 mIsPending = false; 19591 } 19592 } 19593 19594 /** 19595 * <p> 19596 * This class represents a delegate that can be registered in a {@link View} 19597 * to enhance accessibility support via composition rather via inheritance. 19598 * It is specifically targeted to widget developers that extend basic View 19599 * classes i.e. classes in package android.view, that would like their 19600 * applications to be backwards compatible. 19601 * </p> 19602 * <div class="special reference"> 19603 * <h3>Developer Guides</h3> 19604 * <p>For more information about making applications accessible, read the 19605 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 19606 * developer guide.</p> 19607 * </div> 19608 * <p> 19609 * A scenario in which a developer would like to use an accessibility delegate 19610 * is overriding a method introduced in a later API version then the minimal API 19611 * version supported by the application. For example, the method 19612 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 19613 * in API version 4 when the accessibility APIs were first introduced. If a 19614 * developer would like his application to run on API version 4 devices (assuming 19615 * all other APIs used by the application are version 4 or lower) and take advantage 19616 * of this method, instead of overriding the method which would break the application's 19617 * backwards compatibility, he can override the corresponding method in this 19618 * delegate and register the delegate in the target View if the API version of 19619 * the system is high enough i.e. the API version is same or higher to the API 19620 * version that introduced 19621 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 19622 * </p> 19623 * <p> 19624 * Here is an example implementation: 19625 * </p> 19626 * <code><pre><p> 19627 * if (Build.VERSION.SDK_INT >= 14) { 19628 * // If the API version is equal of higher than the version in 19629 * // which onInitializeAccessibilityNodeInfo was introduced we 19630 * // register a delegate with a customized implementation. 19631 * View view = findViewById(R.id.view_id); 19632 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 19633 * public void onInitializeAccessibilityNodeInfo(View host, 19634 * AccessibilityNodeInfo info) { 19635 * // Let the default implementation populate the info. 19636 * super.onInitializeAccessibilityNodeInfo(host, info); 19637 * // Set some other information. 19638 * info.setEnabled(host.isEnabled()); 19639 * } 19640 * }); 19641 * } 19642 * </code></pre></p> 19643 * <p> 19644 * This delegate contains methods that correspond to the accessibility methods 19645 * in View. If a delegate has been specified the implementation in View hands 19646 * off handling to the corresponding method in this delegate. The default 19647 * implementation the delegate methods behaves exactly as the corresponding 19648 * method in View for the case of no accessibility delegate been set. Hence, 19649 * to customize the behavior of a View method, clients can override only the 19650 * corresponding delegate method without altering the behavior of the rest 19651 * accessibility related methods of the host view. 19652 * </p> 19653 */ 19654 public static class AccessibilityDelegate { 19655 19656 /** 19657 * Sends an accessibility event of the given type. If accessibility is not 19658 * enabled this method has no effect. 19659 * <p> 19660 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 19661 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 19662 * been set. 19663 * </p> 19664 * 19665 * @param host The View hosting the delegate. 19666 * @param eventType The type of the event to send. 19667 * 19668 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 19669 */ 19670 public void sendAccessibilityEvent(View host, int eventType) { 19671 host.sendAccessibilityEventInternal(eventType); 19672 } 19673 19674 /** 19675 * Performs the specified accessibility action on the view. For 19676 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 19677 * <p> 19678 * The default implementation behaves as 19679 * {@link View#performAccessibilityAction(int, Bundle) 19680 * View#performAccessibilityAction(int, Bundle)} for the case of 19681 * no accessibility delegate been set. 19682 * </p> 19683 * 19684 * @param action The action to perform. 19685 * @return Whether the action was performed. 19686 * 19687 * @see View#performAccessibilityAction(int, Bundle) 19688 * View#performAccessibilityAction(int, Bundle) 19689 */ 19690 public boolean performAccessibilityAction(View host, int action, Bundle args) { 19691 return host.performAccessibilityActionInternal(action, args); 19692 } 19693 19694 /** 19695 * Sends an accessibility event. This method behaves exactly as 19696 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 19697 * empty {@link AccessibilityEvent} and does not perform a check whether 19698 * accessibility is enabled. 19699 * <p> 19700 * The default implementation behaves as 19701 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19702 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 19703 * the case of no accessibility delegate been set. 19704 * </p> 19705 * 19706 * @param host The View hosting the delegate. 19707 * @param event The event to send. 19708 * 19709 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19710 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19711 */ 19712 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 19713 host.sendAccessibilityEventUncheckedInternal(event); 19714 } 19715 19716 /** 19717 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 19718 * to its children for adding their text content to the event. 19719 * <p> 19720 * The default implementation behaves as 19721 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19722 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 19723 * the case of no accessibility delegate been set. 19724 * </p> 19725 * 19726 * @param host The View hosting the delegate. 19727 * @param event The event. 19728 * @return True if the event population was completed. 19729 * 19730 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19731 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19732 */ 19733 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19734 return host.dispatchPopulateAccessibilityEventInternal(event); 19735 } 19736 19737 /** 19738 * Gives a chance to the host View to populate the accessibility event with its 19739 * text content. 19740 * <p> 19741 * The default implementation behaves as 19742 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 19743 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 19744 * the case of no accessibility delegate been set. 19745 * </p> 19746 * 19747 * @param host The View hosting the delegate. 19748 * @param event The accessibility event which to populate. 19749 * 19750 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 19751 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 19752 */ 19753 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19754 host.onPopulateAccessibilityEventInternal(event); 19755 } 19756 19757 /** 19758 * Initializes an {@link AccessibilityEvent} with information about the 19759 * the host View which is the event source. 19760 * <p> 19761 * The default implementation behaves as 19762 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 19763 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 19764 * the case of no accessibility delegate been set. 19765 * </p> 19766 * 19767 * @param host The View hosting the delegate. 19768 * @param event The event to initialize. 19769 * 19770 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 19771 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 19772 */ 19773 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 19774 host.onInitializeAccessibilityEventInternal(event); 19775 } 19776 19777 /** 19778 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 19779 * <p> 19780 * The default implementation behaves as 19781 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19782 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 19783 * the case of no accessibility delegate been set. 19784 * </p> 19785 * 19786 * @param host The View hosting the delegate. 19787 * @param info The instance to initialize. 19788 * 19789 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19790 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19791 */ 19792 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 19793 host.onInitializeAccessibilityNodeInfoInternal(info); 19794 } 19795 19796 /** 19797 * Called when a child of the host View has requested sending an 19798 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 19799 * to augment the event. 19800 * <p> 19801 * The default implementation behaves as 19802 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19803 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 19804 * the case of no accessibility delegate been set. 19805 * </p> 19806 * 19807 * @param host The View hosting the delegate. 19808 * @param child The child which requests sending the event. 19809 * @param event The event to be sent. 19810 * @return True if the event should be sent 19811 * 19812 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19813 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19814 */ 19815 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 19816 AccessibilityEvent event) { 19817 return host.onRequestSendAccessibilityEventInternal(child, event); 19818 } 19819 19820 /** 19821 * Gets the provider for managing a virtual view hierarchy rooted at this View 19822 * and reported to {@link android.accessibilityservice.AccessibilityService}s 19823 * that explore the window content. 19824 * <p> 19825 * The default implementation behaves as 19826 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 19827 * the case of no accessibility delegate been set. 19828 * </p> 19829 * 19830 * @return The provider. 19831 * 19832 * @see AccessibilityNodeProvider 19833 */ 19834 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 19835 return null; 19836 } 19837 19838 /** 19839 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 19840 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 19841 * This method is responsible for obtaining an accessibility node info from a 19842 * pool of reusable instances and calling 19843 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 19844 * view to initialize the former. 19845 * <p> 19846 * <strong>Note:</strong> The client is responsible for recycling the obtained 19847 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 19848 * creation. 19849 * </p> 19850 * <p> 19851 * The default implementation behaves as 19852 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 19853 * the case of no accessibility delegate been set. 19854 * </p> 19855 * @return A populated {@link AccessibilityNodeInfo}. 19856 * 19857 * @see AccessibilityNodeInfo 19858 * 19859 * @hide 19860 */ 19861 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 19862 return host.createAccessibilityNodeInfoInternal(); 19863 } 19864 } 19865 19866 private class MatchIdPredicate implements Predicate<View> { 19867 public int mId; 19868 19869 @Override 19870 public boolean apply(View view) { 19871 return (view.mID == mId); 19872 } 19873 } 19874 19875 private class MatchLabelForPredicate implements Predicate<View> { 19876 private int mLabeledId; 19877 19878 @Override 19879 public boolean apply(View view) { 19880 return (view.mLabelForId == mLabeledId); 19881 } 19882 } 19883 19884 private class SendViewStateChangedAccessibilityEvent implements Runnable { 19885 private int mChangeTypes = 0; 19886 private boolean mPosted; 19887 private boolean mPostedWithDelay; 19888 private long mLastEventTimeMillis; 19889 19890 @Override 19891 public void run() { 19892 mPosted = false; 19893 mPostedWithDelay = false; 19894 mLastEventTimeMillis = SystemClock.uptimeMillis(); 19895 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 19896 final AccessibilityEvent event = AccessibilityEvent.obtain(); 19897 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 19898 event.setContentChangeTypes(mChangeTypes); 19899 sendAccessibilityEventUnchecked(event); 19900 } 19901 mChangeTypes = 0; 19902 } 19903 19904 public void runOrPost(int changeType) { 19905 mChangeTypes |= changeType; 19906 19907 // If this is a live region or the child of a live region, collect 19908 // all events from this frame and send them on the next frame. 19909 if (inLiveRegion()) { 19910 // If we're already posted with a delay, remove that. 19911 if (mPostedWithDelay) { 19912 removeCallbacks(this); 19913 mPostedWithDelay = false; 19914 } 19915 // Only post if we're not already posted. 19916 if (!mPosted) { 19917 post(this); 19918 mPosted = true; 19919 } 19920 return; 19921 } 19922 19923 if (mPosted) { 19924 return; 19925 } 19926 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 19927 final long minEventIntevalMillis = 19928 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 19929 if (timeSinceLastMillis >= minEventIntevalMillis) { 19930 removeCallbacks(this); 19931 run(); 19932 } else { 19933 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 19934 mPosted = true; 19935 mPostedWithDelay = true; 19936 } 19937 } 19938 } 19939 19940 private boolean inLiveRegion() { 19941 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19942 return true; 19943 } 19944 19945 ViewParent parent = getParent(); 19946 while (parent instanceof View) { 19947 if (((View) parent).getAccessibilityLiveRegion() 19948 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19949 return true; 19950 } 19951 parent = parent.getParent(); 19952 } 19953 19954 return false; 19955 } 19956 19957 /** 19958 * Dump all private flags in readable format, useful for documentation and 19959 * sanity checking. 19960 */ 19961 private static void dumpFlags() { 19962 final HashMap<String, String> found = Maps.newHashMap(); 19963 try { 19964 for (Field field : View.class.getDeclaredFields()) { 19965 final int modifiers = field.getModifiers(); 19966 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 19967 if (field.getType().equals(int.class)) { 19968 final int value = field.getInt(null); 19969 dumpFlag(found, field.getName(), value); 19970 } else if (field.getType().equals(int[].class)) { 19971 final int[] values = (int[]) field.get(null); 19972 for (int i = 0; i < values.length; i++) { 19973 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 19974 } 19975 } 19976 } 19977 } 19978 } catch (IllegalAccessException e) { 19979 throw new RuntimeException(e); 19980 } 19981 19982 final ArrayList<String> keys = Lists.newArrayList(); 19983 keys.addAll(found.keySet()); 19984 Collections.sort(keys); 19985 for (String key : keys) { 19986 Log.d(VIEW_LOG_TAG, found.get(key)); 19987 } 19988 } 19989 19990 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 19991 // Sort flags by prefix, then by bits, always keeping unique keys 19992 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 19993 final int prefix = name.indexOf('_'); 19994 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 19995 final String output = bits + " " + name; 19996 found.put(key, output); 19997 } 19998} 19999