View.java revision e6a39b12656ab8d5c77d8366b24aa6410fd42e11
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.RevealAnimator; 20import android.animation.ValueAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.Configuration; 27import android.content.res.Resources; 28import android.content.res.TypedArray; 29import android.graphics.Bitmap; 30import android.graphics.Canvas; 31import android.graphics.Insets; 32import android.graphics.Interpolator; 33import android.graphics.LinearGradient; 34import android.graphics.Matrix; 35import android.graphics.Outline; 36import android.graphics.Paint; 37import android.graphics.PixelFormat; 38import android.graphics.Point; 39import android.graphics.PorterDuff; 40import android.graphics.PorterDuffXfermode; 41import android.graphics.Rect; 42import android.graphics.RectF; 43import android.graphics.Region; 44import android.graphics.Shader; 45import android.graphics.drawable.ColorDrawable; 46import android.graphics.drawable.Drawable; 47import android.hardware.display.DisplayManagerGlobal; 48import android.os.Bundle; 49import android.os.Handler; 50import android.os.IBinder; 51import android.os.Parcel; 52import android.os.Parcelable; 53import android.os.RemoteException; 54import android.os.SystemClock; 55import android.os.SystemProperties; 56import android.text.TextUtils; 57import android.util.AttributeSet; 58import android.util.FloatProperty; 59import android.util.LayoutDirection; 60import android.util.Log; 61import android.util.LongSparseLongArray; 62import android.util.Pools.SynchronizedPool; 63import android.util.Property; 64import android.util.SparseArray; 65import android.util.SuperNotCalledException; 66import android.util.TypedValue; 67import android.view.ContextMenu.ContextMenuInfo; 68import android.view.AccessibilityIterators.TextSegmentIterator; 69import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 70import android.view.AccessibilityIterators.WordTextSegmentIterator; 71import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 72import android.view.accessibility.AccessibilityEvent; 73import android.view.accessibility.AccessibilityEventSource; 74import android.view.accessibility.AccessibilityManager; 75import android.view.accessibility.AccessibilityNodeInfo; 76import android.view.accessibility.AccessibilityNodeProvider; 77import android.view.animation.Animation; 78import android.view.animation.AnimationUtils; 79import android.view.animation.Transformation; 80import android.view.inputmethod.EditorInfo; 81import android.view.inputmethod.InputConnection; 82import android.view.inputmethod.InputMethodManager; 83import android.widget.ScrollBarDrawable; 84 85import static android.os.Build.VERSION_CODES.*; 86import static java.lang.Math.max; 87 88import com.android.internal.R; 89import com.android.internal.util.Predicate; 90import com.android.internal.view.menu.MenuBuilder; 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.List; 106import java.util.Locale; 107import java.util.Map; 108import java.util.concurrent.CopyOnWriteArrayList; 109import java.util.concurrent.atomic.AtomicInteger; 110 111/** 112 * <p> 113 * This class represents the basic building block for user interface components. A View 114 * occupies a rectangular area on the screen and is responsible for drawing and 115 * event handling. View is the base class for <em>widgets</em>, which are 116 * used to create interactive UI components (buttons, text fields, etc.). The 117 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 118 * are invisible containers that hold other Views (or other ViewGroups) and define 119 * their layout properties. 120 * </p> 121 * 122 * <div class="special reference"> 123 * <h3>Developer Guides</h3> 124 * <p>For information about using this class to develop your application's user interface, 125 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 126 * </div> 127 * 128 * <a name="Using"></a> 129 * <h3>Using Views</h3> 130 * <p> 131 * All of the views in a window are arranged in a single tree. You can add views 132 * either from code or by specifying a tree of views in one or more XML layout 133 * files. There are many specialized subclasses of views that act as controls or 134 * are capable of displaying text, images, or other content. 135 * </p> 136 * <p> 137 * Once you have created a tree of views, there are typically a few types of 138 * common operations you may wish to perform: 139 * <ul> 140 * <li><strong>Set properties:</strong> for example setting the text of a 141 * {@link android.widget.TextView}. The available properties and the methods 142 * that set them will vary among the different subclasses of views. Note that 143 * properties that are known at build time can be set in the XML layout 144 * files.</li> 145 * <li><strong>Set focus:</strong> The framework will handled moving focus in 146 * response to user input. To force focus to a specific view, call 147 * {@link #requestFocus}.</li> 148 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 149 * that will be notified when something interesting happens to the view. For 150 * example, all views will let you set a listener to be notified when the view 151 * gains or loses focus. You can register such a listener using 152 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 153 * Other view subclasses offer more specialized listeners. For example, a Button 154 * exposes a listener to notify clients when the button is clicked.</li> 155 * <li><strong>Set visibility:</strong> You can hide or show views using 156 * {@link #setVisibility(int)}.</li> 157 * </ul> 158 * </p> 159 * <p><em> 160 * Note: The Android framework is responsible for measuring, laying out and 161 * drawing views. You should not call methods that perform these actions on 162 * views yourself unless you are actually implementing a 163 * {@link android.view.ViewGroup}. 164 * </em></p> 165 * 166 * <a name="Lifecycle"></a> 167 * <h3>Implementing a Custom View</h3> 168 * 169 * <p> 170 * To implement a custom view, you will usually begin by providing overrides for 171 * some of the standard methods that the framework calls on all views. You do 172 * not need to override all of these methods. In fact, you can start by just 173 * overriding {@link #onDraw(android.graphics.Canvas)}. 174 * <table border="2" width="85%" align="center" cellpadding="5"> 175 * <thead> 176 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 177 * </thead> 178 * 179 * <tbody> 180 * <tr> 181 * <td rowspan="2">Creation</td> 182 * <td>Constructors</td> 183 * <td>There is a form of the constructor that are called when the view 184 * is created from code and a form that is called when the view is 185 * inflated from a layout file. The second form should parse and apply 186 * any attributes defined in the layout file. 187 * </td> 188 * </tr> 189 * <tr> 190 * <td><code>{@link #onFinishInflate()}</code></td> 191 * <td>Called after a view and all of its children has been inflated 192 * from XML.</td> 193 * </tr> 194 * 195 * <tr> 196 * <td rowspan="3">Layout</td> 197 * <td><code>{@link #onMeasure(int, int)}</code></td> 198 * <td>Called to determine the size requirements for this view and all 199 * of its children. 200 * </td> 201 * </tr> 202 * <tr> 203 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 204 * <td>Called when this view should assign a size and position to all 205 * of its children. 206 * </td> 207 * </tr> 208 * <tr> 209 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 210 * <td>Called when the size of this view has changed. 211 * </td> 212 * </tr> 213 * 214 * <tr> 215 * <td>Drawing</td> 216 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 217 * <td>Called when the view should render its content. 218 * </td> 219 * </tr> 220 * 221 * <tr> 222 * <td rowspan="4">Event processing</td> 223 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 224 * <td>Called when a new hardware key event occurs. 225 * </td> 226 * </tr> 227 * <tr> 228 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 229 * <td>Called when a hardware key up event occurs. 230 * </td> 231 * </tr> 232 * <tr> 233 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 234 * <td>Called when a trackball motion event occurs. 235 * </td> 236 * </tr> 237 * <tr> 238 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 239 * <td>Called when a touch screen motion event occurs. 240 * </td> 241 * </tr> 242 * 243 * <tr> 244 * <td rowspan="2">Focus</td> 245 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 246 * <td>Called when the view gains or loses focus. 247 * </td> 248 * </tr> 249 * 250 * <tr> 251 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 252 * <td>Called when the window containing the view gains or loses focus. 253 * </td> 254 * </tr> 255 * 256 * <tr> 257 * <td rowspan="3">Attaching</td> 258 * <td><code>{@link #onAttachedToWindow()}</code></td> 259 * <td>Called when the view is attached to a window. 260 * </td> 261 * </tr> 262 * 263 * <tr> 264 * <td><code>{@link #onDetachedFromWindow}</code></td> 265 * <td>Called when the view is detached from its window. 266 * </td> 267 * </tr> 268 * 269 * <tr> 270 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 271 * <td>Called when the visibility of the window containing the view 272 * has changed. 273 * </td> 274 * </tr> 275 * </tbody> 276 * 277 * </table> 278 * </p> 279 * 280 * <a name="IDs"></a> 281 * <h3>IDs</h3> 282 * Views may have an integer id associated with them. These ids are typically 283 * assigned in the layout XML files, and are used to find specific views within 284 * the view tree. A common pattern is to: 285 * <ul> 286 * <li>Define a Button in the layout file and assign it a unique ID. 287 * <pre> 288 * <Button 289 * android:id="@+id/my_button" 290 * android:layout_width="wrap_content" 291 * android:layout_height="wrap_content" 292 * android:text="@string/my_button_text"/> 293 * </pre></li> 294 * <li>From the onCreate method of an Activity, find the Button 295 * <pre class="prettyprint"> 296 * Button myButton = (Button) findViewById(R.id.my_button); 297 * </pre></li> 298 * </ul> 299 * <p> 300 * View IDs need not be unique throughout the tree, but it is good practice to 301 * ensure that they are at least unique within the part of the tree you are 302 * searching. 303 * </p> 304 * 305 * <a name="Position"></a> 306 * <h3>Position</h3> 307 * <p> 308 * The geometry of a view is that of a rectangle. A view has a location, 309 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 310 * two dimensions, expressed as a width and a height. The unit for location 311 * and dimensions is the pixel. 312 * </p> 313 * 314 * <p> 315 * It is possible to retrieve the location of a view by invoking the methods 316 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 317 * coordinate of the rectangle representing the view. The latter returns the 318 * top, or Y, coordinate of the rectangle representing the view. These methods 319 * both return the location of the view relative to its parent. For instance, 320 * when getLeft() returns 20, that means the view is located 20 pixels to the 321 * right of the left edge of its direct parent. 322 * </p> 323 * 324 * <p> 325 * In addition, several convenience methods are offered to avoid unnecessary 326 * computations, namely {@link #getRight()} and {@link #getBottom()}. 327 * These methods return the coordinates of the right and bottom edges of the 328 * rectangle representing the view. For instance, calling {@link #getRight()} 329 * is similar to the following computation: <code>getLeft() + getWidth()</code> 330 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 331 * </p> 332 * 333 * <a name="SizePaddingMargins"></a> 334 * <h3>Size, padding and margins</h3> 335 * <p> 336 * The size of a view is expressed with a width and a height. A view actually 337 * possess two pairs of width and height values. 338 * </p> 339 * 340 * <p> 341 * The first pair is known as <em>measured width</em> and 342 * <em>measured height</em>. These dimensions define how big a view wants to be 343 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 344 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 345 * and {@link #getMeasuredHeight()}. 346 * </p> 347 * 348 * <p> 349 * The second pair is simply known as <em>width</em> and <em>height</em>, or 350 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 351 * dimensions define the actual size of the view on screen, at drawing time and 352 * after layout. These values may, but do not have to, be different from the 353 * measured width and height. The width and height can be obtained by calling 354 * {@link #getWidth()} and {@link #getHeight()}. 355 * </p> 356 * 357 * <p> 358 * To measure its dimensions, a view takes into account its padding. The padding 359 * is expressed in pixels for the left, top, right and bottom parts of the view. 360 * Padding can be used to offset the content of the view by a specific amount of 361 * pixels. For instance, a left padding of 2 will push the view's content by 362 * 2 pixels to the right of the left edge. Padding can be set using the 363 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 364 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 365 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 366 * {@link #getPaddingEnd()}. 367 * </p> 368 * 369 * <p> 370 * Even though a view can define a padding, it does not provide any support for 371 * margins. However, view groups provide such a support. Refer to 372 * {@link android.view.ViewGroup} and 373 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 374 * </p> 375 * 376 * <a name="Layout"></a> 377 * <h3>Layout</h3> 378 * <p> 379 * Layout is a two pass process: a measure pass and a layout pass. The measuring 380 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 381 * of the view tree. Each view pushes dimension specifications down the tree 382 * during the recursion. At the end of the measure pass, every view has stored 383 * its measurements. The second pass happens in 384 * {@link #layout(int,int,int,int)} and is also top-down. During 385 * this pass each parent is responsible for positioning all of its children 386 * using the sizes computed in the measure pass. 387 * </p> 388 * 389 * <p> 390 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 391 * {@link #getMeasuredHeight()} values must be set, along with those for all of 392 * that view's descendants. A view's measured width and measured height values 393 * must respect the constraints imposed by the view's parents. This guarantees 394 * that at the end of the measure pass, all parents accept all of their 395 * children's measurements. A parent view may call measure() more than once on 396 * its children. For example, the parent may measure each child once with 397 * unspecified dimensions to find out how big they want to be, then call 398 * measure() on them again with actual numbers if the sum of all the children's 399 * unconstrained sizes is too big or too small. 400 * </p> 401 * 402 * <p> 403 * The measure pass uses two classes to communicate dimensions. The 404 * {@link MeasureSpec} class is used by views to tell their parents how they 405 * want to be measured and positioned. The base LayoutParams class just 406 * describes how big the view wants to be for both width and height. For each 407 * dimension, it can specify one of: 408 * <ul> 409 * <li> an exact number 410 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 411 * (minus padding) 412 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 413 * enclose its content (plus padding). 414 * </ul> 415 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 416 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 417 * an X and Y value. 418 * </p> 419 * 420 * <p> 421 * MeasureSpecs are used to push requirements down the tree from parent to 422 * child. A MeasureSpec can be in one of three modes: 423 * <ul> 424 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 425 * of a child view. For example, a LinearLayout may call measure() on its child 426 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 427 * tall the child view wants to be given a width of 240 pixels. 428 * <li>EXACTLY: This is used by the parent to impose an exact size on the 429 * child. The child must use this size, and guarantee that all of its 430 * descendants will fit within this size. 431 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 432 * child. The child must gurantee that it and all of its descendants will fit 433 * within this size. 434 * </ul> 435 * </p> 436 * 437 * <p> 438 * To intiate a layout, call {@link #requestLayout}. This method is typically 439 * called by a view on itself when it believes that is can no longer fit within 440 * its current bounds. 441 * </p> 442 * 443 * <a name="Drawing"></a> 444 * <h3>Drawing</h3> 445 * <p> 446 * Drawing is handled by walking the tree and rendering each view that 447 * intersects the invalid region. Because the tree is traversed in-order, 448 * this means that parents will draw before (i.e., behind) their children, with 449 * siblings drawn in the order they appear in the tree. 450 * If you set a background drawable for a View, then the View will draw it for you 451 * before calling back to its <code>onDraw()</code> method. 452 * </p> 453 * 454 * <p> 455 * Note that the framework will not draw views that are not in the invalid region. 456 * </p> 457 * 458 * <p> 459 * To force a view to draw, call {@link #invalidate()}. 460 * </p> 461 * 462 * <a name="EventHandlingThreading"></a> 463 * <h3>Event Handling and Threading</h3> 464 * <p> 465 * The basic cycle of a view is as follows: 466 * <ol> 467 * <li>An event comes in and is dispatched to the appropriate view. The view 468 * handles the event and notifies any listeners.</li> 469 * <li>If in the course of processing the event, the view's bounds may need 470 * to be changed, the view will call {@link #requestLayout()}.</li> 471 * <li>Similarly, if in the course of processing the event the view's appearance 472 * may need to be changed, the view will call {@link #invalidate()}.</li> 473 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 474 * the framework will take care of measuring, laying out, and drawing the tree 475 * as appropriate.</li> 476 * </ol> 477 * </p> 478 * 479 * <p><em>Note: The entire view tree is single threaded. You must always be on 480 * the UI thread when calling any method on any view.</em> 481 * If you are doing work on other threads and want to update the state of a view 482 * from that thread, you should use a {@link Handler}. 483 * </p> 484 * 485 * <a name="FocusHandling"></a> 486 * <h3>Focus Handling</h3> 487 * <p> 488 * The framework will handle routine focus movement in response to user input. 489 * This includes changing the focus as views are removed or hidden, or as new 490 * views become available. Views indicate their willingness to take focus 491 * through the {@link #isFocusable} method. To change whether a view can take 492 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 493 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 494 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 495 * </p> 496 * <p> 497 * Focus movement is based on an algorithm which finds the nearest neighbor in a 498 * given direction. In rare cases, the default algorithm may not match the 499 * intended behavior of the developer. In these situations, you can provide 500 * explicit overrides by using these XML attributes in the layout file: 501 * <pre> 502 * nextFocusDown 503 * nextFocusLeft 504 * nextFocusRight 505 * nextFocusUp 506 * </pre> 507 * </p> 508 * 509 * 510 * <p> 511 * To get a particular view to take focus, call {@link #requestFocus()}. 512 * </p> 513 * 514 * <a name="TouchMode"></a> 515 * <h3>Touch Mode</h3> 516 * <p> 517 * When a user is navigating a user interface via directional keys such as a D-pad, it is 518 * necessary to give focus to actionable items such as buttons so the user can see 519 * what will take input. If the device has touch capabilities, however, and the user 520 * begins interacting with the interface by touching it, it is no longer necessary to 521 * always highlight, or give focus to, a particular view. This motivates a mode 522 * for interaction named 'touch mode'. 523 * </p> 524 * <p> 525 * For a touch capable device, once the user touches the screen, the device 526 * will enter touch mode. From this point onward, only views for which 527 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 528 * Other views that are touchable, like buttons, will not take focus when touched; they will 529 * only fire the on click listeners. 530 * </p> 531 * <p> 532 * Any time a user hits a directional key, such as a D-pad direction, the view device will 533 * exit touch mode, and find a view to take focus, so that the user may resume interacting 534 * with the user interface without touching the screen again. 535 * </p> 536 * <p> 537 * The touch mode state is maintained across {@link android.app.Activity}s. Call 538 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 539 * </p> 540 * 541 * <a name="Scrolling"></a> 542 * <h3>Scrolling</h3> 543 * <p> 544 * The framework provides basic support for views that wish to internally 545 * scroll their content. This includes keeping track of the X and Y scroll 546 * offset as well as mechanisms for drawing scrollbars. See 547 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 548 * {@link #awakenScrollBars()} for more details. 549 * </p> 550 * 551 * <a name="Tags"></a> 552 * <h3>Tags</h3> 553 * <p> 554 * Unlike IDs, tags are not used to identify views. Tags are essentially an 555 * extra piece of information that can be associated with a view. They are most 556 * often used as a convenience to store data related to views in the views 557 * themselves rather than by putting them in a separate structure. 558 * </p> 559 * 560 * <a name="Properties"></a> 561 * <h3>Properties</h3> 562 * <p> 563 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 564 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 565 * available both in the {@link Property} form as well as in similarly-named setter/getter 566 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 567 * be used to set persistent state associated with these rendering-related properties on the view. 568 * The properties and methods can also be used in conjunction with 569 * {@link android.animation.Animator Animator}-based animations, described more in the 570 * <a href="#Animation">Animation</a> section. 571 * </p> 572 * 573 * <a name="Animation"></a> 574 * <h3>Animation</h3> 575 * <p> 576 * Starting with Android 3.0, the preferred way of animating views is to use the 577 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 578 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 579 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 580 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 581 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 582 * makes animating these View properties particularly easy and efficient. 583 * </p> 584 * <p> 585 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 586 * You can attach an {@link Animation} object to a view using 587 * {@link #setAnimation(Animation)} or 588 * {@link #startAnimation(Animation)}. The animation can alter the scale, 589 * rotation, translation and alpha of a view over time. If the animation is 590 * attached to a view that has children, the animation will affect the entire 591 * subtree rooted by that node. When an animation is started, the framework will 592 * take care of redrawing the appropriate views until the animation completes. 593 * </p> 594 * 595 * <a name="Security"></a> 596 * <h3>Security</h3> 597 * <p> 598 * Sometimes it is essential that an application be able to verify that an action 599 * is being performed with the full knowledge and consent of the user, such as 600 * granting a permission request, making a purchase or clicking on an advertisement. 601 * Unfortunately, a malicious application could try to spoof the user into 602 * performing these actions, unaware, by concealing the intended purpose of the view. 603 * As a remedy, the framework offers a touch filtering mechanism that can be used to 604 * improve the security of views that provide access to sensitive functionality. 605 * </p><p> 606 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 607 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 608 * will discard touches that are received whenever the view's window is obscured by 609 * another visible window. As a result, the view will not receive touches whenever a 610 * toast, dialog or other window appears above the view's window. 611 * </p><p> 612 * For more fine-grained control over security, consider overriding the 613 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 614 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 615 * </p> 616 * 617 * @attr ref android.R.styleable#View_alpha 618 * @attr ref android.R.styleable#View_background 619 * @attr ref android.R.styleable#View_clickable 620 * @attr ref android.R.styleable#View_contentDescription 621 * @attr ref android.R.styleable#View_drawingCacheQuality 622 * @attr ref android.R.styleable#View_duplicateParentState 623 * @attr ref android.R.styleable#View_id 624 * @attr ref android.R.styleable#View_requiresFadingEdge 625 * @attr ref android.R.styleable#View_fadeScrollbars 626 * @attr ref android.R.styleable#View_fadingEdgeLength 627 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 628 * @attr ref android.R.styleable#View_fitsSystemWindows 629 * @attr ref android.R.styleable#View_isScrollContainer 630 * @attr ref android.R.styleable#View_focusable 631 * @attr ref android.R.styleable#View_focusableInTouchMode 632 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 633 * @attr ref android.R.styleable#View_keepScreenOn 634 * @attr ref android.R.styleable#View_layerType 635 * @attr ref android.R.styleable#View_layoutDirection 636 * @attr ref android.R.styleable#View_longClickable 637 * @attr ref android.R.styleable#View_minHeight 638 * @attr ref android.R.styleable#View_minWidth 639 * @attr ref android.R.styleable#View_nextFocusDown 640 * @attr ref android.R.styleable#View_nextFocusLeft 641 * @attr ref android.R.styleable#View_nextFocusRight 642 * @attr ref android.R.styleable#View_nextFocusUp 643 * @attr ref android.R.styleable#View_onClick 644 * @attr ref android.R.styleable#View_padding 645 * @attr ref android.R.styleable#View_paddingBottom 646 * @attr ref android.R.styleable#View_paddingLeft 647 * @attr ref android.R.styleable#View_paddingRight 648 * @attr ref android.R.styleable#View_paddingTop 649 * @attr ref android.R.styleable#View_paddingStart 650 * @attr ref android.R.styleable#View_paddingEnd 651 * @attr ref android.R.styleable#View_saveEnabled 652 * @attr ref android.R.styleable#View_rotation 653 * @attr ref android.R.styleable#View_rotationX 654 * @attr ref android.R.styleable#View_rotationY 655 * @attr ref android.R.styleable#View_scaleX 656 * @attr ref android.R.styleable#View_scaleY 657 * @attr ref android.R.styleable#View_scrollX 658 * @attr ref android.R.styleable#View_scrollY 659 * @attr ref android.R.styleable#View_scrollbarSize 660 * @attr ref android.R.styleable#View_scrollbarStyle 661 * @attr ref android.R.styleable#View_scrollbars 662 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 663 * @attr ref android.R.styleable#View_scrollbarFadeDuration 664 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 665 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 666 * @attr ref android.R.styleable#View_scrollbarThumbVertical 667 * @attr ref android.R.styleable#View_scrollbarTrackVertical 668 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 669 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 670 * @attr ref android.R.styleable#View_sharedElementName 671 * @attr ref android.R.styleable#View_soundEffectsEnabled 672 * @attr ref android.R.styleable#View_tag 673 * @attr ref android.R.styleable#View_textAlignment 674 * @attr ref android.R.styleable#View_textDirection 675 * @attr ref android.R.styleable#View_transformPivotX 676 * @attr ref android.R.styleable#View_transformPivotY 677 * @attr ref android.R.styleable#View_translationX 678 * @attr ref android.R.styleable#View_translationY 679 * @attr ref android.R.styleable#View_translationZ 680 * @attr ref android.R.styleable#View_visibility 681 * 682 * @see android.view.ViewGroup 683 */ 684public class View implements Drawable.Callback, KeyEvent.Callback, 685 AccessibilityEventSource { 686 private static final boolean DBG = false; 687 688 /** 689 * The logging tag used by this class with android.util.Log. 690 */ 691 protected static final String VIEW_LOG_TAG = "View"; 692 693 /** 694 * When set to true, apps will draw debugging information about their layouts. 695 * 696 * @hide 697 */ 698 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 699 700 /** 701 * Used to mark a View that has no ID. 702 */ 703 public static final int NO_ID = -1; 704 705 /** 706 * Signals that compatibility booleans have been initialized according to 707 * target SDK versions. 708 */ 709 private static boolean sCompatibilityDone = false; 710 711 /** 712 * Use the old (broken) way of building MeasureSpecs. 713 */ 714 private static boolean sUseBrokenMakeMeasureSpec = false; 715 716 /** 717 * Ignore any optimizations using the measure cache. 718 */ 719 private static boolean sIgnoreMeasureCache = false; 720 721 /** 722 * Ignore the clipBounds of this view for the children. 723 */ 724 static boolean sIgnoreClipBoundsForChildren = false; 725 726 /** 727 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 728 * calling setFlags. 729 */ 730 private static final int NOT_FOCUSABLE = 0x00000000; 731 732 /** 733 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 734 * setFlags. 735 */ 736 private static final int FOCUSABLE = 0x00000001; 737 738 /** 739 * Mask for use with setFlags indicating bits used for focus. 740 */ 741 private static final int FOCUSABLE_MASK = 0x00000001; 742 743 /** 744 * This view will adjust its padding to fit sytem windows (e.g. status bar) 745 */ 746 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 747 748 /** @hide */ 749 @IntDef({VISIBLE, INVISIBLE, GONE}) 750 @Retention(RetentionPolicy.SOURCE) 751 public @interface Visibility {} 752 753 /** 754 * This view is visible. 755 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 756 * android:visibility}. 757 */ 758 public static final int VISIBLE = 0x00000000; 759 760 /** 761 * This view is invisible, but it still takes up space for layout purposes. 762 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 763 * android:visibility}. 764 */ 765 public static final int INVISIBLE = 0x00000004; 766 767 /** 768 * This view is invisible, and it doesn't take any space for layout 769 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 770 * android:visibility}. 771 */ 772 public static final int GONE = 0x00000008; 773 774 /** 775 * Mask for use with setFlags indicating bits used for visibility. 776 * {@hide} 777 */ 778 static final int VISIBILITY_MASK = 0x0000000C; 779 780 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 781 782 /** 783 * This view is enabled. Interpretation varies by subclass. 784 * Use with ENABLED_MASK when calling setFlags. 785 * {@hide} 786 */ 787 static final int ENABLED = 0x00000000; 788 789 /** 790 * This view is disabled. Interpretation varies by subclass. 791 * Use with ENABLED_MASK when calling setFlags. 792 * {@hide} 793 */ 794 static final int DISABLED = 0x00000020; 795 796 /** 797 * Mask for use with setFlags indicating bits used for indicating whether 798 * this view is enabled 799 * {@hide} 800 */ 801 static final int ENABLED_MASK = 0x00000020; 802 803 /** 804 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 805 * called and further optimizations will be performed. It is okay to have 806 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 807 * {@hide} 808 */ 809 static final int WILL_NOT_DRAW = 0x00000080; 810 811 /** 812 * Mask for use with setFlags indicating bits used for indicating whether 813 * this view is will draw 814 * {@hide} 815 */ 816 static final int DRAW_MASK = 0x00000080; 817 818 /** 819 * <p>This view doesn't show scrollbars.</p> 820 * {@hide} 821 */ 822 static final int SCROLLBARS_NONE = 0x00000000; 823 824 /** 825 * <p>This view shows horizontal scrollbars.</p> 826 * {@hide} 827 */ 828 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 829 830 /** 831 * <p>This view shows vertical scrollbars.</p> 832 * {@hide} 833 */ 834 static final int SCROLLBARS_VERTICAL = 0x00000200; 835 836 /** 837 * <p>Mask for use with setFlags indicating bits used for indicating which 838 * scrollbars are enabled.</p> 839 * {@hide} 840 */ 841 static final int SCROLLBARS_MASK = 0x00000300; 842 843 /** 844 * Indicates that the view should filter touches when its window is obscured. 845 * Refer to the class comments for more information about this security feature. 846 * {@hide} 847 */ 848 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 849 850 /** 851 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 852 * that they are optional and should be skipped if the window has 853 * requested system UI flags that ignore those insets for layout. 854 */ 855 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 856 857 /** 858 * <p>This view doesn't show fading edges.</p> 859 * {@hide} 860 */ 861 static final int FADING_EDGE_NONE = 0x00000000; 862 863 /** 864 * <p>This view shows horizontal fading edges.</p> 865 * {@hide} 866 */ 867 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 868 869 /** 870 * <p>This view shows vertical fading edges.</p> 871 * {@hide} 872 */ 873 static final int FADING_EDGE_VERTICAL = 0x00002000; 874 875 /** 876 * <p>Mask for use with setFlags indicating bits used for indicating which 877 * fading edges are enabled.</p> 878 * {@hide} 879 */ 880 static final int FADING_EDGE_MASK = 0x00003000; 881 882 /** 883 * <p>Indicates this view can be clicked. When clickable, a View reacts 884 * to clicks by notifying the OnClickListener.<p> 885 * {@hide} 886 */ 887 static final int CLICKABLE = 0x00004000; 888 889 /** 890 * <p>Indicates this view is caching its drawing into a bitmap.</p> 891 * {@hide} 892 */ 893 static final int DRAWING_CACHE_ENABLED = 0x00008000; 894 895 /** 896 * <p>Indicates that no icicle should be saved for this view.<p> 897 * {@hide} 898 */ 899 static final int SAVE_DISABLED = 0x000010000; 900 901 /** 902 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 903 * property.</p> 904 * {@hide} 905 */ 906 static final int SAVE_DISABLED_MASK = 0x000010000; 907 908 /** 909 * <p>Indicates that no drawing cache should ever be created for this view.<p> 910 * {@hide} 911 */ 912 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 913 914 /** 915 * <p>Indicates this view can take / keep focus when int touch mode.</p> 916 * {@hide} 917 */ 918 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 919 920 /** @hide */ 921 @Retention(RetentionPolicy.SOURCE) 922 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 923 public @interface DrawingCacheQuality {} 924 925 /** 926 * <p>Enables low quality mode for the drawing cache.</p> 927 */ 928 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 929 930 /** 931 * <p>Enables high quality mode for the drawing cache.</p> 932 */ 933 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 934 935 /** 936 * <p>Enables automatic quality mode for the drawing cache.</p> 937 */ 938 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 939 940 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 941 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 942 }; 943 944 /** 945 * <p>Mask for use with setFlags indicating bits used for the cache 946 * quality property.</p> 947 * {@hide} 948 */ 949 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 950 951 /** 952 * <p> 953 * Indicates this view can be long clicked. When long clickable, a View 954 * reacts to long clicks by notifying the OnLongClickListener or showing a 955 * context menu. 956 * </p> 957 * {@hide} 958 */ 959 static final int LONG_CLICKABLE = 0x00200000; 960 961 /** 962 * <p>Indicates that this view gets its drawable states from its direct parent 963 * and ignores its original internal states.</p> 964 * 965 * @hide 966 */ 967 static final int DUPLICATE_PARENT_STATE = 0x00400000; 968 969 /** @hide */ 970 @IntDef({ 971 SCROLLBARS_INSIDE_OVERLAY, 972 SCROLLBARS_INSIDE_INSET, 973 SCROLLBARS_OUTSIDE_OVERLAY, 974 SCROLLBARS_OUTSIDE_INSET 975 }) 976 @Retention(RetentionPolicy.SOURCE) 977 public @interface ScrollBarStyle {} 978 979 /** 980 * The scrollbar style to display the scrollbars inside the content area, 981 * without increasing the padding. The scrollbars will be overlaid with 982 * translucency on the view's content. 983 */ 984 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 985 986 /** 987 * The scrollbar style to display the scrollbars inside the padded area, 988 * increasing the padding of the view. The scrollbars will not overlap the 989 * content area of the view. 990 */ 991 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 992 993 /** 994 * The scrollbar style to display the scrollbars at the edge of the view, 995 * without increasing the padding. The scrollbars will be overlaid with 996 * translucency. 997 */ 998 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 999 1000 /** 1001 * The scrollbar style to display the scrollbars at the edge of the view, 1002 * increasing the padding of the view. The scrollbars will only overlap the 1003 * background, if any. 1004 */ 1005 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1006 1007 /** 1008 * Mask to check if the scrollbar style is overlay or inset. 1009 * {@hide} 1010 */ 1011 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1012 1013 /** 1014 * Mask to check if the scrollbar style is inside or outside. 1015 * {@hide} 1016 */ 1017 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1018 1019 /** 1020 * Mask for scrollbar style. 1021 * {@hide} 1022 */ 1023 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1024 1025 /** 1026 * View flag indicating that the screen should remain on while the 1027 * window containing this view is visible to the user. This effectively 1028 * takes care of automatically setting the WindowManager's 1029 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1030 */ 1031 public static final int KEEP_SCREEN_ON = 0x04000000; 1032 1033 /** 1034 * View flag indicating whether this view should have sound effects enabled 1035 * for events such as clicking and touching. 1036 */ 1037 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1038 1039 /** 1040 * View flag indicating whether this view should have haptic feedback 1041 * enabled for events such as long presses. 1042 */ 1043 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1044 1045 /** 1046 * <p>Indicates that the view hierarchy should stop saving state when 1047 * it reaches this view. If state saving is initiated immediately at 1048 * the view, it will be allowed. 1049 * {@hide} 1050 */ 1051 static final int PARENT_SAVE_DISABLED = 0x20000000; 1052 1053 /** 1054 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1055 * {@hide} 1056 */ 1057 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1058 1059 /** @hide */ 1060 @IntDef(flag = true, 1061 value = { 1062 FOCUSABLES_ALL, 1063 FOCUSABLES_TOUCH_MODE 1064 }) 1065 @Retention(RetentionPolicy.SOURCE) 1066 public @interface FocusableMode {} 1067 1068 /** 1069 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1070 * should add all focusable Views regardless if they are focusable in touch mode. 1071 */ 1072 public static final int FOCUSABLES_ALL = 0x00000000; 1073 1074 /** 1075 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1076 * should add only Views focusable in touch mode. 1077 */ 1078 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1079 1080 /** @hide */ 1081 @IntDef({ 1082 FOCUS_BACKWARD, 1083 FOCUS_FORWARD, 1084 FOCUS_LEFT, 1085 FOCUS_UP, 1086 FOCUS_RIGHT, 1087 FOCUS_DOWN 1088 }) 1089 @Retention(RetentionPolicy.SOURCE) 1090 public @interface FocusDirection {} 1091 1092 /** @hide */ 1093 @IntDef({ 1094 FOCUS_LEFT, 1095 FOCUS_UP, 1096 FOCUS_RIGHT, 1097 FOCUS_DOWN 1098 }) 1099 @Retention(RetentionPolicy.SOURCE) 1100 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1101 1102 /** 1103 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1104 * item. 1105 */ 1106 public static final int FOCUS_BACKWARD = 0x00000001; 1107 1108 /** 1109 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1110 * item. 1111 */ 1112 public static final int FOCUS_FORWARD = 0x00000002; 1113 1114 /** 1115 * Use with {@link #focusSearch(int)}. Move focus to the left. 1116 */ 1117 public static final int FOCUS_LEFT = 0x00000011; 1118 1119 /** 1120 * Use with {@link #focusSearch(int)}. Move focus up. 1121 */ 1122 public static final int FOCUS_UP = 0x00000021; 1123 1124 /** 1125 * Use with {@link #focusSearch(int)}. Move focus to the right. 1126 */ 1127 public static final int FOCUS_RIGHT = 0x00000042; 1128 1129 /** 1130 * Use with {@link #focusSearch(int)}. Move focus down. 1131 */ 1132 public static final int FOCUS_DOWN = 0x00000082; 1133 1134 /** 1135 * Bits of {@link #getMeasuredWidthAndState()} and 1136 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1137 */ 1138 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1139 1140 /** 1141 * Bits of {@link #getMeasuredWidthAndState()} and 1142 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1143 */ 1144 public static final int MEASURED_STATE_MASK = 0xff000000; 1145 1146 /** 1147 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1148 * for functions that combine both width and height into a single int, 1149 * such as {@link #getMeasuredState()} and the childState argument of 1150 * {@link #resolveSizeAndState(int, int, int)}. 1151 */ 1152 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1153 1154 /** 1155 * Bit of {@link #getMeasuredWidthAndState()} and 1156 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1157 * is smaller that the space the view would like to have. 1158 */ 1159 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1160 1161 /** 1162 * Base View state sets 1163 */ 1164 // Singles 1165 /** 1166 * Indicates the view has no states set. States are used with 1167 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1168 * view depending on its state. 1169 * 1170 * @see android.graphics.drawable.Drawable 1171 * @see #getDrawableState() 1172 */ 1173 protected static final int[] EMPTY_STATE_SET; 1174 /** 1175 * Indicates the view is enabled. States are used with 1176 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1177 * view depending on its state. 1178 * 1179 * @see android.graphics.drawable.Drawable 1180 * @see #getDrawableState() 1181 */ 1182 protected static final int[] ENABLED_STATE_SET; 1183 /** 1184 * Indicates the view is focused. States are used with 1185 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1186 * view depending on its state. 1187 * 1188 * @see android.graphics.drawable.Drawable 1189 * @see #getDrawableState() 1190 */ 1191 protected static final int[] FOCUSED_STATE_SET; 1192 /** 1193 * Indicates the view is selected. States are used with 1194 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1195 * view depending on its state. 1196 * 1197 * @see android.graphics.drawable.Drawable 1198 * @see #getDrawableState() 1199 */ 1200 protected static final int[] SELECTED_STATE_SET; 1201 /** 1202 * Indicates the view is pressed. States are used with 1203 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1204 * view depending on its state. 1205 * 1206 * @see android.graphics.drawable.Drawable 1207 * @see #getDrawableState() 1208 */ 1209 protected static final int[] PRESSED_STATE_SET; 1210 /** 1211 * Indicates the view's window has focus. States are used with 1212 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1213 * view depending on its state. 1214 * 1215 * @see android.graphics.drawable.Drawable 1216 * @see #getDrawableState() 1217 */ 1218 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1219 // Doubles 1220 /** 1221 * Indicates the view is enabled and has the focus. 1222 * 1223 * @see #ENABLED_STATE_SET 1224 * @see #FOCUSED_STATE_SET 1225 */ 1226 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1227 /** 1228 * Indicates the view is enabled and selected. 1229 * 1230 * @see #ENABLED_STATE_SET 1231 * @see #SELECTED_STATE_SET 1232 */ 1233 protected static final int[] ENABLED_SELECTED_STATE_SET; 1234 /** 1235 * Indicates the view is enabled and that its window has focus. 1236 * 1237 * @see #ENABLED_STATE_SET 1238 * @see #WINDOW_FOCUSED_STATE_SET 1239 */ 1240 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1241 /** 1242 * Indicates the view is focused and selected. 1243 * 1244 * @see #FOCUSED_STATE_SET 1245 * @see #SELECTED_STATE_SET 1246 */ 1247 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1248 /** 1249 * Indicates the view has the focus and that its window has the focus. 1250 * 1251 * @see #FOCUSED_STATE_SET 1252 * @see #WINDOW_FOCUSED_STATE_SET 1253 */ 1254 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1255 /** 1256 * Indicates the view is selected and that its window has the focus. 1257 * 1258 * @see #SELECTED_STATE_SET 1259 * @see #WINDOW_FOCUSED_STATE_SET 1260 */ 1261 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1262 // Triples 1263 /** 1264 * Indicates the view is enabled, focused and selected. 1265 * 1266 * @see #ENABLED_STATE_SET 1267 * @see #FOCUSED_STATE_SET 1268 * @see #SELECTED_STATE_SET 1269 */ 1270 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1271 /** 1272 * Indicates the view is enabled, focused and its window has the focus. 1273 * 1274 * @see #ENABLED_STATE_SET 1275 * @see #FOCUSED_STATE_SET 1276 * @see #WINDOW_FOCUSED_STATE_SET 1277 */ 1278 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1279 /** 1280 * Indicates the view is enabled, selected and its window has the focus. 1281 * 1282 * @see #ENABLED_STATE_SET 1283 * @see #SELECTED_STATE_SET 1284 * @see #WINDOW_FOCUSED_STATE_SET 1285 */ 1286 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1287 /** 1288 * Indicates the view is focused, selected and its window has the focus. 1289 * 1290 * @see #FOCUSED_STATE_SET 1291 * @see #SELECTED_STATE_SET 1292 * @see #WINDOW_FOCUSED_STATE_SET 1293 */ 1294 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1295 /** 1296 * Indicates the view is enabled, focused, selected and its window 1297 * has the focus. 1298 * 1299 * @see #ENABLED_STATE_SET 1300 * @see #FOCUSED_STATE_SET 1301 * @see #SELECTED_STATE_SET 1302 * @see #WINDOW_FOCUSED_STATE_SET 1303 */ 1304 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1305 /** 1306 * Indicates the view is pressed and its window has the focus. 1307 * 1308 * @see #PRESSED_STATE_SET 1309 * @see #WINDOW_FOCUSED_STATE_SET 1310 */ 1311 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1312 /** 1313 * Indicates the view is pressed and selected. 1314 * 1315 * @see #PRESSED_STATE_SET 1316 * @see #SELECTED_STATE_SET 1317 */ 1318 protected static final int[] PRESSED_SELECTED_STATE_SET; 1319 /** 1320 * Indicates the view is pressed, selected and its window has the focus. 1321 * 1322 * @see #PRESSED_STATE_SET 1323 * @see #SELECTED_STATE_SET 1324 * @see #WINDOW_FOCUSED_STATE_SET 1325 */ 1326 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1327 /** 1328 * Indicates the view is pressed and focused. 1329 * 1330 * @see #PRESSED_STATE_SET 1331 * @see #FOCUSED_STATE_SET 1332 */ 1333 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1334 /** 1335 * Indicates the view is pressed, focused and its window has the focus. 1336 * 1337 * @see #PRESSED_STATE_SET 1338 * @see #FOCUSED_STATE_SET 1339 * @see #WINDOW_FOCUSED_STATE_SET 1340 */ 1341 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1342 /** 1343 * Indicates the view is pressed, focused and selected. 1344 * 1345 * @see #PRESSED_STATE_SET 1346 * @see #SELECTED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 */ 1349 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1350 /** 1351 * Indicates the view is pressed, focused, selected and its window has the focus. 1352 * 1353 * @see #PRESSED_STATE_SET 1354 * @see #FOCUSED_STATE_SET 1355 * @see #SELECTED_STATE_SET 1356 * @see #WINDOW_FOCUSED_STATE_SET 1357 */ 1358 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1359 /** 1360 * Indicates the view is pressed and enabled. 1361 * 1362 * @see #PRESSED_STATE_SET 1363 * @see #ENABLED_STATE_SET 1364 */ 1365 protected static final int[] PRESSED_ENABLED_STATE_SET; 1366 /** 1367 * Indicates the view is pressed, enabled and its window has the focus. 1368 * 1369 * @see #PRESSED_STATE_SET 1370 * @see #ENABLED_STATE_SET 1371 * @see #WINDOW_FOCUSED_STATE_SET 1372 */ 1373 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1374 /** 1375 * Indicates the view is pressed, enabled and selected. 1376 * 1377 * @see #PRESSED_STATE_SET 1378 * @see #ENABLED_STATE_SET 1379 * @see #SELECTED_STATE_SET 1380 */ 1381 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1382 /** 1383 * Indicates the view is pressed, enabled, selected and its window has the 1384 * focus. 1385 * 1386 * @see #PRESSED_STATE_SET 1387 * @see #ENABLED_STATE_SET 1388 * @see #SELECTED_STATE_SET 1389 * @see #WINDOW_FOCUSED_STATE_SET 1390 */ 1391 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1392 /** 1393 * Indicates the view is pressed, enabled and focused. 1394 * 1395 * @see #PRESSED_STATE_SET 1396 * @see #ENABLED_STATE_SET 1397 * @see #FOCUSED_STATE_SET 1398 */ 1399 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1400 /** 1401 * Indicates the view is pressed, enabled, focused and its window has the 1402 * focus. 1403 * 1404 * @see #PRESSED_STATE_SET 1405 * @see #ENABLED_STATE_SET 1406 * @see #FOCUSED_STATE_SET 1407 * @see #WINDOW_FOCUSED_STATE_SET 1408 */ 1409 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1410 /** 1411 * Indicates the view is pressed, enabled, focused and selected. 1412 * 1413 * @see #PRESSED_STATE_SET 1414 * @see #ENABLED_STATE_SET 1415 * @see #SELECTED_STATE_SET 1416 * @see #FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1419 /** 1420 * Indicates the view is pressed, enabled, focused, selected and its window 1421 * has the focus. 1422 * 1423 * @see #PRESSED_STATE_SET 1424 * @see #ENABLED_STATE_SET 1425 * @see #SELECTED_STATE_SET 1426 * @see #FOCUSED_STATE_SET 1427 * @see #WINDOW_FOCUSED_STATE_SET 1428 */ 1429 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1430 1431 /** 1432 * The order here is very important to {@link #getDrawableState()} 1433 */ 1434 private static final int[][] VIEW_STATE_SETS; 1435 1436 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1437 static final int VIEW_STATE_SELECTED = 1 << 1; 1438 static final int VIEW_STATE_FOCUSED = 1 << 2; 1439 static final int VIEW_STATE_ENABLED = 1 << 3; 1440 static final int VIEW_STATE_PRESSED = 1 << 4; 1441 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1442 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1443 static final int VIEW_STATE_HOVERED = 1 << 7; 1444 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1445 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1446 1447 static final int[] VIEW_STATE_IDS = new int[] { 1448 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1449 R.attr.state_selected, VIEW_STATE_SELECTED, 1450 R.attr.state_focused, VIEW_STATE_FOCUSED, 1451 R.attr.state_enabled, VIEW_STATE_ENABLED, 1452 R.attr.state_pressed, VIEW_STATE_PRESSED, 1453 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1454 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1455 R.attr.state_hovered, VIEW_STATE_HOVERED, 1456 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1457 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1458 }; 1459 1460 static { 1461 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1462 throw new IllegalStateException( 1463 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1464 } 1465 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1466 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1467 int viewState = R.styleable.ViewDrawableStates[i]; 1468 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1469 if (VIEW_STATE_IDS[j] == viewState) { 1470 orderedIds[i * 2] = viewState; 1471 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1472 } 1473 } 1474 } 1475 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1476 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1477 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1478 int numBits = Integer.bitCount(i); 1479 int[] set = new int[numBits]; 1480 int pos = 0; 1481 for (int j = 0; j < orderedIds.length; j += 2) { 1482 if ((i & orderedIds[j+1]) != 0) { 1483 set[pos++] = orderedIds[j]; 1484 } 1485 } 1486 VIEW_STATE_SETS[i] = set; 1487 } 1488 1489 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1490 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1491 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1492 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1493 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1494 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1495 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1496 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1497 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1498 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1499 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1500 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1501 | VIEW_STATE_FOCUSED]; 1502 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1503 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1504 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1505 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1506 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1507 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1508 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1509 | VIEW_STATE_ENABLED]; 1510 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1511 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1512 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1514 | VIEW_STATE_ENABLED]; 1515 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1516 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1517 | VIEW_STATE_ENABLED]; 1518 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1519 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1520 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1521 1522 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1523 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1524 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1525 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1526 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1527 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1529 | VIEW_STATE_PRESSED]; 1530 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1531 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1532 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1534 | VIEW_STATE_PRESSED]; 1535 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1536 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1537 | VIEW_STATE_PRESSED]; 1538 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1539 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1540 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1541 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1543 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1544 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1545 | VIEW_STATE_PRESSED]; 1546 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1547 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1548 | VIEW_STATE_PRESSED]; 1549 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1550 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1551 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1554 | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1557 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1563 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1564 | VIEW_STATE_PRESSED]; 1565 } 1566 1567 /** 1568 * Accessibility event types that are dispatched for text population. 1569 */ 1570 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1571 AccessibilityEvent.TYPE_VIEW_CLICKED 1572 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1573 | AccessibilityEvent.TYPE_VIEW_SELECTED 1574 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1575 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1576 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1577 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1578 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1579 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1580 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1581 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1582 1583 /** 1584 * Temporary Rect currently for use in setBackground(). This will probably 1585 * be extended in the future to hold our own class with more than just 1586 * a Rect. :) 1587 */ 1588 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1589 1590 /** 1591 * Map used to store views' tags. 1592 */ 1593 private SparseArray<Object> mKeyedTags; 1594 1595 /** 1596 * The next available accessibility id. 1597 */ 1598 private static int sNextAccessibilityViewId; 1599 1600 /** 1601 * The animation currently associated with this view. 1602 * @hide 1603 */ 1604 protected Animation mCurrentAnimation = null; 1605 1606 /** 1607 * Width as measured during measure pass. 1608 * {@hide} 1609 */ 1610 @ViewDebug.ExportedProperty(category = "measurement") 1611 int mMeasuredWidth; 1612 1613 /** 1614 * Height as measured during measure pass. 1615 * {@hide} 1616 */ 1617 @ViewDebug.ExportedProperty(category = "measurement") 1618 int mMeasuredHeight; 1619 1620 /** 1621 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1622 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1623 * its display list. This flag, used only when hw accelerated, allows us to clear the 1624 * flag while retaining this information until it's needed (at getDisplayList() time and 1625 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1626 * 1627 * {@hide} 1628 */ 1629 boolean mRecreateDisplayList = false; 1630 1631 /** 1632 * The view's identifier. 1633 * {@hide} 1634 * 1635 * @see #setId(int) 1636 * @see #getId() 1637 */ 1638 @ViewDebug.ExportedProperty(resolveId = true) 1639 int mID = NO_ID; 1640 1641 /** 1642 * The stable ID of this view for accessibility purposes. 1643 */ 1644 int mAccessibilityViewId = NO_ID; 1645 1646 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1647 1648 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1649 1650 /** 1651 * The view's tag. 1652 * {@hide} 1653 * 1654 * @see #setTag(Object) 1655 * @see #getTag() 1656 */ 1657 protected Object mTag = null; 1658 1659 // for mPrivateFlags: 1660 /** {@hide} */ 1661 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1662 /** {@hide} */ 1663 static final int PFLAG_FOCUSED = 0x00000002; 1664 /** {@hide} */ 1665 static final int PFLAG_SELECTED = 0x00000004; 1666 /** {@hide} */ 1667 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1668 /** {@hide} */ 1669 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1670 /** {@hide} */ 1671 static final int PFLAG_DRAWN = 0x00000020; 1672 /** 1673 * When this flag is set, this view is running an animation on behalf of its 1674 * children and should therefore not cancel invalidate requests, even if they 1675 * lie outside of this view's bounds. 1676 * 1677 * {@hide} 1678 */ 1679 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1680 /** {@hide} */ 1681 static final int PFLAG_SKIP_DRAW = 0x00000080; 1682 /** {@hide} */ 1683 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1684 /** {@hide} */ 1685 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1686 /** {@hide} */ 1687 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1688 /** {@hide} */ 1689 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1690 /** {@hide} */ 1691 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1692 /** {@hide} */ 1693 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1694 1695 private static final int PFLAG_PRESSED = 0x00004000; 1696 1697 /** {@hide} */ 1698 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1699 /** 1700 * Flag used to indicate that this view should be drawn once more (and only once 1701 * more) after its animation has completed. 1702 * {@hide} 1703 */ 1704 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1705 1706 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1707 1708 /** 1709 * Indicates that the View returned true when onSetAlpha() was called and that 1710 * the alpha must be restored. 1711 * {@hide} 1712 */ 1713 static final int PFLAG_ALPHA_SET = 0x00040000; 1714 1715 /** 1716 * Set by {@link #setScrollContainer(boolean)}. 1717 */ 1718 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1719 1720 /** 1721 * Set by {@link #setScrollContainer(boolean)}. 1722 */ 1723 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1724 1725 /** 1726 * View flag indicating whether this view was invalidated (fully or partially.) 1727 * 1728 * @hide 1729 */ 1730 static final int PFLAG_DIRTY = 0x00200000; 1731 1732 /** 1733 * View flag indicating whether this view was invalidated by an opaque 1734 * invalidate request. 1735 * 1736 * @hide 1737 */ 1738 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1739 1740 /** 1741 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1742 * 1743 * @hide 1744 */ 1745 static final int PFLAG_DIRTY_MASK = 0x00600000; 1746 1747 /** 1748 * Indicates whether the background is opaque. 1749 * 1750 * @hide 1751 */ 1752 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1753 1754 /** 1755 * Indicates whether the scrollbars are opaque. 1756 * 1757 * @hide 1758 */ 1759 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1760 1761 /** 1762 * Indicates whether the view is opaque. 1763 * 1764 * @hide 1765 */ 1766 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1767 1768 /** 1769 * Indicates a prepressed state; 1770 * the short time between ACTION_DOWN and recognizing 1771 * a 'real' press. Prepressed is used to recognize quick taps 1772 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1773 * 1774 * @hide 1775 */ 1776 private static final int PFLAG_PREPRESSED = 0x02000000; 1777 1778 /** 1779 * Indicates whether the view is temporarily detached. 1780 * 1781 * @hide 1782 */ 1783 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1784 1785 /** 1786 * Indicates that we should awaken scroll bars once attached 1787 * 1788 * @hide 1789 */ 1790 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1791 1792 /** 1793 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1794 * @hide 1795 */ 1796 private static final int PFLAG_HOVERED = 0x10000000; 1797 1798 /** 1799 * no longer needed, should be reused 1800 */ 1801 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1802 1803 /** {@hide} */ 1804 static final int PFLAG_ACTIVATED = 0x40000000; 1805 1806 /** 1807 * Indicates that this view was specifically invalidated, not just dirtied because some 1808 * child view was invalidated. The flag is used to determine when we need to recreate 1809 * a view's display list (as opposed to just returning a reference to its existing 1810 * display list). 1811 * 1812 * @hide 1813 */ 1814 static final int PFLAG_INVALIDATED = 0x80000000; 1815 1816 /** 1817 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1818 * 1819 * |-------|-------|-------|-------| 1820 * 1 PFLAG2_DRAG_CAN_ACCEPT 1821 * 1 PFLAG2_DRAG_HOVERED 1822 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1823 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1824 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1825 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1826 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1827 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1828 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1829 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1830 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1831 * 111 PFLAG2_TEXT_DIRECTION_MASK 1832 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1833 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1834 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1835 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1836 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1837 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1838 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1839 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1840 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1841 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1842 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1843 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1844 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1845 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1846 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1847 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1848 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1849 * 1 PFLAG2_VIEW_QUICK_REJECTED 1850 * 1 PFLAG2_PADDING_RESOLVED 1851 * 1 PFLAG2_DRAWABLE_RESOLVED 1852 * 1 PFLAG2_HAS_TRANSIENT_STATE 1853 * |-------|-------|-------|-------| 1854 */ 1855 1856 /** 1857 * Indicates that this view has reported that it can accept the current drag's content. 1858 * Cleared when the drag operation concludes. 1859 * @hide 1860 */ 1861 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1862 1863 /** 1864 * Indicates that this view is currently directly under the drag location in a 1865 * drag-and-drop operation involving content that it can accept. Cleared when 1866 * the drag exits the view, or when the drag operation concludes. 1867 * @hide 1868 */ 1869 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1870 1871 /** @hide */ 1872 @IntDef({ 1873 LAYOUT_DIRECTION_LTR, 1874 LAYOUT_DIRECTION_RTL, 1875 LAYOUT_DIRECTION_INHERIT, 1876 LAYOUT_DIRECTION_LOCALE 1877 }) 1878 @Retention(RetentionPolicy.SOURCE) 1879 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1880 public @interface LayoutDir {} 1881 1882 /** @hide */ 1883 @IntDef({ 1884 LAYOUT_DIRECTION_LTR, 1885 LAYOUT_DIRECTION_RTL 1886 }) 1887 @Retention(RetentionPolicy.SOURCE) 1888 public @interface ResolvedLayoutDir {} 1889 1890 /** 1891 * Horizontal layout direction of this view is from Left to Right. 1892 * Use with {@link #setLayoutDirection}. 1893 */ 1894 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1895 1896 /** 1897 * Horizontal layout direction of this view is from Right to Left. 1898 * Use with {@link #setLayoutDirection}. 1899 */ 1900 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1901 1902 /** 1903 * Horizontal layout direction of this view is inherited from its parent. 1904 * Use with {@link #setLayoutDirection}. 1905 */ 1906 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1907 1908 /** 1909 * Horizontal layout direction of this view is from deduced from the default language 1910 * script for the locale. Use with {@link #setLayoutDirection}. 1911 */ 1912 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1913 1914 /** 1915 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1916 * @hide 1917 */ 1918 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1919 1920 /** 1921 * Mask for use with private flags indicating bits used for horizontal layout direction. 1922 * @hide 1923 */ 1924 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1925 1926 /** 1927 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1928 * right-to-left direction. 1929 * @hide 1930 */ 1931 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1932 1933 /** 1934 * Indicates whether the view horizontal layout direction has been resolved. 1935 * @hide 1936 */ 1937 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1938 1939 /** 1940 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1941 * @hide 1942 */ 1943 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1944 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1945 1946 /* 1947 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1948 * flag value. 1949 * @hide 1950 */ 1951 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1952 LAYOUT_DIRECTION_LTR, 1953 LAYOUT_DIRECTION_RTL, 1954 LAYOUT_DIRECTION_INHERIT, 1955 LAYOUT_DIRECTION_LOCALE 1956 }; 1957 1958 /** 1959 * Default horizontal layout direction. 1960 */ 1961 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1962 1963 /** 1964 * Default horizontal layout direction. 1965 * @hide 1966 */ 1967 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1968 1969 /** 1970 * Text direction is inherited thru {@link ViewGroup} 1971 */ 1972 public static final int TEXT_DIRECTION_INHERIT = 0; 1973 1974 /** 1975 * Text direction is using "first strong algorithm". The first strong directional character 1976 * determines the paragraph direction. If there is no strong directional character, the 1977 * paragraph direction is the view's resolved layout direction. 1978 */ 1979 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1980 1981 /** 1982 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1983 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1984 * If there are neither, the paragraph direction is the view's resolved layout direction. 1985 */ 1986 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1987 1988 /** 1989 * Text direction is forced to LTR. 1990 */ 1991 public static final int TEXT_DIRECTION_LTR = 3; 1992 1993 /** 1994 * Text direction is forced to RTL. 1995 */ 1996 public static final int TEXT_DIRECTION_RTL = 4; 1997 1998 /** 1999 * Text direction is coming from the system Locale. 2000 */ 2001 public static final int TEXT_DIRECTION_LOCALE = 5; 2002 2003 /** 2004 * Default text direction is inherited 2005 */ 2006 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2007 2008 /** 2009 * Default resolved text direction 2010 * @hide 2011 */ 2012 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2013 2014 /** 2015 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2016 * @hide 2017 */ 2018 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2019 2020 /** 2021 * Mask for use with private flags indicating bits used for text direction. 2022 * @hide 2023 */ 2024 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2025 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2026 2027 /** 2028 * Array of text direction flags for mapping attribute "textDirection" to correct 2029 * flag value. 2030 * @hide 2031 */ 2032 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2033 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2034 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2035 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2036 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2037 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2038 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2039 }; 2040 2041 /** 2042 * Indicates whether the view text direction has been resolved. 2043 * @hide 2044 */ 2045 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2046 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2047 2048 /** 2049 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2050 * @hide 2051 */ 2052 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2053 2054 /** 2055 * Mask for use with private flags indicating bits used for resolved text direction. 2056 * @hide 2057 */ 2058 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2059 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2060 2061 /** 2062 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2063 * @hide 2064 */ 2065 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2066 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2067 2068 /** @hide */ 2069 @IntDef({ 2070 TEXT_ALIGNMENT_INHERIT, 2071 TEXT_ALIGNMENT_GRAVITY, 2072 TEXT_ALIGNMENT_CENTER, 2073 TEXT_ALIGNMENT_TEXT_START, 2074 TEXT_ALIGNMENT_TEXT_END, 2075 TEXT_ALIGNMENT_VIEW_START, 2076 TEXT_ALIGNMENT_VIEW_END 2077 }) 2078 @Retention(RetentionPolicy.SOURCE) 2079 public @interface TextAlignment {} 2080 2081 /** 2082 * Default text alignment. The text alignment of this View is inherited from its parent. 2083 * Use with {@link #setTextAlignment(int)} 2084 */ 2085 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2086 2087 /** 2088 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2089 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2090 * 2091 * Use with {@link #setTextAlignment(int)} 2092 */ 2093 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2094 2095 /** 2096 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2097 * 2098 * Use with {@link #setTextAlignment(int)} 2099 */ 2100 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2101 2102 /** 2103 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2104 * 2105 * Use with {@link #setTextAlignment(int)} 2106 */ 2107 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2108 2109 /** 2110 * Center the paragraph, e.g. ALIGN_CENTER. 2111 * 2112 * Use with {@link #setTextAlignment(int)} 2113 */ 2114 public static final int TEXT_ALIGNMENT_CENTER = 4; 2115 2116 /** 2117 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2118 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2119 * 2120 * Use with {@link #setTextAlignment(int)} 2121 */ 2122 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2123 2124 /** 2125 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2126 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2127 * 2128 * Use with {@link #setTextAlignment(int)} 2129 */ 2130 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2131 2132 /** 2133 * Default text alignment is inherited 2134 */ 2135 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2136 2137 /** 2138 * Default resolved text alignment 2139 * @hide 2140 */ 2141 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2142 2143 /** 2144 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2145 * @hide 2146 */ 2147 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2148 2149 /** 2150 * Mask for use with private flags indicating bits used for text alignment. 2151 * @hide 2152 */ 2153 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2154 2155 /** 2156 * Array of text direction flags for mapping attribute "textAlignment" to correct 2157 * flag value. 2158 * @hide 2159 */ 2160 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2161 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2162 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2163 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2164 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2165 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2166 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2167 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2168 }; 2169 2170 /** 2171 * Indicates whether the view text alignment has been resolved. 2172 * @hide 2173 */ 2174 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2175 2176 /** 2177 * Bit shift to get the resolved text alignment. 2178 * @hide 2179 */ 2180 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2181 2182 /** 2183 * Mask for use with private flags indicating bits used for text alignment. 2184 * @hide 2185 */ 2186 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2187 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2188 2189 /** 2190 * Indicates whether if the view text alignment has been resolved to gravity 2191 */ 2192 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2193 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2194 2195 // Accessiblity constants for mPrivateFlags2 2196 2197 /** 2198 * Shift for the bits in {@link #mPrivateFlags2} related to the 2199 * "importantForAccessibility" attribute. 2200 */ 2201 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2202 2203 /** 2204 * Automatically determine whether a view is important for accessibility. 2205 */ 2206 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2207 2208 /** 2209 * The view is important for accessibility. 2210 */ 2211 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2212 2213 /** 2214 * The view is not important for accessibility. 2215 */ 2216 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2217 2218 /** 2219 * The view is not important for accessibility, nor are any of its 2220 * descendant views. 2221 */ 2222 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2223 2224 /** 2225 * The default whether the view is important for accessibility. 2226 */ 2227 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2228 2229 /** 2230 * Mask for obtainig the bits which specify how to determine 2231 * whether a view is important for accessibility. 2232 */ 2233 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2234 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2235 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2236 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2237 2238 /** 2239 * Shift for the bits in {@link #mPrivateFlags2} related to the 2240 * "accessibilityLiveRegion" attribute. 2241 */ 2242 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2243 2244 /** 2245 * Live region mode specifying that accessibility services should not 2246 * automatically announce changes to this view. This is the default live 2247 * region mode for most views. 2248 * <p> 2249 * Use with {@link #setAccessibilityLiveRegion(int)}. 2250 */ 2251 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2252 2253 /** 2254 * Live region mode specifying that accessibility services should announce 2255 * changes to this view. 2256 * <p> 2257 * Use with {@link #setAccessibilityLiveRegion(int)}. 2258 */ 2259 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2260 2261 /** 2262 * Live region mode specifying that accessibility services should interrupt 2263 * ongoing speech to immediately announce changes to this view. 2264 * <p> 2265 * Use with {@link #setAccessibilityLiveRegion(int)}. 2266 */ 2267 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2268 2269 /** 2270 * The default whether the view is important for accessibility. 2271 */ 2272 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2273 2274 /** 2275 * Mask for obtaining the bits which specify a view's accessibility live 2276 * region mode. 2277 */ 2278 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2279 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2280 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2281 2282 /** 2283 * Flag indicating whether a view has accessibility focus. 2284 */ 2285 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2286 2287 /** 2288 * Flag whether the accessibility state of the subtree rooted at this view changed. 2289 */ 2290 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2291 2292 /** 2293 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2294 * is used to check whether later changes to the view's transform should invalidate the 2295 * view to force the quickReject test to run again. 2296 */ 2297 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2298 2299 /** 2300 * Flag indicating that start/end padding has been resolved into left/right padding 2301 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2302 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2303 * during measurement. In some special cases this is required such as when an adapter-based 2304 * view measures prospective children without attaching them to a window. 2305 */ 2306 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2307 2308 /** 2309 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2310 */ 2311 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2312 2313 /** 2314 * Indicates that the view is tracking some sort of transient state 2315 * that the app should not need to be aware of, but that the framework 2316 * should take special care to preserve. 2317 */ 2318 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2319 2320 /** 2321 * Group of bits indicating that RTL properties resolution is done. 2322 */ 2323 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2324 PFLAG2_TEXT_DIRECTION_RESOLVED | 2325 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2326 PFLAG2_PADDING_RESOLVED | 2327 PFLAG2_DRAWABLE_RESOLVED; 2328 2329 // There are a couple of flags left in mPrivateFlags2 2330 2331 /* End of masks for mPrivateFlags2 */ 2332 2333 /** 2334 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2335 * 2336 * |-------|-------|-------|-------| 2337 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2338 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2339 * 1 PFLAG3_IS_LAID_OUT 2340 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2341 * 1 PFLAG3_CALLED_SUPER 2342 * |-------|-------|-------|-------| 2343 */ 2344 2345 /** 2346 * Flag indicating that view has a transform animation set on it. This is used to track whether 2347 * an animation is cleared between successive frames, in order to tell the associated 2348 * DisplayList to clear its animation matrix. 2349 */ 2350 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2351 2352 /** 2353 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2354 * animation is cleared between successive frames, in order to tell the associated 2355 * DisplayList to restore its alpha value. 2356 */ 2357 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2358 2359 /** 2360 * Flag indicating that the view has been through at least one layout since it 2361 * was last attached to a window. 2362 */ 2363 static final int PFLAG3_IS_LAID_OUT = 0x4; 2364 2365 /** 2366 * Flag indicating that a call to measure() was skipped and should be done 2367 * instead when layout() is invoked. 2368 */ 2369 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2370 2371 /** 2372 * Flag indicating that an overridden method correctly called down to 2373 * the superclass implementation as required by the API spec. 2374 */ 2375 static final int PFLAG3_CALLED_SUPER = 0x10; 2376 2377 /** 2378 * Flag indicating that a view's outline has been specifically defined. 2379 */ 2380 static final int PFLAG3_OUTLINE_DEFINED = 0x20; 2381 2382 /** 2383 * Flag indicating that we're in the process of applying window insets. 2384 */ 2385 static final int PFLAG3_APPLYING_INSETS = 0x40; 2386 2387 /** 2388 * Flag indicating that we're in the process of fitting system windows using the old method. 2389 */ 2390 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x80; 2391 2392 /* End of masks for mPrivateFlags3 */ 2393 2394 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2395 2396 /** 2397 * Always allow a user to over-scroll this view, provided it is a 2398 * view that can scroll. 2399 * 2400 * @see #getOverScrollMode() 2401 * @see #setOverScrollMode(int) 2402 */ 2403 public static final int OVER_SCROLL_ALWAYS = 0; 2404 2405 /** 2406 * Allow a user to over-scroll this view only if the content is large 2407 * enough to meaningfully scroll, provided it is a view that can scroll. 2408 * 2409 * @see #getOverScrollMode() 2410 * @see #setOverScrollMode(int) 2411 */ 2412 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2413 2414 /** 2415 * Never allow a user to over-scroll this view. 2416 * 2417 * @see #getOverScrollMode() 2418 * @see #setOverScrollMode(int) 2419 */ 2420 public static final int OVER_SCROLL_NEVER = 2; 2421 2422 /** 2423 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2424 * requested the system UI (status bar) to be visible (the default). 2425 * 2426 * @see #setSystemUiVisibility(int) 2427 */ 2428 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2429 2430 /** 2431 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2432 * system UI to enter an unobtrusive "low profile" mode. 2433 * 2434 * <p>This is for use in games, book readers, video players, or any other 2435 * "immersive" application where the usual system chrome is deemed too distracting. 2436 * 2437 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2438 * 2439 * @see #setSystemUiVisibility(int) 2440 */ 2441 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2442 2443 /** 2444 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2445 * system navigation be temporarily hidden. 2446 * 2447 * <p>This is an even less obtrusive state than that called for by 2448 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2449 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2450 * those to disappear. This is useful (in conjunction with the 2451 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2452 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2453 * window flags) for displaying content using every last pixel on the display. 2454 * 2455 * <p>There is a limitation: because navigation controls are so important, the least user 2456 * interaction will cause them to reappear immediately. When this happens, both 2457 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2458 * so that both elements reappear at the same time. 2459 * 2460 * @see #setSystemUiVisibility(int) 2461 */ 2462 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2463 2464 /** 2465 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2466 * into the normal fullscreen mode so that its content can take over the screen 2467 * while still allowing the user to interact with the application. 2468 * 2469 * <p>This has the same visual effect as 2470 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2471 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2472 * meaning that non-critical screen decorations (such as the status bar) will be 2473 * hidden while the user is in the View's window, focusing the experience on 2474 * that content. Unlike the window flag, if you are using ActionBar in 2475 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2476 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2477 * hide the action bar. 2478 * 2479 * <p>This approach to going fullscreen is best used over the window flag when 2480 * it is a transient state -- that is, the application does this at certain 2481 * points in its user interaction where it wants to allow the user to focus 2482 * on content, but not as a continuous state. For situations where the application 2483 * would like to simply stay full screen the entire time (such as a game that 2484 * wants to take over the screen), the 2485 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2486 * is usually a better approach. The state set here will be removed by the system 2487 * in various situations (such as the user moving to another application) like 2488 * the other system UI states. 2489 * 2490 * <p>When using this flag, the application should provide some easy facility 2491 * for the user to go out of it. A common example would be in an e-book 2492 * reader, where tapping on the screen brings back whatever screen and UI 2493 * decorations that had been hidden while the user was immersed in reading 2494 * the book. 2495 * 2496 * @see #setSystemUiVisibility(int) 2497 */ 2498 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2499 2500 /** 2501 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2502 * flags, we would like a stable view of the content insets given to 2503 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2504 * will always represent the worst case that the application can expect 2505 * as a continuous state. In the stock Android UI this is the space for 2506 * the system bar, nav bar, and status bar, but not more transient elements 2507 * such as an input method. 2508 * 2509 * The stable layout your UI sees is based on the system UI modes you can 2510 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2511 * then you will get a stable layout for changes of the 2512 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2513 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2514 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2515 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2516 * with a stable layout. (Note that you should avoid using 2517 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2518 * 2519 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2520 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2521 * then a hidden status bar will be considered a "stable" state for purposes 2522 * here. This allows your UI to continually hide the status bar, while still 2523 * using the system UI flags to hide the action bar while still retaining 2524 * a stable layout. Note that changing the window fullscreen flag will never 2525 * provide a stable layout for a clean transition. 2526 * 2527 * <p>If you are using ActionBar in 2528 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2529 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2530 * insets it adds to those given to the application. 2531 */ 2532 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2533 2534 /** 2535 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2536 * to be layed out as if it has requested 2537 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2538 * allows it to avoid artifacts when switching in and out of that mode, at 2539 * the expense that some of its user interface may be covered by screen 2540 * decorations when they are shown. You can perform layout of your inner 2541 * UI elements to account for the navigation system UI through the 2542 * {@link #fitSystemWindows(Rect)} method. 2543 */ 2544 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2545 2546 /** 2547 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2548 * to be layed out as if it has requested 2549 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2550 * allows it to avoid artifacts when switching in and out of that mode, at 2551 * the expense that some of its user interface may be covered by screen 2552 * decorations when they are shown. You can perform layout of your inner 2553 * UI elements to account for non-fullscreen system UI through the 2554 * {@link #fitSystemWindows(Rect)} method. 2555 */ 2556 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2557 2558 /** 2559 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2560 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2561 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2562 * user interaction. 2563 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2564 * has an effect when used in combination with that flag.</p> 2565 */ 2566 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2567 2568 /** 2569 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2570 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2571 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2572 * experience while also hiding the system bars. If this flag is not set, 2573 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2574 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2575 * if the user swipes from the top of the screen. 2576 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2577 * system gestures, such as swiping from the top of the screen. These transient system bars 2578 * will overlay app’s content, may have some degree of transparency, and will automatically 2579 * hide after a short timeout. 2580 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2581 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2582 * with one or both of those flags.</p> 2583 */ 2584 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2585 2586 /** 2587 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2588 */ 2589 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2590 2591 /** 2592 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2593 */ 2594 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2595 2596 /** 2597 * @hide 2598 * 2599 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2600 * out of the public fields to keep the undefined bits out of the developer's way. 2601 * 2602 * Flag to make the status bar not expandable. Unless you also 2603 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2604 */ 2605 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2606 2607 /** 2608 * @hide 2609 * 2610 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2611 * out of the public fields to keep the undefined bits out of the developer's way. 2612 * 2613 * Flag to hide notification icons and scrolling ticker text. 2614 */ 2615 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2616 2617 /** 2618 * @hide 2619 * 2620 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2621 * out of the public fields to keep the undefined bits out of the developer's way. 2622 * 2623 * Flag to disable incoming notification alerts. This will not block 2624 * icons, but it will block sound, vibrating and other visual or aural notifications. 2625 */ 2626 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2627 2628 /** 2629 * @hide 2630 * 2631 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2632 * out of the public fields to keep the undefined bits out of the developer's way. 2633 * 2634 * Flag to hide only the scrolling ticker. Note that 2635 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2636 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2637 */ 2638 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2639 2640 /** 2641 * @hide 2642 * 2643 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2644 * out of the public fields to keep the undefined bits out of the developer's way. 2645 * 2646 * Flag to hide the center system info area. 2647 */ 2648 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2649 2650 /** 2651 * @hide 2652 * 2653 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2654 * out of the public fields to keep the undefined bits out of the developer's way. 2655 * 2656 * Flag to hide only the home button. Don't use this 2657 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2658 */ 2659 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2660 2661 /** 2662 * @hide 2663 * 2664 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2665 * out of the public fields to keep the undefined bits out of the developer's way. 2666 * 2667 * Flag to hide only the back button. Don't use this 2668 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2669 */ 2670 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2671 2672 /** 2673 * @hide 2674 * 2675 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2676 * out of the public fields to keep the undefined bits out of the developer's way. 2677 * 2678 * Flag to hide only the clock. You might use this if your activity has 2679 * its own clock making the status bar's clock redundant. 2680 */ 2681 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2682 2683 /** 2684 * @hide 2685 * 2686 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2687 * out of the public fields to keep the undefined bits out of the developer's way. 2688 * 2689 * Flag to hide only the recent apps button. Don't use this 2690 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2691 */ 2692 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2693 2694 /** 2695 * @hide 2696 * 2697 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2698 * out of the public fields to keep the undefined bits out of the developer's way. 2699 * 2700 * Flag to disable the global search gesture. Don't use this 2701 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2702 */ 2703 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2704 2705 /** 2706 * @hide 2707 * 2708 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2709 * out of the public fields to keep the undefined bits out of the developer's way. 2710 * 2711 * Flag to specify that the status bar is displayed in transient mode. 2712 */ 2713 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2714 2715 /** 2716 * @hide 2717 * 2718 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2719 * out of the public fields to keep the undefined bits out of the developer's way. 2720 * 2721 * Flag to specify that the navigation bar is displayed in transient mode. 2722 */ 2723 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2724 2725 /** 2726 * @hide 2727 * 2728 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2729 * out of the public fields to keep the undefined bits out of the developer's way. 2730 * 2731 * Flag to specify that the hidden status bar would like to be shown. 2732 */ 2733 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2734 2735 /** 2736 * @hide 2737 * 2738 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2739 * out of the public fields to keep the undefined bits out of the developer's way. 2740 * 2741 * Flag to specify that the hidden navigation bar would like to be shown. 2742 */ 2743 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2744 2745 /** 2746 * @hide 2747 * 2748 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2749 * out of the public fields to keep the undefined bits out of the developer's way. 2750 * 2751 * Flag to specify that the status bar is displayed in translucent mode. 2752 */ 2753 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2754 2755 /** 2756 * @hide 2757 * 2758 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2759 * out of the public fields to keep the undefined bits out of the developer's way. 2760 * 2761 * Flag to specify that the navigation bar is displayed in translucent mode. 2762 */ 2763 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2764 2765 /** 2766 * @hide 2767 */ 2768 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x0000FFFF; 2769 2770 /** 2771 * These are the system UI flags that can be cleared by events outside 2772 * of an application. Currently this is just the ability to tap on the 2773 * screen while hiding the navigation bar to have it return. 2774 * @hide 2775 */ 2776 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2777 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2778 | SYSTEM_UI_FLAG_FULLSCREEN; 2779 2780 /** 2781 * Flags that can impact the layout in relation to system UI. 2782 */ 2783 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2784 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2785 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2786 2787 /** @hide */ 2788 @IntDef(flag = true, 2789 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2790 @Retention(RetentionPolicy.SOURCE) 2791 public @interface FindViewFlags {} 2792 2793 /** 2794 * Find views that render the specified text. 2795 * 2796 * @see #findViewsWithText(ArrayList, CharSequence, int) 2797 */ 2798 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2799 2800 /** 2801 * Find find views that contain the specified content description. 2802 * 2803 * @see #findViewsWithText(ArrayList, CharSequence, int) 2804 */ 2805 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2806 2807 /** 2808 * Find views that contain {@link AccessibilityNodeProvider}. Such 2809 * a View is a root of virtual view hierarchy and may contain the searched 2810 * text. If this flag is set Views with providers are automatically 2811 * added and it is a responsibility of the client to call the APIs of 2812 * the provider to determine whether the virtual tree rooted at this View 2813 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2814 * representing the virtual views with this text. 2815 * 2816 * @see #findViewsWithText(ArrayList, CharSequence, int) 2817 * 2818 * @hide 2819 */ 2820 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2821 2822 /** 2823 * The undefined cursor position. 2824 * 2825 * @hide 2826 */ 2827 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2828 2829 /** 2830 * Indicates that the screen has changed state and is now off. 2831 * 2832 * @see #onScreenStateChanged(int) 2833 */ 2834 public static final int SCREEN_STATE_OFF = 0x0; 2835 2836 /** 2837 * Indicates that the screen has changed state and is now on. 2838 * 2839 * @see #onScreenStateChanged(int) 2840 */ 2841 public static final int SCREEN_STATE_ON = 0x1; 2842 2843 /** 2844 * Controls the over-scroll mode for this view. 2845 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2846 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2847 * and {@link #OVER_SCROLL_NEVER}. 2848 */ 2849 private int mOverScrollMode; 2850 2851 /** 2852 * The parent this view is attached to. 2853 * {@hide} 2854 * 2855 * @see #getParent() 2856 */ 2857 protected ViewParent mParent; 2858 2859 /** 2860 * {@hide} 2861 */ 2862 AttachInfo mAttachInfo; 2863 2864 /** 2865 * {@hide} 2866 */ 2867 @ViewDebug.ExportedProperty(flagMapping = { 2868 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2869 name = "FORCE_LAYOUT"), 2870 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2871 name = "LAYOUT_REQUIRED"), 2872 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2873 name = "DRAWING_CACHE_INVALID", outputIf = false), 2874 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2875 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2876 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2877 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2878 }) 2879 int mPrivateFlags; 2880 int mPrivateFlags2; 2881 int mPrivateFlags3; 2882 2883 /** 2884 * This view's request for the visibility of the status bar. 2885 * @hide 2886 */ 2887 @ViewDebug.ExportedProperty(flagMapping = { 2888 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2889 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2890 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2891 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2892 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2893 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2894 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2895 equals = SYSTEM_UI_FLAG_VISIBLE, 2896 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2897 }) 2898 int mSystemUiVisibility; 2899 2900 /** 2901 * Reference count for transient state. 2902 * @see #setHasTransientState(boolean) 2903 */ 2904 int mTransientStateCount = 0; 2905 2906 /** 2907 * Count of how many windows this view has been attached to. 2908 */ 2909 int mWindowAttachCount; 2910 2911 /** 2912 * The layout parameters associated with this view and used by the parent 2913 * {@link android.view.ViewGroup} to determine how this view should be 2914 * laid out. 2915 * {@hide} 2916 */ 2917 protected ViewGroup.LayoutParams mLayoutParams; 2918 2919 /** 2920 * The view flags hold various views states. 2921 * {@hide} 2922 */ 2923 @ViewDebug.ExportedProperty 2924 int mViewFlags; 2925 2926 static class TransformationInfo { 2927 /** 2928 * The transform matrix for the View. This transform is calculated internally 2929 * based on the translation, rotation, and scale properties. 2930 * 2931 * Do *not* use this variable directly; instead call getMatrix(), which will 2932 * load the value from the View's RenderNode. 2933 */ 2934 private final Matrix mMatrix = new Matrix(); 2935 2936 /** 2937 * The inverse transform matrix for the View. This transform is calculated 2938 * internally based on the translation, rotation, and scale properties. 2939 * 2940 * Do *not* use this variable directly; instead call getInverseMatrix(), 2941 * which will load the value from the View's RenderNode. 2942 */ 2943 private Matrix mInverseMatrix; 2944 2945 /** 2946 * The opacity of the View. This is a value from 0 to 1, where 0 means 2947 * completely transparent and 1 means completely opaque. 2948 */ 2949 @ViewDebug.ExportedProperty 2950 float mAlpha = 1f; 2951 2952 /** 2953 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2954 * property only used by transitions, which is composited with the other alpha 2955 * values to calculate the final visual alpha value. 2956 */ 2957 float mTransitionAlpha = 1f; 2958 } 2959 2960 TransformationInfo mTransformationInfo; 2961 2962 /** 2963 * Current clip bounds. to which all drawing of this view are constrained. 2964 */ 2965 Rect mClipBounds = null; 2966 2967 private boolean mLastIsOpaque; 2968 2969 /** 2970 * The distance in pixels from the left edge of this view's parent 2971 * to the left edge of this view. 2972 * {@hide} 2973 */ 2974 @ViewDebug.ExportedProperty(category = "layout") 2975 protected int mLeft; 2976 /** 2977 * The distance in pixels from the left edge of this view's parent 2978 * to the right edge of this view. 2979 * {@hide} 2980 */ 2981 @ViewDebug.ExportedProperty(category = "layout") 2982 protected int mRight; 2983 /** 2984 * The distance in pixels from the top edge of this view's parent 2985 * to the top edge of this view. 2986 * {@hide} 2987 */ 2988 @ViewDebug.ExportedProperty(category = "layout") 2989 protected int mTop; 2990 /** 2991 * The distance in pixels from the top edge of this view's parent 2992 * to the bottom edge of this view. 2993 * {@hide} 2994 */ 2995 @ViewDebug.ExportedProperty(category = "layout") 2996 protected int mBottom; 2997 2998 /** 2999 * The offset, in pixels, by which the content of this view is scrolled 3000 * horizontally. 3001 * {@hide} 3002 */ 3003 @ViewDebug.ExportedProperty(category = "scrolling") 3004 protected int mScrollX; 3005 /** 3006 * The offset, in pixels, by which the content of this view is scrolled 3007 * vertically. 3008 * {@hide} 3009 */ 3010 @ViewDebug.ExportedProperty(category = "scrolling") 3011 protected int mScrollY; 3012 3013 /** 3014 * The left padding in pixels, that is the distance in pixels between the 3015 * left edge of this view and the left edge of its content. 3016 * {@hide} 3017 */ 3018 @ViewDebug.ExportedProperty(category = "padding") 3019 protected int mPaddingLeft = 0; 3020 /** 3021 * The right padding in pixels, that is the distance in pixels between the 3022 * right edge of this view and the right edge of its content. 3023 * {@hide} 3024 */ 3025 @ViewDebug.ExportedProperty(category = "padding") 3026 protected int mPaddingRight = 0; 3027 /** 3028 * The top padding in pixels, that is the distance in pixels between the 3029 * top edge of this view and the top edge of its content. 3030 * {@hide} 3031 */ 3032 @ViewDebug.ExportedProperty(category = "padding") 3033 protected int mPaddingTop; 3034 /** 3035 * The bottom padding in pixels, that is the distance in pixels between the 3036 * bottom edge of this view and the bottom edge of its content. 3037 * {@hide} 3038 */ 3039 @ViewDebug.ExportedProperty(category = "padding") 3040 protected int mPaddingBottom; 3041 3042 /** 3043 * The layout insets in pixels, that is the distance in pixels between the 3044 * visible edges of this view its bounds. 3045 */ 3046 private Insets mLayoutInsets; 3047 3048 /** 3049 * Briefly describes the view and is primarily used for accessibility support. 3050 */ 3051 private CharSequence mContentDescription; 3052 3053 /** 3054 * Specifies the id of a view for which this view serves as a label for 3055 * accessibility purposes. 3056 */ 3057 private int mLabelForId = View.NO_ID; 3058 3059 /** 3060 * Predicate for matching labeled view id with its label for 3061 * accessibility purposes. 3062 */ 3063 private MatchLabelForPredicate mMatchLabelForPredicate; 3064 3065 /** 3066 * Predicate for matching a view by its id. 3067 */ 3068 private MatchIdPredicate mMatchIdPredicate; 3069 3070 /** 3071 * Cache the paddingRight set by the user to append to the scrollbar's size. 3072 * 3073 * @hide 3074 */ 3075 @ViewDebug.ExportedProperty(category = "padding") 3076 protected int mUserPaddingRight; 3077 3078 /** 3079 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3080 * 3081 * @hide 3082 */ 3083 @ViewDebug.ExportedProperty(category = "padding") 3084 protected int mUserPaddingBottom; 3085 3086 /** 3087 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3088 * 3089 * @hide 3090 */ 3091 @ViewDebug.ExportedProperty(category = "padding") 3092 protected int mUserPaddingLeft; 3093 3094 /** 3095 * Cache the paddingStart set by the user to append to the scrollbar's size. 3096 * 3097 */ 3098 @ViewDebug.ExportedProperty(category = "padding") 3099 int mUserPaddingStart; 3100 3101 /** 3102 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3103 * 3104 */ 3105 @ViewDebug.ExportedProperty(category = "padding") 3106 int mUserPaddingEnd; 3107 3108 /** 3109 * Cache initial left padding. 3110 * 3111 * @hide 3112 */ 3113 int mUserPaddingLeftInitial; 3114 3115 /** 3116 * Cache initial right padding. 3117 * 3118 * @hide 3119 */ 3120 int mUserPaddingRightInitial; 3121 3122 /** 3123 * Default undefined padding 3124 */ 3125 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3126 3127 /** 3128 * Cache if a left padding has been defined 3129 */ 3130 private boolean mLeftPaddingDefined = false; 3131 3132 /** 3133 * Cache if a right padding has been defined 3134 */ 3135 private boolean mRightPaddingDefined = false; 3136 3137 /** 3138 * @hide 3139 */ 3140 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3141 /** 3142 * @hide 3143 */ 3144 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3145 3146 private LongSparseLongArray mMeasureCache; 3147 3148 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3149 private Drawable mBackground; 3150 3151 /** 3152 * Display list used for backgrounds. 3153 * <p> 3154 * When non-null and valid, this is expected to contain an up-to-date copy 3155 * of the background drawable. It is cleared on temporary detach and reset 3156 * on cleanup. 3157 */ 3158 private RenderNode mBackgroundDisplayList; 3159 3160 private int mBackgroundResource; 3161 private boolean mBackgroundSizeChanged; 3162 3163 static class ListenerInfo { 3164 /** 3165 * Listener used to dispatch focus change events. 3166 * This field should be made private, so it is hidden from the SDK. 3167 * {@hide} 3168 */ 3169 protected OnFocusChangeListener mOnFocusChangeListener; 3170 3171 /** 3172 * Listeners for layout change events. 3173 */ 3174 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3175 3176 /** 3177 * Listeners for attach events. 3178 */ 3179 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3180 3181 /** 3182 * Listener used to dispatch click events. 3183 * This field should be made private, so it is hidden from the SDK. 3184 * {@hide} 3185 */ 3186 public OnClickListener mOnClickListener; 3187 3188 /** 3189 * Listener used to dispatch long click events. 3190 * This field should be made private, so it is hidden from the SDK. 3191 * {@hide} 3192 */ 3193 protected OnLongClickListener mOnLongClickListener; 3194 3195 /** 3196 * Listener used to build the context menu. 3197 * This field should be made private, so it is hidden from the SDK. 3198 * {@hide} 3199 */ 3200 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3201 3202 private OnKeyListener mOnKeyListener; 3203 3204 private OnTouchListener mOnTouchListener; 3205 3206 private OnHoverListener mOnHoverListener; 3207 3208 private OnGenericMotionListener mOnGenericMotionListener; 3209 3210 private OnDragListener mOnDragListener; 3211 3212 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3213 3214 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3215 } 3216 3217 ListenerInfo mListenerInfo; 3218 3219 /** 3220 * The application environment this view lives in. 3221 * This field should be made private, so it is hidden from the SDK. 3222 * {@hide} 3223 */ 3224 protected Context mContext; 3225 3226 private final Resources mResources; 3227 3228 private ScrollabilityCache mScrollCache; 3229 3230 private int[] mDrawableState = null; 3231 3232 /** 3233 * Stores the outline of the view, passed down to the DisplayList level for 3234 * defining shadow shape. 3235 */ 3236 private Outline mOutline; 3237 3238 /** 3239 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3240 * the user may specify which view to go to next. 3241 */ 3242 private int mNextFocusLeftId = View.NO_ID; 3243 3244 /** 3245 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3246 * the user may specify which view to go to next. 3247 */ 3248 private int mNextFocusRightId = View.NO_ID; 3249 3250 /** 3251 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3252 * the user may specify which view to go to next. 3253 */ 3254 private int mNextFocusUpId = View.NO_ID; 3255 3256 /** 3257 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3258 * the user may specify which view to go to next. 3259 */ 3260 private int mNextFocusDownId = View.NO_ID; 3261 3262 /** 3263 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3264 * the user may specify which view to go to next. 3265 */ 3266 int mNextFocusForwardId = View.NO_ID; 3267 3268 private CheckForLongPress mPendingCheckForLongPress; 3269 private CheckForTap mPendingCheckForTap = null; 3270 private PerformClick mPerformClick; 3271 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3272 3273 private UnsetPressedState mUnsetPressedState; 3274 3275 /** 3276 * Whether the long press's action has been invoked. The tap's action is invoked on the 3277 * up event while a long press is invoked as soon as the long press duration is reached, so 3278 * a long press could be performed before the tap is checked, in which case the tap's action 3279 * should not be invoked. 3280 */ 3281 private boolean mHasPerformedLongPress; 3282 3283 /** 3284 * The minimum height of the view. We'll try our best to have the height 3285 * of this view to at least this amount. 3286 */ 3287 @ViewDebug.ExportedProperty(category = "measurement") 3288 private int mMinHeight; 3289 3290 /** 3291 * The minimum width of the view. We'll try our best to have the width 3292 * of this view to at least this amount. 3293 */ 3294 @ViewDebug.ExportedProperty(category = "measurement") 3295 private int mMinWidth; 3296 3297 /** 3298 * The delegate to handle touch events that are physically in this view 3299 * but should be handled by another view. 3300 */ 3301 private TouchDelegate mTouchDelegate = null; 3302 3303 /** 3304 * Solid color to use as a background when creating the drawing cache. Enables 3305 * the cache to use 16 bit bitmaps instead of 32 bit. 3306 */ 3307 private int mDrawingCacheBackgroundColor = 0; 3308 3309 /** 3310 * Special tree observer used when mAttachInfo is null. 3311 */ 3312 private ViewTreeObserver mFloatingTreeObserver; 3313 3314 /** 3315 * Cache the touch slop from the context that created the view. 3316 */ 3317 private int mTouchSlop; 3318 3319 /** 3320 * Object that handles automatic animation of view properties. 3321 */ 3322 private ViewPropertyAnimator mAnimator = null; 3323 3324 /** 3325 * Flag indicating that a drag can cross window boundaries. When 3326 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3327 * with this flag set, all visible applications will be able to participate 3328 * in the drag operation and receive the dragged content. 3329 * 3330 * @hide 3331 */ 3332 public static final int DRAG_FLAG_GLOBAL = 1; 3333 3334 /** 3335 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3336 */ 3337 private float mVerticalScrollFactor; 3338 3339 /** 3340 * Position of the vertical scroll bar. 3341 */ 3342 private int mVerticalScrollbarPosition; 3343 3344 /** 3345 * Position the scroll bar at the default position as determined by the system. 3346 */ 3347 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3348 3349 /** 3350 * Position the scroll bar along the left edge. 3351 */ 3352 public static final int SCROLLBAR_POSITION_LEFT = 1; 3353 3354 /** 3355 * Position the scroll bar along the right edge. 3356 */ 3357 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3358 3359 /** 3360 * Indicates that the view does not have a layer. 3361 * 3362 * @see #getLayerType() 3363 * @see #setLayerType(int, android.graphics.Paint) 3364 * @see #LAYER_TYPE_SOFTWARE 3365 * @see #LAYER_TYPE_HARDWARE 3366 */ 3367 public static final int LAYER_TYPE_NONE = 0; 3368 3369 /** 3370 * <p>Indicates that the view has a software layer. A software layer is backed 3371 * by a bitmap and causes the view to be rendered using Android's software 3372 * rendering pipeline, even if hardware acceleration is enabled.</p> 3373 * 3374 * <p>Software layers have various usages:</p> 3375 * <p>When the application is not using hardware acceleration, a software layer 3376 * is useful to apply a specific color filter and/or blending mode and/or 3377 * translucency to a view and all its children.</p> 3378 * <p>When the application is using hardware acceleration, a software layer 3379 * is useful to render drawing primitives not supported by the hardware 3380 * accelerated pipeline. It can also be used to cache a complex view tree 3381 * into a texture and reduce the complexity of drawing operations. For instance, 3382 * when animating a complex view tree with a translation, a software layer can 3383 * be used to render the view tree only once.</p> 3384 * <p>Software layers should be avoided when the affected view tree updates 3385 * often. Every update will require to re-render the software layer, which can 3386 * potentially be slow (particularly when hardware acceleration is turned on 3387 * since the layer will have to be uploaded into a hardware texture after every 3388 * update.)</p> 3389 * 3390 * @see #getLayerType() 3391 * @see #setLayerType(int, android.graphics.Paint) 3392 * @see #LAYER_TYPE_NONE 3393 * @see #LAYER_TYPE_HARDWARE 3394 */ 3395 public static final int LAYER_TYPE_SOFTWARE = 1; 3396 3397 /** 3398 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3399 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3400 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3401 * rendering pipeline, but only if hardware acceleration is turned on for the 3402 * view hierarchy. When hardware acceleration is turned off, hardware layers 3403 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3404 * 3405 * <p>A hardware layer is useful to apply a specific color filter and/or 3406 * blending mode and/or translucency to a view and all its children.</p> 3407 * <p>A hardware layer can be used to cache a complex view tree into a 3408 * texture and reduce the complexity of drawing operations. For instance, 3409 * when animating a complex view tree with a translation, a hardware layer can 3410 * be used to render the view tree only once.</p> 3411 * <p>A hardware layer can also be used to increase the rendering quality when 3412 * rotation transformations are applied on a view. It can also be used to 3413 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3414 * 3415 * @see #getLayerType() 3416 * @see #setLayerType(int, android.graphics.Paint) 3417 * @see #LAYER_TYPE_NONE 3418 * @see #LAYER_TYPE_SOFTWARE 3419 */ 3420 public static final int LAYER_TYPE_HARDWARE = 2; 3421 3422 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3423 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3424 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3425 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3426 }) 3427 int mLayerType = LAYER_TYPE_NONE; 3428 Paint mLayerPaint; 3429 Rect mLocalDirtyRect; 3430 private HardwareLayer mHardwareLayer; 3431 3432 /** 3433 * Set to true when drawing cache is enabled and cannot be created. 3434 * 3435 * @hide 3436 */ 3437 public boolean mCachingFailed; 3438 private Bitmap mDrawingCache; 3439 private Bitmap mUnscaledDrawingCache; 3440 3441 /** 3442 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3443 * <p> 3444 * When non-null and valid, this is expected to contain an up-to-date copy 3445 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3446 * cleanup. 3447 */ 3448 final RenderNode mRenderNode; 3449 3450 /** 3451 * Set to true when the view is sending hover accessibility events because it 3452 * is the innermost hovered view. 3453 */ 3454 private boolean mSendingHoverAccessibilityEvents; 3455 3456 /** 3457 * Delegate for injecting accessibility functionality. 3458 */ 3459 AccessibilityDelegate mAccessibilityDelegate; 3460 3461 /** 3462 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3463 * and add/remove objects to/from the overlay directly through the Overlay methods. 3464 */ 3465 ViewOverlay mOverlay; 3466 3467 /** 3468 * Consistency verifier for debugging purposes. 3469 * @hide 3470 */ 3471 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3472 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3473 new InputEventConsistencyVerifier(this, 0) : null; 3474 3475 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3476 3477 /** 3478 * Simple constructor to use when creating a view from code. 3479 * 3480 * @param context The Context the view is running in, through which it can 3481 * access the current theme, resources, etc. 3482 */ 3483 public View(Context context) { 3484 mContext = context; 3485 mResources = context != null ? context.getResources() : null; 3486 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3487 // Set some flags defaults 3488 mPrivateFlags2 = 3489 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3490 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3491 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3492 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3493 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3494 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3495 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3496 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3497 mUserPaddingStart = UNDEFINED_PADDING; 3498 mUserPaddingEnd = UNDEFINED_PADDING; 3499 mRenderNode = RenderNode.create(getClass().getName()); 3500 3501 if (!sCompatibilityDone && context != null) { 3502 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3503 3504 // Older apps may need this compatibility hack for measurement. 3505 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3506 3507 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3508 // of whether a layout was requested on that View. 3509 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3510 3511 // Older apps may need this to ignore the clip bounds 3512 sIgnoreClipBoundsForChildren = targetSdkVersion < L; 3513 3514 sCompatibilityDone = true; 3515 } 3516 } 3517 3518 /** 3519 * Constructor that is called when inflating a view from XML. This is called 3520 * when a view is being constructed from an XML file, supplying attributes 3521 * that were specified in the XML file. This version uses a default style of 3522 * 0, so the only attribute values applied are those in the Context's Theme 3523 * and the given AttributeSet. 3524 * 3525 * <p> 3526 * The method onFinishInflate() will be called after all children have been 3527 * added. 3528 * 3529 * @param context The Context the view is running in, through which it can 3530 * access the current theme, resources, etc. 3531 * @param attrs The attributes of the XML tag that is inflating the view. 3532 * @see #View(Context, AttributeSet, int) 3533 */ 3534 public View(Context context, AttributeSet attrs) { 3535 this(context, attrs, 0); 3536 } 3537 3538 /** 3539 * Perform inflation from XML and apply a class-specific base style from a 3540 * theme attribute. This constructor of View allows subclasses to use their 3541 * own base style when they are inflating. For example, a Button class's 3542 * constructor would call this version of the super class constructor and 3543 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3544 * allows the theme's button style to modify all of the base view attributes 3545 * (in particular its background) as well as the Button class's attributes. 3546 * 3547 * @param context The Context the view is running in, through which it can 3548 * access the current theme, resources, etc. 3549 * @param attrs The attributes of the XML tag that is inflating the view. 3550 * @param defStyleAttr An attribute in the current theme that contains a 3551 * reference to a style resource that supplies default values for 3552 * the view. Can be 0 to not look for defaults. 3553 * @see #View(Context, AttributeSet) 3554 */ 3555 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3556 this(context, attrs, defStyleAttr, 0); 3557 } 3558 3559 /** 3560 * Perform inflation from XML and apply a class-specific base style from a 3561 * theme attribute or style resource. This constructor of View allows 3562 * subclasses to use their own base style when they are inflating. 3563 * <p> 3564 * When determining the final value of a particular attribute, there are 3565 * four inputs that come into play: 3566 * <ol> 3567 * <li>Any attribute values in the given AttributeSet. 3568 * <li>The style resource specified in the AttributeSet (named "style"). 3569 * <li>The default style specified by <var>defStyleAttr</var>. 3570 * <li>The default style specified by <var>defStyleRes</var>. 3571 * <li>The base values in this theme. 3572 * </ol> 3573 * <p> 3574 * Each of these inputs is considered in-order, with the first listed taking 3575 * precedence over the following ones. In other words, if in the 3576 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3577 * , then the button's text will <em>always</em> be black, regardless of 3578 * what is specified in any of the styles. 3579 * 3580 * @param context The Context the view is running in, through which it can 3581 * access the current theme, resources, etc. 3582 * @param attrs The attributes of the XML tag that is inflating the view. 3583 * @param defStyleAttr An attribute in the current theme that contains a 3584 * reference to a style resource that supplies default values for 3585 * the view. Can be 0 to not look for defaults. 3586 * @param defStyleRes A resource identifier of a style resource that 3587 * supplies default values for the view, used only if 3588 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3589 * to not look for defaults. 3590 * @see #View(Context, AttributeSet, int) 3591 */ 3592 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3593 this(context); 3594 3595 final TypedArray a = context.obtainStyledAttributes( 3596 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3597 3598 Drawable background = null; 3599 3600 int leftPadding = -1; 3601 int topPadding = -1; 3602 int rightPadding = -1; 3603 int bottomPadding = -1; 3604 int startPadding = UNDEFINED_PADDING; 3605 int endPadding = UNDEFINED_PADDING; 3606 3607 int padding = -1; 3608 3609 int viewFlagValues = 0; 3610 int viewFlagMasks = 0; 3611 3612 boolean setScrollContainer = false; 3613 3614 int x = 0; 3615 int y = 0; 3616 3617 float tx = 0; 3618 float ty = 0; 3619 float tz = 0; 3620 float rotation = 0; 3621 float rotationX = 0; 3622 float rotationY = 0; 3623 float sx = 1f; 3624 float sy = 1f; 3625 boolean transformSet = false; 3626 3627 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3628 int overScrollMode = mOverScrollMode; 3629 boolean initializeScrollbars = false; 3630 3631 boolean startPaddingDefined = false; 3632 boolean endPaddingDefined = false; 3633 boolean leftPaddingDefined = false; 3634 boolean rightPaddingDefined = false; 3635 3636 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3637 3638 final int N = a.getIndexCount(); 3639 for (int i = 0; i < N; i++) { 3640 int attr = a.getIndex(i); 3641 switch (attr) { 3642 case com.android.internal.R.styleable.View_background: 3643 background = a.getDrawable(attr); 3644 break; 3645 case com.android.internal.R.styleable.View_padding: 3646 padding = a.getDimensionPixelSize(attr, -1); 3647 mUserPaddingLeftInitial = padding; 3648 mUserPaddingRightInitial = padding; 3649 leftPaddingDefined = true; 3650 rightPaddingDefined = true; 3651 break; 3652 case com.android.internal.R.styleable.View_paddingLeft: 3653 leftPadding = a.getDimensionPixelSize(attr, -1); 3654 mUserPaddingLeftInitial = leftPadding; 3655 leftPaddingDefined = true; 3656 break; 3657 case com.android.internal.R.styleable.View_paddingTop: 3658 topPadding = a.getDimensionPixelSize(attr, -1); 3659 break; 3660 case com.android.internal.R.styleable.View_paddingRight: 3661 rightPadding = a.getDimensionPixelSize(attr, -1); 3662 mUserPaddingRightInitial = rightPadding; 3663 rightPaddingDefined = true; 3664 break; 3665 case com.android.internal.R.styleable.View_paddingBottom: 3666 bottomPadding = a.getDimensionPixelSize(attr, -1); 3667 break; 3668 case com.android.internal.R.styleable.View_paddingStart: 3669 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3670 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3671 break; 3672 case com.android.internal.R.styleable.View_paddingEnd: 3673 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3674 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3675 break; 3676 case com.android.internal.R.styleable.View_scrollX: 3677 x = a.getDimensionPixelOffset(attr, 0); 3678 break; 3679 case com.android.internal.R.styleable.View_scrollY: 3680 y = a.getDimensionPixelOffset(attr, 0); 3681 break; 3682 case com.android.internal.R.styleable.View_alpha: 3683 setAlpha(a.getFloat(attr, 1f)); 3684 break; 3685 case com.android.internal.R.styleable.View_transformPivotX: 3686 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3687 break; 3688 case com.android.internal.R.styleable.View_transformPivotY: 3689 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3690 break; 3691 case com.android.internal.R.styleable.View_translationX: 3692 tx = a.getDimensionPixelOffset(attr, 0); 3693 transformSet = true; 3694 break; 3695 case com.android.internal.R.styleable.View_translationY: 3696 ty = a.getDimensionPixelOffset(attr, 0); 3697 transformSet = true; 3698 break; 3699 case com.android.internal.R.styleable.View_translationZ: 3700 tz = a.getDimensionPixelOffset(attr, 0); 3701 transformSet = true; 3702 break; 3703 case com.android.internal.R.styleable.View_rotation: 3704 rotation = a.getFloat(attr, 0); 3705 transformSet = true; 3706 break; 3707 case com.android.internal.R.styleable.View_rotationX: 3708 rotationX = a.getFloat(attr, 0); 3709 transformSet = true; 3710 break; 3711 case com.android.internal.R.styleable.View_rotationY: 3712 rotationY = a.getFloat(attr, 0); 3713 transformSet = true; 3714 break; 3715 case com.android.internal.R.styleable.View_scaleX: 3716 sx = a.getFloat(attr, 1f); 3717 transformSet = true; 3718 break; 3719 case com.android.internal.R.styleable.View_scaleY: 3720 sy = a.getFloat(attr, 1f); 3721 transformSet = true; 3722 break; 3723 case com.android.internal.R.styleable.View_id: 3724 mID = a.getResourceId(attr, NO_ID); 3725 break; 3726 case com.android.internal.R.styleable.View_tag: 3727 mTag = a.getText(attr); 3728 break; 3729 case com.android.internal.R.styleable.View_fitsSystemWindows: 3730 if (a.getBoolean(attr, false)) { 3731 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3732 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3733 } 3734 break; 3735 case com.android.internal.R.styleable.View_focusable: 3736 if (a.getBoolean(attr, false)) { 3737 viewFlagValues |= FOCUSABLE; 3738 viewFlagMasks |= FOCUSABLE_MASK; 3739 } 3740 break; 3741 case com.android.internal.R.styleable.View_focusableInTouchMode: 3742 if (a.getBoolean(attr, false)) { 3743 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3744 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3745 } 3746 break; 3747 case com.android.internal.R.styleable.View_clickable: 3748 if (a.getBoolean(attr, false)) { 3749 viewFlagValues |= CLICKABLE; 3750 viewFlagMasks |= CLICKABLE; 3751 } 3752 break; 3753 case com.android.internal.R.styleable.View_longClickable: 3754 if (a.getBoolean(attr, false)) { 3755 viewFlagValues |= LONG_CLICKABLE; 3756 viewFlagMasks |= LONG_CLICKABLE; 3757 } 3758 break; 3759 case com.android.internal.R.styleable.View_saveEnabled: 3760 if (!a.getBoolean(attr, true)) { 3761 viewFlagValues |= SAVE_DISABLED; 3762 viewFlagMasks |= SAVE_DISABLED_MASK; 3763 } 3764 break; 3765 case com.android.internal.R.styleable.View_duplicateParentState: 3766 if (a.getBoolean(attr, false)) { 3767 viewFlagValues |= DUPLICATE_PARENT_STATE; 3768 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3769 } 3770 break; 3771 case com.android.internal.R.styleable.View_visibility: 3772 final int visibility = a.getInt(attr, 0); 3773 if (visibility != 0) { 3774 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3775 viewFlagMasks |= VISIBILITY_MASK; 3776 } 3777 break; 3778 case com.android.internal.R.styleable.View_layoutDirection: 3779 // Clear any layout direction flags (included resolved bits) already set 3780 mPrivateFlags2 &= 3781 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3782 // Set the layout direction flags depending on the value of the attribute 3783 final int layoutDirection = a.getInt(attr, -1); 3784 final int value = (layoutDirection != -1) ? 3785 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3786 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3787 break; 3788 case com.android.internal.R.styleable.View_drawingCacheQuality: 3789 final int cacheQuality = a.getInt(attr, 0); 3790 if (cacheQuality != 0) { 3791 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3792 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3793 } 3794 break; 3795 case com.android.internal.R.styleable.View_contentDescription: 3796 setContentDescription(a.getString(attr)); 3797 break; 3798 case com.android.internal.R.styleable.View_labelFor: 3799 setLabelFor(a.getResourceId(attr, NO_ID)); 3800 break; 3801 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3802 if (!a.getBoolean(attr, true)) { 3803 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3804 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3805 } 3806 break; 3807 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3808 if (!a.getBoolean(attr, true)) { 3809 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3810 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3811 } 3812 break; 3813 case R.styleable.View_scrollbars: 3814 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3815 if (scrollbars != SCROLLBARS_NONE) { 3816 viewFlagValues |= scrollbars; 3817 viewFlagMasks |= SCROLLBARS_MASK; 3818 initializeScrollbars = true; 3819 } 3820 break; 3821 //noinspection deprecation 3822 case R.styleable.View_fadingEdge: 3823 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3824 // Ignore the attribute starting with ICS 3825 break; 3826 } 3827 // With builds < ICS, fall through and apply fading edges 3828 case R.styleable.View_requiresFadingEdge: 3829 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3830 if (fadingEdge != FADING_EDGE_NONE) { 3831 viewFlagValues |= fadingEdge; 3832 viewFlagMasks |= FADING_EDGE_MASK; 3833 initializeFadingEdge(a); 3834 } 3835 break; 3836 case R.styleable.View_scrollbarStyle: 3837 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3838 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3839 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3840 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3841 } 3842 break; 3843 case R.styleable.View_isScrollContainer: 3844 setScrollContainer = true; 3845 if (a.getBoolean(attr, false)) { 3846 setScrollContainer(true); 3847 } 3848 break; 3849 case com.android.internal.R.styleable.View_keepScreenOn: 3850 if (a.getBoolean(attr, false)) { 3851 viewFlagValues |= KEEP_SCREEN_ON; 3852 viewFlagMasks |= KEEP_SCREEN_ON; 3853 } 3854 break; 3855 case R.styleable.View_filterTouchesWhenObscured: 3856 if (a.getBoolean(attr, false)) { 3857 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3858 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3859 } 3860 break; 3861 case R.styleable.View_nextFocusLeft: 3862 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3863 break; 3864 case R.styleable.View_nextFocusRight: 3865 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3866 break; 3867 case R.styleable.View_nextFocusUp: 3868 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3869 break; 3870 case R.styleable.View_nextFocusDown: 3871 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3872 break; 3873 case R.styleable.View_nextFocusForward: 3874 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3875 break; 3876 case R.styleable.View_minWidth: 3877 mMinWidth = a.getDimensionPixelSize(attr, 0); 3878 break; 3879 case R.styleable.View_minHeight: 3880 mMinHeight = a.getDimensionPixelSize(attr, 0); 3881 break; 3882 case R.styleable.View_onClick: 3883 if (context.isRestricted()) { 3884 throw new IllegalStateException("The android:onClick attribute cannot " 3885 + "be used within a restricted context"); 3886 } 3887 3888 final String handlerName = a.getString(attr); 3889 if (handlerName != null) { 3890 setOnClickListener(new OnClickListener() { 3891 private Method mHandler; 3892 3893 public void onClick(View v) { 3894 if (mHandler == null) { 3895 try { 3896 mHandler = getContext().getClass().getMethod(handlerName, 3897 View.class); 3898 } catch (NoSuchMethodException e) { 3899 int id = getId(); 3900 String idText = id == NO_ID ? "" : " with id '" 3901 + getContext().getResources().getResourceEntryName( 3902 id) + "'"; 3903 throw new IllegalStateException("Could not find a method " + 3904 handlerName + "(View) in the activity " 3905 + getContext().getClass() + " for onClick handler" 3906 + " on view " + View.this.getClass() + idText, e); 3907 } 3908 } 3909 3910 try { 3911 mHandler.invoke(getContext(), View.this); 3912 } catch (IllegalAccessException e) { 3913 throw new IllegalStateException("Could not execute non " 3914 + "public method of the activity", e); 3915 } catch (InvocationTargetException e) { 3916 throw new IllegalStateException("Could not execute " 3917 + "method of the activity", e); 3918 } 3919 } 3920 }); 3921 } 3922 break; 3923 case R.styleable.View_overScrollMode: 3924 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3925 break; 3926 case R.styleable.View_verticalScrollbarPosition: 3927 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3928 break; 3929 case R.styleable.View_layerType: 3930 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3931 break; 3932 case R.styleable.View_textDirection: 3933 // Clear any text direction flag already set 3934 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 3935 // Set the text direction flags depending on the value of the attribute 3936 final int textDirection = a.getInt(attr, -1); 3937 if (textDirection != -1) { 3938 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 3939 } 3940 break; 3941 case R.styleable.View_textAlignment: 3942 // Clear any text alignment flag already set 3943 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 3944 // Set the text alignment flag depending on the value of the attribute 3945 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 3946 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 3947 break; 3948 case R.styleable.View_importantForAccessibility: 3949 setImportantForAccessibility(a.getInt(attr, 3950 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 3951 break; 3952 case R.styleable.View_accessibilityLiveRegion: 3953 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 3954 break; 3955 case R.styleable.View_sharedElementName: 3956 setSharedElementName(a.getString(attr)); 3957 break; 3958 } 3959 } 3960 3961 setOverScrollMode(overScrollMode); 3962 3963 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 3964 // the resolved layout direction). Those cached values will be used later during padding 3965 // resolution. 3966 mUserPaddingStart = startPadding; 3967 mUserPaddingEnd = endPadding; 3968 3969 if (background != null) { 3970 setBackground(background); 3971 } 3972 3973 // setBackground above will record that padding is currently provided by the background. 3974 // If we have padding specified via xml, record that here instead and use it. 3975 mLeftPaddingDefined = leftPaddingDefined; 3976 mRightPaddingDefined = rightPaddingDefined; 3977 3978 if (padding >= 0) { 3979 leftPadding = padding; 3980 topPadding = padding; 3981 rightPadding = padding; 3982 bottomPadding = padding; 3983 mUserPaddingLeftInitial = padding; 3984 mUserPaddingRightInitial = padding; 3985 } 3986 3987 if (isRtlCompatibilityMode()) { 3988 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 3989 // left / right padding are used if defined (meaning here nothing to do). If they are not 3990 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 3991 // start / end and resolve them as left / right (layout direction is not taken into account). 3992 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 3993 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 3994 // defined. 3995 if (!mLeftPaddingDefined && startPaddingDefined) { 3996 leftPadding = startPadding; 3997 } 3998 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 3999 if (!mRightPaddingDefined && endPaddingDefined) { 4000 rightPadding = endPadding; 4001 } 4002 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4003 } else { 4004 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4005 // values defined. Otherwise, left /right values are used. 4006 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4007 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4008 // defined. 4009 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4010 4011 if (mLeftPaddingDefined && !hasRelativePadding) { 4012 mUserPaddingLeftInitial = leftPadding; 4013 } 4014 if (mRightPaddingDefined && !hasRelativePadding) { 4015 mUserPaddingRightInitial = rightPadding; 4016 } 4017 } 4018 4019 internalSetPadding( 4020 mUserPaddingLeftInitial, 4021 topPadding >= 0 ? topPadding : mPaddingTop, 4022 mUserPaddingRightInitial, 4023 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4024 4025 if (viewFlagMasks != 0) { 4026 setFlags(viewFlagValues, viewFlagMasks); 4027 } 4028 4029 if (initializeScrollbars) { 4030 initializeScrollbars(a); 4031 } 4032 4033 a.recycle(); 4034 4035 // Needs to be called after mViewFlags is set 4036 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4037 recomputePadding(); 4038 } 4039 4040 if (x != 0 || y != 0) { 4041 scrollTo(x, y); 4042 } 4043 4044 if (transformSet) { 4045 setTranslationX(tx); 4046 setTranslationY(ty); 4047 setTranslationZ(tz); 4048 setRotation(rotation); 4049 setRotationX(rotationX); 4050 setRotationY(rotationY); 4051 setScaleX(sx); 4052 setScaleY(sy); 4053 } 4054 4055 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4056 setScrollContainer(true); 4057 } 4058 4059 computeOpaqueFlags(); 4060 } 4061 4062 /** 4063 * Non-public constructor for use in testing 4064 */ 4065 View() { 4066 mResources = null; 4067 mRenderNode = RenderNode.create(getClass().getName()); 4068 } 4069 4070 public String toString() { 4071 StringBuilder out = new StringBuilder(128); 4072 out.append(getClass().getName()); 4073 out.append('{'); 4074 out.append(Integer.toHexString(System.identityHashCode(this))); 4075 out.append(' '); 4076 switch (mViewFlags&VISIBILITY_MASK) { 4077 case VISIBLE: out.append('V'); break; 4078 case INVISIBLE: out.append('I'); break; 4079 case GONE: out.append('G'); break; 4080 default: out.append('.'); break; 4081 } 4082 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4083 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4084 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4085 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4086 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4087 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4088 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4089 out.append(' '); 4090 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4091 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4092 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4093 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4094 out.append('p'); 4095 } else { 4096 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4097 } 4098 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4099 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4100 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4101 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4102 out.append(' '); 4103 out.append(mLeft); 4104 out.append(','); 4105 out.append(mTop); 4106 out.append('-'); 4107 out.append(mRight); 4108 out.append(','); 4109 out.append(mBottom); 4110 final int id = getId(); 4111 if (id != NO_ID) { 4112 out.append(" #"); 4113 out.append(Integer.toHexString(id)); 4114 final Resources r = mResources; 4115 if (Resources.resourceHasPackage(id) && r != null) { 4116 try { 4117 String pkgname; 4118 switch (id&0xff000000) { 4119 case 0x7f000000: 4120 pkgname="app"; 4121 break; 4122 case 0x01000000: 4123 pkgname="android"; 4124 break; 4125 default: 4126 pkgname = r.getResourcePackageName(id); 4127 break; 4128 } 4129 String typename = r.getResourceTypeName(id); 4130 String entryname = r.getResourceEntryName(id); 4131 out.append(" "); 4132 out.append(pkgname); 4133 out.append(":"); 4134 out.append(typename); 4135 out.append("/"); 4136 out.append(entryname); 4137 } catch (Resources.NotFoundException e) { 4138 } 4139 } 4140 } 4141 out.append("}"); 4142 return out.toString(); 4143 } 4144 4145 /** 4146 * <p> 4147 * Initializes the fading edges from a given set of styled attributes. This 4148 * method should be called by subclasses that need fading edges and when an 4149 * instance of these subclasses is created programmatically rather than 4150 * being inflated from XML. This method is automatically called when the XML 4151 * is inflated. 4152 * </p> 4153 * 4154 * @param a the styled attributes set to initialize the fading edges from 4155 */ 4156 protected void initializeFadingEdge(TypedArray a) { 4157 initScrollCache(); 4158 4159 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4160 R.styleable.View_fadingEdgeLength, 4161 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4162 } 4163 4164 /** 4165 * Returns the size of the vertical faded edges used to indicate that more 4166 * content in this view is visible. 4167 * 4168 * @return The size in pixels of the vertical faded edge or 0 if vertical 4169 * faded edges are not enabled for this view. 4170 * @attr ref android.R.styleable#View_fadingEdgeLength 4171 */ 4172 public int getVerticalFadingEdgeLength() { 4173 if (isVerticalFadingEdgeEnabled()) { 4174 ScrollabilityCache cache = mScrollCache; 4175 if (cache != null) { 4176 return cache.fadingEdgeLength; 4177 } 4178 } 4179 return 0; 4180 } 4181 4182 /** 4183 * Set the size of the faded edge used to indicate that more content in this 4184 * view is available. Will not change whether the fading edge is enabled; use 4185 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4186 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4187 * for the vertical or horizontal fading edges. 4188 * 4189 * @param length The size in pixels of the faded edge used to indicate that more 4190 * content in this view is visible. 4191 */ 4192 public void setFadingEdgeLength(int length) { 4193 initScrollCache(); 4194 mScrollCache.fadingEdgeLength = length; 4195 } 4196 4197 /** 4198 * Returns the size of the horizontal faded edges used to indicate that more 4199 * content in this view is visible. 4200 * 4201 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4202 * faded edges are not enabled for this view. 4203 * @attr ref android.R.styleable#View_fadingEdgeLength 4204 */ 4205 public int getHorizontalFadingEdgeLength() { 4206 if (isHorizontalFadingEdgeEnabled()) { 4207 ScrollabilityCache cache = mScrollCache; 4208 if (cache != null) { 4209 return cache.fadingEdgeLength; 4210 } 4211 } 4212 return 0; 4213 } 4214 4215 /** 4216 * Returns the width of the vertical scrollbar. 4217 * 4218 * @return The width in pixels of the vertical scrollbar or 0 if there 4219 * is no vertical scrollbar. 4220 */ 4221 public int getVerticalScrollbarWidth() { 4222 ScrollabilityCache cache = mScrollCache; 4223 if (cache != null) { 4224 ScrollBarDrawable scrollBar = cache.scrollBar; 4225 if (scrollBar != null) { 4226 int size = scrollBar.getSize(true); 4227 if (size <= 0) { 4228 size = cache.scrollBarSize; 4229 } 4230 return size; 4231 } 4232 return 0; 4233 } 4234 return 0; 4235 } 4236 4237 /** 4238 * Returns the height of the horizontal scrollbar. 4239 * 4240 * @return The height in pixels of the horizontal scrollbar or 0 if 4241 * there is no horizontal scrollbar. 4242 */ 4243 protected int getHorizontalScrollbarHeight() { 4244 ScrollabilityCache cache = mScrollCache; 4245 if (cache != null) { 4246 ScrollBarDrawable scrollBar = cache.scrollBar; 4247 if (scrollBar != null) { 4248 int size = scrollBar.getSize(false); 4249 if (size <= 0) { 4250 size = cache.scrollBarSize; 4251 } 4252 return size; 4253 } 4254 return 0; 4255 } 4256 return 0; 4257 } 4258 4259 /** 4260 * <p> 4261 * Initializes the scrollbars from a given set of styled attributes. This 4262 * method should be called by subclasses that need scrollbars and when an 4263 * instance of these subclasses is created programmatically rather than 4264 * being inflated from XML. This method is automatically called when the XML 4265 * is inflated. 4266 * </p> 4267 * 4268 * @param a the styled attributes set to initialize the scrollbars from 4269 */ 4270 protected void initializeScrollbars(TypedArray a) { 4271 initScrollCache(); 4272 4273 final ScrollabilityCache scrollabilityCache = mScrollCache; 4274 4275 if (scrollabilityCache.scrollBar == null) { 4276 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4277 } 4278 4279 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4280 4281 if (!fadeScrollbars) { 4282 scrollabilityCache.state = ScrollabilityCache.ON; 4283 } 4284 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4285 4286 4287 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4288 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4289 .getScrollBarFadeDuration()); 4290 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4291 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4292 ViewConfiguration.getScrollDefaultDelay()); 4293 4294 4295 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4296 com.android.internal.R.styleable.View_scrollbarSize, 4297 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4298 4299 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4300 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4301 4302 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4303 if (thumb != null) { 4304 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4305 } 4306 4307 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4308 false); 4309 if (alwaysDraw) { 4310 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4311 } 4312 4313 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4314 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4315 4316 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4317 if (thumb != null) { 4318 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4319 } 4320 4321 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4322 false); 4323 if (alwaysDraw) { 4324 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4325 } 4326 4327 // Apply layout direction to the new Drawables if needed 4328 final int layoutDirection = getLayoutDirection(); 4329 if (track != null) { 4330 track.setLayoutDirection(layoutDirection); 4331 } 4332 if (thumb != null) { 4333 thumb.setLayoutDirection(layoutDirection); 4334 } 4335 4336 // Re-apply user/background padding so that scrollbar(s) get added 4337 resolvePadding(); 4338 } 4339 4340 /** 4341 * <p> 4342 * Initalizes the scrollability cache if necessary. 4343 * </p> 4344 */ 4345 private void initScrollCache() { 4346 if (mScrollCache == null) { 4347 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4348 } 4349 } 4350 4351 private ScrollabilityCache getScrollCache() { 4352 initScrollCache(); 4353 return mScrollCache; 4354 } 4355 4356 /** 4357 * Set the position of the vertical scroll bar. Should be one of 4358 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4359 * {@link #SCROLLBAR_POSITION_RIGHT}. 4360 * 4361 * @param position Where the vertical scroll bar should be positioned. 4362 */ 4363 public void setVerticalScrollbarPosition(int position) { 4364 if (mVerticalScrollbarPosition != position) { 4365 mVerticalScrollbarPosition = position; 4366 computeOpaqueFlags(); 4367 resolvePadding(); 4368 } 4369 } 4370 4371 /** 4372 * @return The position where the vertical scroll bar will show, if applicable. 4373 * @see #setVerticalScrollbarPosition(int) 4374 */ 4375 public int getVerticalScrollbarPosition() { 4376 return mVerticalScrollbarPosition; 4377 } 4378 4379 ListenerInfo getListenerInfo() { 4380 if (mListenerInfo != null) { 4381 return mListenerInfo; 4382 } 4383 mListenerInfo = new ListenerInfo(); 4384 return mListenerInfo; 4385 } 4386 4387 /** 4388 * Register a callback to be invoked when focus of this view changed. 4389 * 4390 * @param l The callback that will run. 4391 */ 4392 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4393 getListenerInfo().mOnFocusChangeListener = l; 4394 } 4395 4396 /** 4397 * Add a listener that will be called when the bounds of the view change due to 4398 * layout processing. 4399 * 4400 * @param listener The listener that will be called when layout bounds change. 4401 */ 4402 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4403 ListenerInfo li = getListenerInfo(); 4404 if (li.mOnLayoutChangeListeners == null) { 4405 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4406 } 4407 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4408 li.mOnLayoutChangeListeners.add(listener); 4409 } 4410 } 4411 4412 /** 4413 * Remove a listener for layout changes. 4414 * 4415 * @param listener The listener for layout bounds change. 4416 */ 4417 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4418 ListenerInfo li = mListenerInfo; 4419 if (li == null || li.mOnLayoutChangeListeners == null) { 4420 return; 4421 } 4422 li.mOnLayoutChangeListeners.remove(listener); 4423 } 4424 4425 /** 4426 * Add a listener for attach state changes. 4427 * 4428 * This listener will be called whenever this view is attached or detached 4429 * from a window. Remove the listener using 4430 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4431 * 4432 * @param listener Listener to attach 4433 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4434 */ 4435 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4436 ListenerInfo li = getListenerInfo(); 4437 if (li.mOnAttachStateChangeListeners == null) { 4438 li.mOnAttachStateChangeListeners 4439 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4440 } 4441 li.mOnAttachStateChangeListeners.add(listener); 4442 } 4443 4444 /** 4445 * Remove a listener for attach state changes. The listener will receive no further 4446 * notification of window attach/detach events. 4447 * 4448 * @param listener Listener to remove 4449 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4450 */ 4451 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4452 ListenerInfo li = mListenerInfo; 4453 if (li == null || li.mOnAttachStateChangeListeners == null) { 4454 return; 4455 } 4456 li.mOnAttachStateChangeListeners.remove(listener); 4457 } 4458 4459 /** 4460 * Returns the focus-change callback registered for this view. 4461 * 4462 * @return The callback, or null if one is not registered. 4463 */ 4464 public OnFocusChangeListener getOnFocusChangeListener() { 4465 ListenerInfo li = mListenerInfo; 4466 return li != null ? li.mOnFocusChangeListener : null; 4467 } 4468 4469 /** 4470 * Register a callback to be invoked when this view is clicked. If this view is not 4471 * clickable, it becomes clickable. 4472 * 4473 * @param l The callback that will run 4474 * 4475 * @see #setClickable(boolean) 4476 */ 4477 public void setOnClickListener(OnClickListener l) { 4478 if (!isClickable()) { 4479 setClickable(true); 4480 } 4481 getListenerInfo().mOnClickListener = l; 4482 } 4483 4484 /** 4485 * Return whether this view has an attached OnClickListener. Returns 4486 * true if there is a listener, false if there is none. 4487 */ 4488 public boolean hasOnClickListeners() { 4489 ListenerInfo li = mListenerInfo; 4490 return (li != null && li.mOnClickListener != null); 4491 } 4492 4493 /** 4494 * Register a callback to be invoked when this view is clicked and held. If this view is not 4495 * long clickable, it becomes long clickable. 4496 * 4497 * @param l The callback that will run 4498 * 4499 * @see #setLongClickable(boolean) 4500 */ 4501 public void setOnLongClickListener(OnLongClickListener l) { 4502 if (!isLongClickable()) { 4503 setLongClickable(true); 4504 } 4505 getListenerInfo().mOnLongClickListener = l; 4506 } 4507 4508 /** 4509 * Register a callback to be invoked when the context menu for this view is 4510 * being built. If this view is not long clickable, it becomes long clickable. 4511 * 4512 * @param l The callback that will run 4513 * 4514 */ 4515 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4516 if (!isLongClickable()) { 4517 setLongClickable(true); 4518 } 4519 getListenerInfo().mOnCreateContextMenuListener = l; 4520 } 4521 4522 /** 4523 * Call this view's OnClickListener, if it is defined. Performs all normal 4524 * actions associated with clicking: reporting accessibility event, playing 4525 * a sound, etc. 4526 * 4527 * @return True there was an assigned OnClickListener that was called, false 4528 * otherwise is returned. 4529 */ 4530 public boolean performClick() { 4531 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4532 4533 ListenerInfo li = mListenerInfo; 4534 if (li != null && li.mOnClickListener != null) { 4535 playSoundEffect(SoundEffectConstants.CLICK); 4536 li.mOnClickListener.onClick(this); 4537 return true; 4538 } 4539 4540 return false; 4541 } 4542 4543 /** 4544 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4545 * this only calls the listener, and does not do any associated clicking 4546 * actions like reporting an accessibility event. 4547 * 4548 * @return True there was an assigned OnClickListener that was called, false 4549 * otherwise is returned. 4550 */ 4551 public boolean callOnClick() { 4552 ListenerInfo li = mListenerInfo; 4553 if (li != null && li.mOnClickListener != null) { 4554 li.mOnClickListener.onClick(this); 4555 return true; 4556 } 4557 return false; 4558 } 4559 4560 /** 4561 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4562 * OnLongClickListener did not consume the event. 4563 * 4564 * @return True if one of the above receivers consumed the event, false otherwise. 4565 */ 4566 public boolean performLongClick() { 4567 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4568 4569 boolean handled = false; 4570 ListenerInfo li = mListenerInfo; 4571 if (li != null && li.mOnLongClickListener != null) { 4572 handled = li.mOnLongClickListener.onLongClick(View.this); 4573 } 4574 if (!handled) { 4575 handled = showContextMenu(); 4576 } 4577 if (handled) { 4578 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4579 } 4580 return handled; 4581 } 4582 4583 /** 4584 * Performs button-related actions during a touch down event. 4585 * 4586 * @param event The event. 4587 * @return True if the down was consumed. 4588 * 4589 * @hide 4590 */ 4591 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4592 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4593 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4594 return true; 4595 } 4596 } 4597 return false; 4598 } 4599 4600 /** 4601 * Bring up the context menu for this view. 4602 * 4603 * @return Whether a context menu was displayed. 4604 */ 4605 public boolean showContextMenu() { 4606 return getParent().showContextMenuForChild(this); 4607 } 4608 4609 /** 4610 * Bring up the context menu for this view, referring to the item under the specified point. 4611 * 4612 * @param x The referenced x coordinate. 4613 * @param y The referenced y coordinate. 4614 * @param metaState The keyboard modifiers that were pressed. 4615 * @return Whether a context menu was displayed. 4616 * 4617 * @hide 4618 */ 4619 public boolean showContextMenu(float x, float y, int metaState) { 4620 return showContextMenu(); 4621 } 4622 4623 /** 4624 * Start an action mode. 4625 * 4626 * @param callback Callback that will control the lifecycle of the action mode 4627 * @return The new action mode if it is started, null otherwise 4628 * 4629 * @see ActionMode 4630 */ 4631 public ActionMode startActionMode(ActionMode.Callback callback) { 4632 ViewParent parent = getParent(); 4633 if (parent == null) return null; 4634 return parent.startActionModeForChild(this, callback); 4635 } 4636 4637 /** 4638 * Register a callback to be invoked when a hardware key is pressed in this view. 4639 * Key presses in software input methods will generally not trigger the methods of 4640 * this listener. 4641 * @param l the key listener to attach to this view 4642 */ 4643 public void setOnKeyListener(OnKeyListener l) { 4644 getListenerInfo().mOnKeyListener = l; 4645 } 4646 4647 /** 4648 * Register a callback to be invoked when a touch event is sent to this view. 4649 * @param l the touch listener to attach to this view 4650 */ 4651 public void setOnTouchListener(OnTouchListener l) { 4652 getListenerInfo().mOnTouchListener = l; 4653 } 4654 4655 /** 4656 * Register a callback to be invoked when a generic motion event is sent to this view. 4657 * @param l the generic motion listener to attach to this view 4658 */ 4659 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4660 getListenerInfo().mOnGenericMotionListener = l; 4661 } 4662 4663 /** 4664 * Register a callback to be invoked when a hover event is sent to this view. 4665 * @param l the hover listener to attach to this view 4666 */ 4667 public void setOnHoverListener(OnHoverListener l) { 4668 getListenerInfo().mOnHoverListener = l; 4669 } 4670 4671 /** 4672 * Register a drag event listener callback object for this View. The parameter is 4673 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4674 * View, the system calls the 4675 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4676 * @param l An implementation of {@link android.view.View.OnDragListener}. 4677 */ 4678 public void setOnDragListener(OnDragListener l) { 4679 getListenerInfo().mOnDragListener = l; 4680 } 4681 4682 /** 4683 * Give this view focus. This will cause 4684 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4685 * 4686 * Note: this does not check whether this {@link View} should get focus, it just 4687 * gives it focus no matter what. It should only be called internally by framework 4688 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4689 * 4690 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4691 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4692 * focus moved when requestFocus() is called. It may not always 4693 * apply, in which case use the default View.FOCUS_DOWN. 4694 * @param previouslyFocusedRect The rectangle of the view that had focus 4695 * prior in this View's coordinate system. 4696 */ 4697 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4698 if (DBG) { 4699 System.out.println(this + " requestFocus()"); 4700 } 4701 4702 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4703 mPrivateFlags |= PFLAG_FOCUSED; 4704 4705 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4706 4707 if (mParent != null) { 4708 mParent.requestChildFocus(this, this); 4709 } 4710 4711 if (mAttachInfo != null) { 4712 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4713 } 4714 4715 manageFocusHotspot(true, oldFocus); 4716 onFocusChanged(true, direction, previouslyFocusedRect); 4717 refreshDrawableState(); 4718 } 4719 } 4720 4721 /** 4722 * Forwards focus information to the background drawable, if necessary. When 4723 * the view is gaining focus, <code>v</code> is the previous focus holder. 4724 * When the view is losing focus, <code>v</code> is the next focus holder. 4725 * 4726 * @param focused whether this view is focused 4727 * @param v previous or the next focus holder, or null if none 4728 */ 4729 private void manageFocusHotspot(boolean focused, View v) { 4730 if (mBackground != null && mBackground.supportsHotspots()) { 4731 final Rect r = new Rect(); 4732 if (!focused && v != null) { 4733 v.getBoundsOnScreen(r); 4734 final int[] location = new int[2]; 4735 getLocationOnScreen(location); 4736 r.offset(-location[0], -location[1]); 4737 } else { 4738 r.set(0, 0, mRight - mLeft, mBottom - mTop); 4739 } 4740 4741 final float x = r.exactCenterX(); 4742 final float y = r.exactCenterY(); 4743 mBackground.setHotspot(R.attr.state_focused, x, y); 4744 4745 if (!focused) { 4746 mBackground.removeHotspot(R.attr.state_focused); 4747 } 4748 } 4749 } 4750 4751 /** 4752 * Request that a rectangle of this view be visible on the screen, 4753 * scrolling if necessary just enough. 4754 * 4755 * <p>A View should call this if it maintains some notion of which part 4756 * of its content is interesting. For example, a text editing view 4757 * should call this when its cursor moves. 4758 * 4759 * @param rectangle The rectangle. 4760 * @return Whether any parent scrolled. 4761 */ 4762 public boolean requestRectangleOnScreen(Rect rectangle) { 4763 return requestRectangleOnScreen(rectangle, false); 4764 } 4765 4766 /** 4767 * Request that a rectangle of this view be visible on the screen, 4768 * scrolling if necessary just enough. 4769 * 4770 * <p>A View should call this if it maintains some notion of which part 4771 * of its content is interesting. For example, a text editing view 4772 * should call this when its cursor moves. 4773 * 4774 * <p>When <code>immediate</code> is set to true, scrolling will not be 4775 * animated. 4776 * 4777 * @param rectangle The rectangle. 4778 * @param immediate True to forbid animated scrolling, false otherwise 4779 * @return Whether any parent scrolled. 4780 */ 4781 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4782 if (mParent == null) { 4783 return false; 4784 } 4785 4786 View child = this; 4787 4788 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4789 position.set(rectangle); 4790 4791 ViewParent parent = mParent; 4792 boolean scrolled = false; 4793 while (parent != null) { 4794 rectangle.set((int) position.left, (int) position.top, 4795 (int) position.right, (int) position.bottom); 4796 4797 scrolled |= parent.requestChildRectangleOnScreen(child, 4798 rectangle, immediate); 4799 4800 if (!child.hasIdentityMatrix()) { 4801 child.getMatrix().mapRect(position); 4802 } 4803 4804 position.offset(child.mLeft, child.mTop); 4805 4806 if (!(parent instanceof View)) { 4807 break; 4808 } 4809 4810 View parentView = (View) parent; 4811 4812 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 4813 4814 child = parentView; 4815 parent = child.getParent(); 4816 } 4817 4818 return scrolled; 4819 } 4820 4821 /** 4822 * Called when this view wants to give up focus. If focus is cleared 4823 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 4824 * <p> 4825 * <strong>Note:</strong> When a View clears focus the framework is trying 4826 * to give focus to the first focusable View from the top. Hence, if this 4827 * View is the first from the top that can take focus, then all callbacks 4828 * related to clearing focus will be invoked after wich the framework will 4829 * give focus to this view. 4830 * </p> 4831 */ 4832 public void clearFocus() { 4833 if (DBG) { 4834 System.out.println(this + " clearFocus()"); 4835 } 4836 4837 clearFocusInternal(null, true, true); 4838 } 4839 4840 /** 4841 * Clears focus from the view, optionally propagating the change up through 4842 * the parent hierarchy and requesting that the root view place new focus. 4843 * 4844 * @param propagate whether to propagate the change up through the parent 4845 * hierarchy 4846 * @param refocus when propagate is true, specifies whether to request the 4847 * root view place new focus 4848 */ 4849 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 4850 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 4851 mPrivateFlags &= ~PFLAG_FOCUSED; 4852 4853 if (propagate && mParent != null) { 4854 mParent.clearChildFocus(this); 4855 } 4856 4857 onFocusChanged(false, 0, null); 4858 4859 manageFocusHotspot(false, focused); 4860 refreshDrawableState(); 4861 4862 if (propagate && (!refocus || !rootViewRequestFocus())) { 4863 notifyGlobalFocusCleared(this); 4864 } 4865 } 4866 } 4867 4868 void notifyGlobalFocusCleared(View oldFocus) { 4869 if (oldFocus != null && mAttachInfo != null) { 4870 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 4871 } 4872 } 4873 4874 boolean rootViewRequestFocus() { 4875 final View root = getRootView(); 4876 return root != null && root.requestFocus(); 4877 } 4878 4879 /** 4880 * Called internally by the view system when a new view is getting focus. 4881 * This is what clears the old focus. 4882 * <p> 4883 * <b>NOTE:</b> The parent view's focused child must be updated manually 4884 * after calling this method. Otherwise, the view hierarchy may be left in 4885 * an inconstent state. 4886 */ 4887 void unFocus(View focused) { 4888 if (DBG) { 4889 System.out.println(this + " unFocus()"); 4890 } 4891 4892 clearFocusInternal(focused, false, false); 4893 } 4894 4895 /** 4896 * Returns true if this view has focus iteself, or is the ancestor of the 4897 * view that has focus. 4898 * 4899 * @return True if this view has or contains focus, false otherwise. 4900 */ 4901 @ViewDebug.ExportedProperty(category = "focus") 4902 public boolean hasFocus() { 4903 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 4904 } 4905 4906 /** 4907 * Returns true if this view is focusable or if it contains a reachable View 4908 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 4909 * is a View whose parents do not block descendants focus. 4910 * 4911 * Only {@link #VISIBLE} views are considered focusable. 4912 * 4913 * @return True if the view is focusable or if the view contains a focusable 4914 * View, false otherwise. 4915 * 4916 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 4917 */ 4918 public boolean hasFocusable() { 4919 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 4920 } 4921 4922 /** 4923 * Called by the view system when the focus state of this view changes. 4924 * When the focus change event is caused by directional navigation, direction 4925 * and previouslyFocusedRect provide insight into where the focus is coming from. 4926 * When overriding, be sure to call up through to the super class so that 4927 * the standard focus handling will occur. 4928 * 4929 * @param gainFocus True if the View has focus; false otherwise. 4930 * @param direction The direction focus has moved when requestFocus() 4931 * is called to give this view focus. Values are 4932 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 4933 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 4934 * It may not always apply, in which case use the default. 4935 * @param previouslyFocusedRect The rectangle, in this view's coordinate 4936 * system, of the previously focused view. If applicable, this will be 4937 * passed in as finer grained information about where the focus is coming 4938 * from (in addition to direction). Will be <code>null</code> otherwise. 4939 */ 4940 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 4941 @Nullable Rect previouslyFocusedRect) { 4942 if (gainFocus) { 4943 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 4944 } else { 4945 notifyViewAccessibilityStateChangedIfNeeded( 4946 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 4947 } 4948 4949 InputMethodManager imm = InputMethodManager.peekInstance(); 4950 if (!gainFocus) { 4951 if (isPressed()) { 4952 setPressed(false); 4953 } 4954 if (imm != null && mAttachInfo != null 4955 && mAttachInfo.mHasWindowFocus) { 4956 imm.focusOut(this); 4957 } 4958 onFocusLost(); 4959 } else if (imm != null && mAttachInfo != null 4960 && mAttachInfo.mHasWindowFocus) { 4961 imm.focusIn(this); 4962 } 4963 4964 invalidate(true); 4965 ListenerInfo li = mListenerInfo; 4966 if (li != null && li.mOnFocusChangeListener != null) { 4967 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 4968 } 4969 4970 if (mAttachInfo != null) { 4971 mAttachInfo.mKeyDispatchState.reset(this); 4972 } 4973 } 4974 4975 /** 4976 * Sends an accessibility event of the given type. If accessibility is 4977 * not enabled this method has no effect. The default implementation calls 4978 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 4979 * to populate information about the event source (this View), then calls 4980 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 4981 * populate the text content of the event source including its descendants, 4982 * and last calls 4983 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 4984 * on its parent to resuest sending of the event to interested parties. 4985 * <p> 4986 * If an {@link AccessibilityDelegate} has been specified via calling 4987 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 4988 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 4989 * responsible for handling this call. 4990 * </p> 4991 * 4992 * @param eventType The type of the event to send, as defined by several types from 4993 * {@link android.view.accessibility.AccessibilityEvent}, such as 4994 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 4995 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 4996 * 4997 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 4998 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 4999 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5000 * @see AccessibilityDelegate 5001 */ 5002 public void sendAccessibilityEvent(int eventType) { 5003 if (mAccessibilityDelegate != null) { 5004 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5005 } else { 5006 sendAccessibilityEventInternal(eventType); 5007 } 5008 } 5009 5010 /** 5011 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5012 * {@link AccessibilityEvent} to make an announcement which is related to some 5013 * sort of a context change for which none of the events representing UI transitions 5014 * is a good fit. For example, announcing a new page in a book. If accessibility 5015 * is not enabled this method does nothing. 5016 * 5017 * @param text The announcement text. 5018 */ 5019 public void announceForAccessibility(CharSequence text) { 5020 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5021 AccessibilityEvent event = AccessibilityEvent.obtain( 5022 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5023 onInitializeAccessibilityEvent(event); 5024 event.getText().add(text); 5025 event.setContentDescription(null); 5026 mParent.requestSendAccessibilityEvent(this, event); 5027 } 5028 } 5029 5030 /** 5031 * @see #sendAccessibilityEvent(int) 5032 * 5033 * Note: Called from the default {@link AccessibilityDelegate}. 5034 */ 5035 void sendAccessibilityEventInternal(int eventType) { 5036 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5037 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5038 } 5039 } 5040 5041 /** 5042 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5043 * takes as an argument an empty {@link AccessibilityEvent} and does not 5044 * perform a check whether accessibility is enabled. 5045 * <p> 5046 * If an {@link AccessibilityDelegate} has been specified via calling 5047 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5048 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5049 * is responsible for handling this call. 5050 * </p> 5051 * 5052 * @param event The event to send. 5053 * 5054 * @see #sendAccessibilityEvent(int) 5055 */ 5056 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5057 if (mAccessibilityDelegate != null) { 5058 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5059 } else { 5060 sendAccessibilityEventUncheckedInternal(event); 5061 } 5062 } 5063 5064 /** 5065 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5066 * 5067 * Note: Called from the default {@link AccessibilityDelegate}. 5068 */ 5069 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5070 if (!isShown()) { 5071 return; 5072 } 5073 onInitializeAccessibilityEvent(event); 5074 // Only a subset of accessibility events populates text content. 5075 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5076 dispatchPopulateAccessibilityEvent(event); 5077 } 5078 // In the beginning we called #isShown(), so we know that getParent() is not null. 5079 getParent().requestSendAccessibilityEvent(this, event); 5080 } 5081 5082 /** 5083 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5084 * to its children for adding their text content to the event. Note that the 5085 * event text is populated in a separate dispatch path since we add to the 5086 * event not only the text of the source but also the text of all its descendants. 5087 * A typical implementation will call 5088 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5089 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5090 * on each child. Override this method if custom population of the event text 5091 * content is required. 5092 * <p> 5093 * If an {@link AccessibilityDelegate} has been specified via calling 5094 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5095 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5096 * is responsible for handling this call. 5097 * </p> 5098 * <p> 5099 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5100 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5101 * </p> 5102 * 5103 * @param event The event. 5104 * 5105 * @return True if the event population was completed. 5106 */ 5107 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5108 if (mAccessibilityDelegate != null) { 5109 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5110 } else { 5111 return dispatchPopulateAccessibilityEventInternal(event); 5112 } 5113 } 5114 5115 /** 5116 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5117 * 5118 * Note: Called from the default {@link AccessibilityDelegate}. 5119 */ 5120 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5121 onPopulateAccessibilityEvent(event); 5122 return false; 5123 } 5124 5125 /** 5126 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5127 * giving a chance to this View to populate the accessibility event with its 5128 * text content. While this method is free to modify event 5129 * attributes other than text content, doing so should normally be performed in 5130 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5131 * <p> 5132 * Example: Adding formatted date string to an accessibility event in addition 5133 * to the text added by the super implementation: 5134 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5135 * super.onPopulateAccessibilityEvent(event); 5136 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5137 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5138 * mCurrentDate.getTimeInMillis(), flags); 5139 * event.getText().add(selectedDateUtterance); 5140 * }</pre> 5141 * <p> 5142 * If an {@link AccessibilityDelegate} has been specified via calling 5143 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5144 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5145 * is responsible for handling this call. 5146 * </p> 5147 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5148 * information to the event, in case the default implementation has basic information to add. 5149 * </p> 5150 * 5151 * @param event The accessibility event which to populate. 5152 * 5153 * @see #sendAccessibilityEvent(int) 5154 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5155 */ 5156 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5157 if (mAccessibilityDelegate != null) { 5158 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5159 } else { 5160 onPopulateAccessibilityEventInternal(event); 5161 } 5162 } 5163 5164 /** 5165 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5166 * 5167 * Note: Called from the default {@link AccessibilityDelegate}. 5168 */ 5169 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5170 } 5171 5172 /** 5173 * Initializes an {@link AccessibilityEvent} with information about 5174 * this View which is the event source. In other words, the source of 5175 * an accessibility event is the view whose state change triggered firing 5176 * the event. 5177 * <p> 5178 * Example: Setting the password property of an event in addition 5179 * to properties set by the super implementation: 5180 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5181 * super.onInitializeAccessibilityEvent(event); 5182 * event.setPassword(true); 5183 * }</pre> 5184 * <p> 5185 * If an {@link AccessibilityDelegate} has been specified via calling 5186 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5187 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5188 * is responsible for handling this call. 5189 * </p> 5190 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5191 * information to the event, in case the default implementation has basic information to add. 5192 * </p> 5193 * @param event The event to initialize. 5194 * 5195 * @see #sendAccessibilityEvent(int) 5196 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5197 */ 5198 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5199 if (mAccessibilityDelegate != null) { 5200 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5201 } else { 5202 onInitializeAccessibilityEventInternal(event); 5203 } 5204 } 5205 5206 /** 5207 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5208 * 5209 * Note: Called from the default {@link AccessibilityDelegate}. 5210 */ 5211 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5212 event.setSource(this); 5213 event.setClassName(View.class.getName()); 5214 event.setPackageName(getContext().getPackageName()); 5215 event.setEnabled(isEnabled()); 5216 event.setContentDescription(mContentDescription); 5217 5218 switch (event.getEventType()) { 5219 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5220 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5221 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5222 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5223 event.setItemCount(focusablesTempList.size()); 5224 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5225 if (mAttachInfo != null) { 5226 focusablesTempList.clear(); 5227 } 5228 } break; 5229 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5230 CharSequence text = getIterableTextForAccessibility(); 5231 if (text != null && text.length() > 0) { 5232 event.setFromIndex(getAccessibilitySelectionStart()); 5233 event.setToIndex(getAccessibilitySelectionEnd()); 5234 event.setItemCount(text.length()); 5235 } 5236 } break; 5237 } 5238 } 5239 5240 /** 5241 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5242 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5243 * This method is responsible for obtaining an accessibility node info from a 5244 * pool of reusable instances and calling 5245 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5246 * initialize the former. 5247 * <p> 5248 * Note: The client is responsible for recycling the obtained instance by calling 5249 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5250 * </p> 5251 * 5252 * @return A populated {@link AccessibilityNodeInfo}. 5253 * 5254 * @see AccessibilityNodeInfo 5255 */ 5256 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5257 if (mAccessibilityDelegate != null) { 5258 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5259 } else { 5260 return createAccessibilityNodeInfoInternal(); 5261 } 5262 } 5263 5264 /** 5265 * @see #createAccessibilityNodeInfo() 5266 */ 5267 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5268 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5269 if (provider != null) { 5270 return provider.createAccessibilityNodeInfo(View.NO_ID); 5271 } else { 5272 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5273 onInitializeAccessibilityNodeInfo(info); 5274 return info; 5275 } 5276 } 5277 5278 /** 5279 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5280 * The base implementation sets: 5281 * <ul> 5282 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5283 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5284 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5285 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5286 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5287 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5288 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5289 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5290 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5291 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5292 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5293 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5294 * </ul> 5295 * <p> 5296 * Subclasses should override this method, call the super implementation, 5297 * and set additional attributes. 5298 * </p> 5299 * <p> 5300 * If an {@link AccessibilityDelegate} has been specified via calling 5301 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5302 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5303 * is responsible for handling this call. 5304 * </p> 5305 * 5306 * @param info The instance to initialize. 5307 */ 5308 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5309 if (mAccessibilityDelegate != null) { 5310 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5311 } else { 5312 onInitializeAccessibilityNodeInfoInternal(info); 5313 } 5314 } 5315 5316 /** 5317 * Gets the location of this view in screen coordintates. 5318 * 5319 * @param outRect The output location 5320 */ 5321 void getBoundsOnScreen(Rect outRect) { 5322 if (mAttachInfo == null) { 5323 return; 5324 } 5325 5326 RectF position = mAttachInfo.mTmpTransformRect; 5327 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5328 5329 if (!hasIdentityMatrix()) { 5330 getMatrix().mapRect(position); 5331 } 5332 5333 position.offset(mLeft, mTop); 5334 5335 ViewParent parent = mParent; 5336 while (parent instanceof View) { 5337 View parentView = (View) parent; 5338 5339 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5340 5341 if (!parentView.hasIdentityMatrix()) { 5342 parentView.getMatrix().mapRect(position); 5343 } 5344 5345 position.offset(parentView.mLeft, parentView.mTop); 5346 5347 parent = parentView.mParent; 5348 } 5349 5350 if (parent instanceof ViewRootImpl) { 5351 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5352 position.offset(0, -viewRootImpl.mCurScrollY); 5353 } 5354 5355 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5356 5357 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5358 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5359 } 5360 5361 /** 5362 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5363 * 5364 * Note: Called from the default {@link AccessibilityDelegate}. 5365 */ 5366 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5367 Rect bounds = mAttachInfo.mTmpInvalRect; 5368 5369 getDrawingRect(bounds); 5370 info.setBoundsInParent(bounds); 5371 5372 getBoundsOnScreen(bounds); 5373 info.setBoundsInScreen(bounds); 5374 5375 ViewParent parent = getParentForAccessibility(); 5376 if (parent instanceof View) { 5377 info.setParent((View) parent); 5378 } 5379 5380 if (mID != View.NO_ID) { 5381 View rootView = getRootView(); 5382 if (rootView == null) { 5383 rootView = this; 5384 } 5385 View label = rootView.findLabelForView(this, mID); 5386 if (label != null) { 5387 info.setLabeledBy(label); 5388 } 5389 5390 if ((mAttachInfo.mAccessibilityFetchFlags 5391 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5392 && Resources.resourceHasPackage(mID)) { 5393 try { 5394 String viewId = getResources().getResourceName(mID); 5395 info.setViewIdResourceName(viewId); 5396 } catch (Resources.NotFoundException nfe) { 5397 /* ignore */ 5398 } 5399 } 5400 } 5401 5402 if (mLabelForId != View.NO_ID) { 5403 View rootView = getRootView(); 5404 if (rootView == null) { 5405 rootView = this; 5406 } 5407 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5408 if (labeled != null) { 5409 info.setLabelFor(labeled); 5410 } 5411 } 5412 5413 info.setVisibleToUser(isVisibleToUser()); 5414 5415 info.setPackageName(mContext.getPackageName()); 5416 info.setClassName(View.class.getName()); 5417 info.setContentDescription(getContentDescription()); 5418 5419 info.setEnabled(isEnabled()); 5420 info.setClickable(isClickable()); 5421 info.setFocusable(isFocusable()); 5422 info.setFocused(isFocused()); 5423 info.setAccessibilityFocused(isAccessibilityFocused()); 5424 info.setSelected(isSelected()); 5425 info.setLongClickable(isLongClickable()); 5426 info.setLiveRegion(getAccessibilityLiveRegion()); 5427 5428 // TODO: These make sense only if we are in an AdapterView but all 5429 // views can be selected. Maybe from accessibility perspective 5430 // we should report as selectable view in an AdapterView. 5431 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5432 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5433 5434 if (isFocusable()) { 5435 if (isFocused()) { 5436 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5437 } else { 5438 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5439 } 5440 } 5441 5442 if (!isAccessibilityFocused()) { 5443 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5444 } else { 5445 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5446 } 5447 5448 if (isClickable() && isEnabled()) { 5449 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5450 } 5451 5452 if (isLongClickable() && isEnabled()) { 5453 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5454 } 5455 5456 CharSequence text = getIterableTextForAccessibility(); 5457 if (text != null && text.length() > 0) { 5458 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5459 5460 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5461 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5462 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5463 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5464 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5465 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5466 } 5467 } 5468 5469 private View findLabelForView(View view, int labeledId) { 5470 if (mMatchLabelForPredicate == null) { 5471 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5472 } 5473 mMatchLabelForPredicate.mLabeledId = labeledId; 5474 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5475 } 5476 5477 /** 5478 * Computes whether this view is visible to the user. Such a view is 5479 * attached, visible, all its predecessors are visible, it is not clipped 5480 * entirely by its predecessors, and has an alpha greater than zero. 5481 * 5482 * @return Whether the view is visible on the screen. 5483 * 5484 * @hide 5485 */ 5486 protected boolean isVisibleToUser() { 5487 return isVisibleToUser(null); 5488 } 5489 5490 /** 5491 * Computes whether the given portion of this view is visible to the user. 5492 * Such a view is attached, visible, all its predecessors are visible, 5493 * has an alpha greater than zero, and the specified portion is not 5494 * clipped entirely by its predecessors. 5495 * 5496 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5497 * <code>null</code>, and the entire view will be tested in this case. 5498 * When <code>true</code> is returned by the function, the actual visible 5499 * region will be stored in this parameter; that is, if boundInView is fully 5500 * contained within the view, no modification will be made, otherwise regions 5501 * outside of the visible area of the view will be clipped. 5502 * 5503 * @return Whether the specified portion of the view is visible on the screen. 5504 * 5505 * @hide 5506 */ 5507 protected boolean isVisibleToUser(Rect boundInView) { 5508 if (mAttachInfo != null) { 5509 // Attached to invisible window means this view is not visible. 5510 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5511 return false; 5512 } 5513 // An invisible predecessor or one with alpha zero means 5514 // that this view is not visible to the user. 5515 Object current = this; 5516 while (current instanceof View) { 5517 View view = (View) current; 5518 // We have attach info so this view is attached and there is no 5519 // need to check whether we reach to ViewRootImpl on the way up. 5520 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5521 view.getVisibility() != VISIBLE) { 5522 return false; 5523 } 5524 current = view.mParent; 5525 } 5526 // Check if the view is entirely covered by its predecessors. 5527 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5528 Point offset = mAttachInfo.mPoint; 5529 if (!getGlobalVisibleRect(visibleRect, offset)) { 5530 return false; 5531 } 5532 // Check if the visible portion intersects the rectangle of interest. 5533 if (boundInView != null) { 5534 visibleRect.offset(-offset.x, -offset.y); 5535 return boundInView.intersect(visibleRect); 5536 } 5537 return true; 5538 } 5539 return false; 5540 } 5541 5542 /** 5543 * Returns the delegate for implementing accessibility support via 5544 * composition. For more details see {@link AccessibilityDelegate}. 5545 * 5546 * @return The delegate, or null if none set. 5547 * 5548 * @hide 5549 */ 5550 public AccessibilityDelegate getAccessibilityDelegate() { 5551 return mAccessibilityDelegate; 5552 } 5553 5554 /** 5555 * Sets a delegate for implementing accessibility support via composition as 5556 * opposed to inheritance. The delegate's primary use is for implementing 5557 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5558 * 5559 * @param delegate The delegate instance. 5560 * 5561 * @see AccessibilityDelegate 5562 */ 5563 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5564 mAccessibilityDelegate = delegate; 5565 } 5566 5567 /** 5568 * Gets the provider for managing a virtual view hierarchy rooted at this View 5569 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5570 * that explore the window content. 5571 * <p> 5572 * If this method returns an instance, this instance is responsible for managing 5573 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5574 * View including the one representing the View itself. Similarly the returned 5575 * instance is responsible for performing accessibility actions on any virtual 5576 * view or the root view itself. 5577 * </p> 5578 * <p> 5579 * If an {@link AccessibilityDelegate} has been specified via calling 5580 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5581 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5582 * is responsible for handling this call. 5583 * </p> 5584 * 5585 * @return The provider. 5586 * 5587 * @see AccessibilityNodeProvider 5588 */ 5589 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5590 if (mAccessibilityDelegate != null) { 5591 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5592 } else { 5593 return null; 5594 } 5595 } 5596 5597 /** 5598 * Gets the unique identifier of this view on the screen for accessibility purposes. 5599 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5600 * 5601 * @return The view accessibility id. 5602 * 5603 * @hide 5604 */ 5605 public int getAccessibilityViewId() { 5606 if (mAccessibilityViewId == NO_ID) { 5607 mAccessibilityViewId = sNextAccessibilityViewId++; 5608 } 5609 return mAccessibilityViewId; 5610 } 5611 5612 /** 5613 * Gets the unique identifier of the window in which this View reseides. 5614 * 5615 * @return The window accessibility id. 5616 * 5617 * @hide 5618 */ 5619 public int getAccessibilityWindowId() { 5620 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5621 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5622 } 5623 5624 /** 5625 * Gets the {@link View} description. It briefly describes the view and is 5626 * primarily used for accessibility support. Set this property to enable 5627 * better accessibility support for your application. This is especially 5628 * true for views that do not have textual representation (For example, 5629 * ImageButton). 5630 * 5631 * @return The content description. 5632 * 5633 * @attr ref android.R.styleable#View_contentDescription 5634 */ 5635 @ViewDebug.ExportedProperty(category = "accessibility") 5636 public CharSequence getContentDescription() { 5637 return mContentDescription; 5638 } 5639 5640 /** 5641 * Sets the {@link View} description. It briefly describes the view and is 5642 * primarily used for accessibility support. Set this property to enable 5643 * better accessibility support for your application. This is especially 5644 * true for views that do not have textual representation (For example, 5645 * ImageButton). 5646 * 5647 * @param contentDescription The content description. 5648 * 5649 * @attr ref android.R.styleable#View_contentDescription 5650 */ 5651 @RemotableViewMethod 5652 public void setContentDescription(CharSequence contentDescription) { 5653 if (mContentDescription == null) { 5654 if (contentDescription == null) { 5655 return; 5656 } 5657 } else if (mContentDescription.equals(contentDescription)) { 5658 return; 5659 } 5660 mContentDescription = contentDescription; 5661 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5662 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5663 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5664 notifySubtreeAccessibilityStateChangedIfNeeded(); 5665 } else { 5666 notifyViewAccessibilityStateChangedIfNeeded( 5667 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5668 } 5669 } 5670 5671 /** 5672 * Gets the id of a view for which this view serves as a label for 5673 * accessibility purposes. 5674 * 5675 * @return The labeled view id. 5676 */ 5677 @ViewDebug.ExportedProperty(category = "accessibility") 5678 public int getLabelFor() { 5679 return mLabelForId; 5680 } 5681 5682 /** 5683 * Sets the id of a view for which this view serves as a label for 5684 * accessibility purposes. 5685 * 5686 * @param id The labeled view id. 5687 */ 5688 @RemotableViewMethod 5689 public void setLabelFor(int id) { 5690 mLabelForId = id; 5691 if (mLabelForId != View.NO_ID 5692 && mID == View.NO_ID) { 5693 mID = generateViewId(); 5694 } 5695 } 5696 5697 /** 5698 * Invoked whenever this view loses focus, either by losing window focus or by losing 5699 * focus within its window. This method can be used to clear any state tied to the 5700 * focus. For instance, if a button is held pressed with the trackball and the window 5701 * loses focus, this method can be used to cancel the press. 5702 * 5703 * Subclasses of View overriding this method should always call super.onFocusLost(). 5704 * 5705 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 5706 * @see #onWindowFocusChanged(boolean) 5707 * 5708 * @hide pending API council approval 5709 */ 5710 protected void onFocusLost() { 5711 resetPressedState(); 5712 } 5713 5714 private void resetPressedState() { 5715 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 5716 return; 5717 } 5718 5719 if (isPressed()) { 5720 setPressed(false); 5721 5722 if (!mHasPerformedLongPress) { 5723 removeLongPressCallback(); 5724 } 5725 } 5726 } 5727 5728 /** 5729 * Returns true if this view has focus 5730 * 5731 * @return True if this view has focus, false otherwise. 5732 */ 5733 @ViewDebug.ExportedProperty(category = "focus") 5734 public boolean isFocused() { 5735 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5736 } 5737 5738 /** 5739 * Find the view in the hierarchy rooted at this view that currently has 5740 * focus. 5741 * 5742 * @return The view that currently has focus, or null if no focused view can 5743 * be found. 5744 */ 5745 public View findFocus() { 5746 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 5747 } 5748 5749 /** 5750 * Indicates whether this view is one of the set of scrollable containers in 5751 * its window. 5752 * 5753 * @return whether this view is one of the set of scrollable containers in 5754 * its window 5755 * 5756 * @attr ref android.R.styleable#View_isScrollContainer 5757 */ 5758 public boolean isScrollContainer() { 5759 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 5760 } 5761 5762 /** 5763 * Change whether this view is one of the set of scrollable containers in 5764 * its window. This will be used to determine whether the window can 5765 * resize or must pan when a soft input area is open -- scrollable 5766 * containers allow the window to use resize mode since the container 5767 * will appropriately shrink. 5768 * 5769 * @attr ref android.R.styleable#View_isScrollContainer 5770 */ 5771 public void setScrollContainer(boolean isScrollContainer) { 5772 if (isScrollContainer) { 5773 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 5774 mAttachInfo.mScrollContainers.add(this); 5775 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 5776 } 5777 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 5778 } else { 5779 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 5780 mAttachInfo.mScrollContainers.remove(this); 5781 } 5782 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 5783 } 5784 } 5785 5786 /** 5787 * Returns the quality of the drawing cache. 5788 * 5789 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5790 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5791 * 5792 * @see #setDrawingCacheQuality(int) 5793 * @see #setDrawingCacheEnabled(boolean) 5794 * @see #isDrawingCacheEnabled() 5795 * 5796 * @attr ref android.R.styleable#View_drawingCacheQuality 5797 */ 5798 @DrawingCacheQuality 5799 public int getDrawingCacheQuality() { 5800 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 5801 } 5802 5803 /** 5804 * Set the drawing cache quality of this view. This value is used only when the 5805 * drawing cache is enabled 5806 * 5807 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 5808 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 5809 * 5810 * @see #getDrawingCacheQuality() 5811 * @see #setDrawingCacheEnabled(boolean) 5812 * @see #isDrawingCacheEnabled() 5813 * 5814 * @attr ref android.R.styleable#View_drawingCacheQuality 5815 */ 5816 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 5817 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 5818 } 5819 5820 /** 5821 * Returns whether the screen should remain on, corresponding to the current 5822 * value of {@link #KEEP_SCREEN_ON}. 5823 * 5824 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 5825 * 5826 * @see #setKeepScreenOn(boolean) 5827 * 5828 * @attr ref android.R.styleable#View_keepScreenOn 5829 */ 5830 public boolean getKeepScreenOn() { 5831 return (mViewFlags & KEEP_SCREEN_ON) != 0; 5832 } 5833 5834 /** 5835 * Controls whether the screen should remain on, modifying the 5836 * value of {@link #KEEP_SCREEN_ON}. 5837 * 5838 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 5839 * 5840 * @see #getKeepScreenOn() 5841 * 5842 * @attr ref android.R.styleable#View_keepScreenOn 5843 */ 5844 public void setKeepScreenOn(boolean keepScreenOn) { 5845 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 5846 } 5847 5848 /** 5849 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5850 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5851 * 5852 * @attr ref android.R.styleable#View_nextFocusLeft 5853 */ 5854 public int getNextFocusLeftId() { 5855 return mNextFocusLeftId; 5856 } 5857 5858 /** 5859 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 5860 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 5861 * decide automatically. 5862 * 5863 * @attr ref android.R.styleable#View_nextFocusLeft 5864 */ 5865 public void setNextFocusLeftId(int nextFocusLeftId) { 5866 mNextFocusLeftId = nextFocusLeftId; 5867 } 5868 5869 /** 5870 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5871 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5872 * 5873 * @attr ref android.R.styleable#View_nextFocusRight 5874 */ 5875 public int getNextFocusRightId() { 5876 return mNextFocusRightId; 5877 } 5878 5879 /** 5880 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 5881 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 5882 * decide automatically. 5883 * 5884 * @attr ref android.R.styleable#View_nextFocusRight 5885 */ 5886 public void setNextFocusRightId(int nextFocusRightId) { 5887 mNextFocusRightId = nextFocusRightId; 5888 } 5889 5890 /** 5891 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5892 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5893 * 5894 * @attr ref android.R.styleable#View_nextFocusUp 5895 */ 5896 public int getNextFocusUpId() { 5897 return mNextFocusUpId; 5898 } 5899 5900 /** 5901 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 5902 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 5903 * decide automatically. 5904 * 5905 * @attr ref android.R.styleable#View_nextFocusUp 5906 */ 5907 public void setNextFocusUpId(int nextFocusUpId) { 5908 mNextFocusUpId = nextFocusUpId; 5909 } 5910 5911 /** 5912 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5913 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5914 * 5915 * @attr ref android.R.styleable#View_nextFocusDown 5916 */ 5917 public int getNextFocusDownId() { 5918 return mNextFocusDownId; 5919 } 5920 5921 /** 5922 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 5923 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 5924 * decide automatically. 5925 * 5926 * @attr ref android.R.styleable#View_nextFocusDown 5927 */ 5928 public void setNextFocusDownId(int nextFocusDownId) { 5929 mNextFocusDownId = nextFocusDownId; 5930 } 5931 5932 /** 5933 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5934 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 5935 * 5936 * @attr ref android.R.styleable#View_nextFocusForward 5937 */ 5938 public int getNextFocusForwardId() { 5939 return mNextFocusForwardId; 5940 } 5941 5942 /** 5943 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 5944 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 5945 * decide automatically. 5946 * 5947 * @attr ref android.R.styleable#View_nextFocusForward 5948 */ 5949 public void setNextFocusForwardId(int nextFocusForwardId) { 5950 mNextFocusForwardId = nextFocusForwardId; 5951 } 5952 5953 /** 5954 * Returns the visibility of this view and all of its ancestors 5955 * 5956 * @return True if this view and all of its ancestors are {@link #VISIBLE} 5957 */ 5958 public boolean isShown() { 5959 View current = this; 5960 //noinspection ConstantConditions 5961 do { 5962 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 5963 return false; 5964 } 5965 ViewParent parent = current.mParent; 5966 if (parent == null) { 5967 return false; // We are not attached to the view root 5968 } 5969 if (!(parent instanceof View)) { 5970 return true; 5971 } 5972 current = (View) parent; 5973 } while (current != null); 5974 5975 return false; 5976 } 5977 5978 /** 5979 * Called by the view hierarchy when the content insets for a window have 5980 * changed, to allow it to adjust its content to fit within those windows. 5981 * The content insets tell you the space that the status bar, input method, 5982 * and other system windows infringe on the application's window. 5983 * 5984 * <p>You do not normally need to deal with this function, since the default 5985 * window decoration given to applications takes care of applying it to the 5986 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 5987 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 5988 * and your content can be placed under those system elements. You can then 5989 * use this method within your view hierarchy if you have parts of your UI 5990 * which you would like to ensure are not being covered. 5991 * 5992 * <p>The default implementation of this method simply applies the content 5993 * insets to the view's padding, consuming that content (modifying the 5994 * insets to be 0), and returning true. This behavior is off by default, but can 5995 * be enabled through {@link #setFitsSystemWindows(boolean)}. 5996 * 5997 * <p>This function's traversal down the hierarchy is depth-first. The same content 5998 * insets object is propagated down the hierarchy, so any changes made to it will 5999 * be seen by all following views (including potentially ones above in 6000 * the hierarchy since this is a depth-first traversal). The first view 6001 * that returns true will abort the entire traversal. 6002 * 6003 * <p>The default implementation works well for a situation where it is 6004 * used with a container that covers the entire window, allowing it to 6005 * apply the appropriate insets to its content on all edges. If you need 6006 * a more complicated layout (such as two different views fitting system 6007 * windows, one on the top of the window, and one on the bottom), 6008 * you can override the method and handle the insets however you would like. 6009 * Note that the insets provided by the framework are always relative to the 6010 * far edges of the window, not accounting for the location of the called view 6011 * within that window. (In fact when this method is called you do not yet know 6012 * where the layout will place the view, as it is done before layout happens.) 6013 * 6014 * <p>Note: unlike many View methods, there is no dispatch phase to this 6015 * call. If you are overriding it in a ViewGroup and want to allow the 6016 * call to continue to your children, you must be sure to call the super 6017 * implementation. 6018 * 6019 * <p>Here is a sample layout that makes use of fitting system windows 6020 * to have controls for a video view placed inside of the window decorations 6021 * that it hides and shows. This can be used with code like the second 6022 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6023 * 6024 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6025 * 6026 * @param insets Current content insets of the window. Prior to 6027 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6028 * the insets or else you and Android will be unhappy. 6029 * 6030 * @return {@code true} if this view applied the insets and it should not 6031 * continue propagating further down the hierarchy, {@code false} otherwise. 6032 * @see #getFitsSystemWindows() 6033 * @see #setFitsSystemWindows(boolean) 6034 * @see #setSystemUiVisibility(int) 6035 * 6036 * @deprecated As of API XX use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6037 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6038 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6039 * to implement handling their own insets. 6040 */ 6041 protected boolean fitSystemWindows(Rect insets) { 6042 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6043 // If we're not in the process of dispatching the newer apply insets call, 6044 // that means we're not in the compatibility path. Dispatch into the newer 6045 // apply insets path and take things from there. 6046 try { 6047 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6048 return !dispatchApplyWindowInsets(new WindowInsets(insets)).hasInsets(); 6049 } finally { 6050 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6051 } 6052 } else { 6053 // We're being called from the newer apply insets path. 6054 // Perform the standard fallback behavior. 6055 return fitSystemWindowsInt(insets); 6056 } 6057 } 6058 6059 private boolean fitSystemWindowsInt(Rect insets) { 6060 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6061 mUserPaddingStart = UNDEFINED_PADDING; 6062 mUserPaddingEnd = UNDEFINED_PADDING; 6063 Rect localInsets = sThreadLocal.get(); 6064 if (localInsets == null) { 6065 localInsets = new Rect(); 6066 sThreadLocal.set(localInsets); 6067 } 6068 boolean res = computeFitSystemWindows(insets, localInsets); 6069 mUserPaddingLeftInitial = localInsets.left; 6070 mUserPaddingRightInitial = localInsets.right; 6071 internalSetPadding(localInsets.left, localInsets.top, 6072 localInsets.right, localInsets.bottom); 6073 return res; 6074 } 6075 return false; 6076 } 6077 6078 /** 6079 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6080 * 6081 * <p>This method should be overridden by views that wish to apply a policy different from or 6082 * in addition to the default behavior. Clients that wish to force a view subtree 6083 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6084 * 6085 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6086 * it will be called during dispatch instead of this method. The listener may optionally 6087 * call this method from its own implementation if it wishes to apply the view's default 6088 * insets policy in addition to its own.</p> 6089 * 6090 * <p>Implementations of this method should either return the insets parameter unchanged 6091 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6092 * that this view applied itself. This allows new inset types added in future platform 6093 * versions to pass through existing implementations unchanged without being erroneously 6094 * consumed.</p> 6095 * 6096 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6097 * property is set then the view will consume the system window insets and apply them 6098 * as padding for the view.</p> 6099 * 6100 * @param insets Insets to apply 6101 * @return The supplied insets with any applied insets consumed 6102 */ 6103 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6104 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6105 // We weren't called from within a direct call to fitSystemWindows, 6106 // call into it as a fallback in case we're in a class that overrides it 6107 // and has logic to perform. 6108 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6109 return insets.cloneWithSystemWindowInsetsConsumed(); 6110 } 6111 } else { 6112 // We were called from within a direct call to fitSystemWindows. 6113 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6114 return insets.cloneWithSystemWindowInsetsConsumed(); 6115 } 6116 } 6117 return insets; 6118 } 6119 6120 /** 6121 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6122 * window insets to this view. The listener's 6123 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6124 * method will be called instead of the view's 6125 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6126 * 6127 * @param listener Listener to set 6128 * 6129 * @see #onApplyWindowInsets(WindowInsets) 6130 */ 6131 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6132 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6133 } 6134 6135 /** 6136 * Request to apply the given window insets to this view or another view in its subtree. 6137 * 6138 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6139 * obscured by window decorations or overlays. This can include the status and navigation bars, 6140 * action bars, input methods and more. New inset categories may be added in the future. 6141 * The method returns the insets provided minus any that were applied by this view or its 6142 * children.</p> 6143 * 6144 * <p>Clients wishing to provide custom behavior should override the 6145 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6146 * {@link OnApplyWindowInsetsListener} via the 6147 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6148 * method.</p> 6149 * 6150 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6151 * </p> 6152 * 6153 * @param insets Insets to apply 6154 * @return The provided insets minus the insets that were consumed 6155 */ 6156 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6157 try { 6158 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6159 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6160 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6161 } else { 6162 return onApplyWindowInsets(insets); 6163 } 6164 } finally { 6165 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6166 } 6167 } 6168 6169 /** 6170 * @hide Compute the insets that should be consumed by this view and the ones 6171 * that should propagate to those under it. 6172 */ 6173 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6174 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6175 || mAttachInfo == null 6176 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6177 && !mAttachInfo.mOverscanRequested)) { 6178 outLocalInsets.set(inoutInsets); 6179 inoutInsets.set(0, 0, 0, 0); 6180 return true; 6181 } else { 6182 // The application wants to take care of fitting system window for 6183 // the content... however we still need to take care of any overscan here. 6184 final Rect overscan = mAttachInfo.mOverscanInsets; 6185 outLocalInsets.set(overscan); 6186 inoutInsets.left -= overscan.left; 6187 inoutInsets.top -= overscan.top; 6188 inoutInsets.right -= overscan.right; 6189 inoutInsets.bottom -= overscan.bottom; 6190 return false; 6191 } 6192 } 6193 6194 /** 6195 * Sets whether or not this view should account for system screen decorations 6196 * such as the status bar and inset its content; that is, controlling whether 6197 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6198 * executed. See that method for more details. 6199 * 6200 * <p>Note that if you are providing your own implementation of 6201 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6202 * flag to true -- your implementation will be overriding the default 6203 * implementation that checks this flag. 6204 * 6205 * @param fitSystemWindows If true, then the default implementation of 6206 * {@link #fitSystemWindows(Rect)} will be executed. 6207 * 6208 * @attr ref android.R.styleable#View_fitsSystemWindows 6209 * @see #getFitsSystemWindows() 6210 * @see #fitSystemWindows(Rect) 6211 * @see #setSystemUiVisibility(int) 6212 */ 6213 public void setFitsSystemWindows(boolean fitSystemWindows) { 6214 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6215 } 6216 6217 /** 6218 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6219 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6220 * will be executed. 6221 * 6222 * @return {@code true} if the default implementation of 6223 * {@link #fitSystemWindows(Rect)} will be executed. 6224 * 6225 * @attr ref android.R.styleable#View_fitsSystemWindows 6226 * @see #setFitsSystemWindows(boolean) 6227 * @see #fitSystemWindows(Rect) 6228 * @see #setSystemUiVisibility(int) 6229 */ 6230 public boolean getFitsSystemWindows() { 6231 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6232 } 6233 6234 /** @hide */ 6235 public boolean fitsSystemWindows() { 6236 return getFitsSystemWindows(); 6237 } 6238 6239 /** 6240 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6241 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6242 */ 6243 public void requestFitSystemWindows() { 6244 if (mParent != null) { 6245 mParent.requestFitSystemWindows(); 6246 } 6247 } 6248 6249 /** 6250 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6251 */ 6252 public void requestApplyInsets() { 6253 requestFitSystemWindows(); 6254 } 6255 6256 /** 6257 * For use by PhoneWindow to make its own system window fitting optional. 6258 * @hide 6259 */ 6260 public void makeOptionalFitsSystemWindows() { 6261 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6262 } 6263 6264 /** 6265 * Returns the visibility status for this view. 6266 * 6267 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6268 * @attr ref android.R.styleable#View_visibility 6269 */ 6270 @ViewDebug.ExportedProperty(mapping = { 6271 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6272 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6273 @ViewDebug.IntToString(from = GONE, to = "GONE") 6274 }) 6275 @Visibility 6276 public int getVisibility() { 6277 return mViewFlags & VISIBILITY_MASK; 6278 } 6279 6280 /** 6281 * Set the enabled state of this view. 6282 * 6283 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6284 * @attr ref android.R.styleable#View_visibility 6285 */ 6286 @RemotableViewMethod 6287 public void setVisibility(@Visibility int visibility) { 6288 setFlags(visibility, VISIBILITY_MASK); 6289 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6290 } 6291 6292 /** 6293 * Returns the enabled status for this view. The interpretation of the 6294 * enabled state varies by subclass. 6295 * 6296 * @return True if this view is enabled, false otherwise. 6297 */ 6298 @ViewDebug.ExportedProperty 6299 public boolean isEnabled() { 6300 return (mViewFlags & ENABLED_MASK) == ENABLED; 6301 } 6302 6303 /** 6304 * Set the enabled state of this view. The interpretation of the enabled 6305 * state varies by subclass. 6306 * 6307 * @param enabled True if this view is enabled, false otherwise. 6308 */ 6309 @RemotableViewMethod 6310 public void setEnabled(boolean enabled) { 6311 if (enabled == isEnabled()) return; 6312 6313 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6314 6315 /* 6316 * The View most likely has to change its appearance, so refresh 6317 * the drawable state. 6318 */ 6319 refreshDrawableState(); 6320 6321 // Invalidate too, since the default behavior for views is to be 6322 // be drawn at 50% alpha rather than to change the drawable. 6323 invalidate(true); 6324 6325 if (!enabled) { 6326 cancelPendingInputEvents(); 6327 } 6328 } 6329 6330 /** 6331 * Set whether this view can receive the focus. 6332 * 6333 * Setting this to false will also ensure that this view is not focusable 6334 * in touch mode. 6335 * 6336 * @param focusable If true, this view can receive the focus. 6337 * 6338 * @see #setFocusableInTouchMode(boolean) 6339 * @attr ref android.R.styleable#View_focusable 6340 */ 6341 public void setFocusable(boolean focusable) { 6342 if (!focusable) { 6343 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6344 } 6345 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6346 } 6347 6348 /** 6349 * Set whether this view can receive focus while in touch mode. 6350 * 6351 * Setting this to true will also ensure that this view is focusable. 6352 * 6353 * @param focusableInTouchMode If true, this view can receive the focus while 6354 * in touch mode. 6355 * 6356 * @see #setFocusable(boolean) 6357 * @attr ref android.R.styleable#View_focusableInTouchMode 6358 */ 6359 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6360 // Focusable in touch mode should always be set before the focusable flag 6361 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6362 // which, in touch mode, will not successfully request focus on this view 6363 // because the focusable in touch mode flag is not set 6364 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6365 if (focusableInTouchMode) { 6366 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6367 } 6368 } 6369 6370 /** 6371 * Set whether this view should have sound effects enabled for events such as 6372 * clicking and touching. 6373 * 6374 * <p>You may wish to disable sound effects for a view if you already play sounds, 6375 * for instance, a dial key that plays dtmf tones. 6376 * 6377 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6378 * @see #isSoundEffectsEnabled() 6379 * @see #playSoundEffect(int) 6380 * @attr ref android.R.styleable#View_soundEffectsEnabled 6381 */ 6382 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6383 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6384 } 6385 6386 /** 6387 * @return whether this view should have sound effects enabled for events such as 6388 * clicking and touching. 6389 * 6390 * @see #setSoundEffectsEnabled(boolean) 6391 * @see #playSoundEffect(int) 6392 * @attr ref android.R.styleable#View_soundEffectsEnabled 6393 */ 6394 @ViewDebug.ExportedProperty 6395 public boolean isSoundEffectsEnabled() { 6396 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6397 } 6398 6399 /** 6400 * Set whether this view should have haptic feedback for events such as 6401 * long presses. 6402 * 6403 * <p>You may wish to disable haptic feedback if your view already controls 6404 * its own haptic feedback. 6405 * 6406 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6407 * @see #isHapticFeedbackEnabled() 6408 * @see #performHapticFeedback(int) 6409 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6410 */ 6411 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6412 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6413 } 6414 6415 /** 6416 * @return whether this view should have haptic feedback enabled for events 6417 * long presses. 6418 * 6419 * @see #setHapticFeedbackEnabled(boolean) 6420 * @see #performHapticFeedback(int) 6421 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6422 */ 6423 @ViewDebug.ExportedProperty 6424 public boolean isHapticFeedbackEnabled() { 6425 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6426 } 6427 6428 /** 6429 * Returns the layout direction for this view. 6430 * 6431 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6432 * {@link #LAYOUT_DIRECTION_RTL}, 6433 * {@link #LAYOUT_DIRECTION_INHERIT} or 6434 * {@link #LAYOUT_DIRECTION_LOCALE}. 6435 * 6436 * @attr ref android.R.styleable#View_layoutDirection 6437 * 6438 * @hide 6439 */ 6440 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6441 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6442 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6443 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6444 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6445 }) 6446 @LayoutDir 6447 public int getRawLayoutDirection() { 6448 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6449 } 6450 6451 /** 6452 * Set the layout direction for this view. This will propagate a reset of layout direction 6453 * resolution to the view's children and resolve layout direction for this view. 6454 * 6455 * @param layoutDirection the layout direction to set. Should be one of: 6456 * 6457 * {@link #LAYOUT_DIRECTION_LTR}, 6458 * {@link #LAYOUT_DIRECTION_RTL}, 6459 * {@link #LAYOUT_DIRECTION_INHERIT}, 6460 * {@link #LAYOUT_DIRECTION_LOCALE}. 6461 * 6462 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6463 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6464 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6465 * 6466 * @attr ref android.R.styleable#View_layoutDirection 6467 */ 6468 @RemotableViewMethod 6469 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6470 if (getRawLayoutDirection() != layoutDirection) { 6471 // Reset the current layout direction and the resolved one 6472 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6473 resetRtlProperties(); 6474 // Set the new layout direction (filtered) 6475 mPrivateFlags2 |= 6476 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6477 // We need to resolve all RTL properties as they all depend on layout direction 6478 resolveRtlPropertiesIfNeeded(); 6479 requestLayout(); 6480 invalidate(true); 6481 } 6482 } 6483 6484 /** 6485 * Returns the resolved layout direction for this view. 6486 * 6487 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6488 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6489 * 6490 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6491 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6492 * 6493 * @attr ref android.R.styleable#View_layoutDirection 6494 */ 6495 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6496 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6497 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6498 }) 6499 @ResolvedLayoutDir 6500 public int getLayoutDirection() { 6501 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6502 if (targetSdkVersion < JELLY_BEAN_MR1) { 6503 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6504 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6505 } 6506 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6507 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6508 } 6509 6510 /** 6511 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6512 * layout attribute and/or the inherited value from the parent 6513 * 6514 * @return true if the layout is right-to-left. 6515 * 6516 * @hide 6517 */ 6518 @ViewDebug.ExportedProperty(category = "layout") 6519 public boolean isLayoutRtl() { 6520 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6521 } 6522 6523 /** 6524 * Indicates whether the view is currently tracking transient state that the 6525 * app should not need to concern itself with saving and restoring, but that 6526 * the framework should take special note to preserve when possible. 6527 * 6528 * <p>A view with transient state cannot be trivially rebound from an external 6529 * data source, such as an adapter binding item views in a list. This may be 6530 * because the view is performing an animation, tracking user selection 6531 * of content, or similar.</p> 6532 * 6533 * @return true if the view has transient state 6534 */ 6535 @ViewDebug.ExportedProperty(category = "layout") 6536 public boolean hasTransientState() { 6537 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6538 } 6539 6540 /** 6541 * Set whether this view is currently tracking transient state that the 6542 * framework should attempt to preserve when possible. This flag is reference counted, 6543 * so every call to setHasTransientState(true) should be paired with a later call 6544 * to setHasTransientState(false). 6545 * 6546 * <p>A view with transient state cannot be trivially rebound from an external 6547 * data source, such as an adapter binding item views in a list. This may be 6548 * because the view is performing an animation, tracking user selection 6549 * of content, or similar.</p> 6550 * 6551 * @param hasTransientState true if this view has transient state 6552 */ 6553 public void setHasTransientState(boolean hasTransientState) { 6554 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6555 mTransientStateCount - 1; 6556 if (mTransientStateCount < 0) { 6557 mTransientStateCount = 0; 6558 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6559 "unmatched pair of setHasTransientState calls"); 6560 } else if ((hasTransientState && mTransientStateCount == 1) || 6561 (!hasTransientState && mTransientStateCount == 0)) { 6562 // update flag if we've just incremented up from 0 or decremented down to 0 6563 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6564 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6565 if (mParent != null) { 6566 try { 6567 mParent.childHasTransientStateChanged(this, hasTransientState); 6568 } catch (AbstractMethodError e) { 6569 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6570 " does not fully implement ViewParent", e); 6571 } 6572 } 6573 } 6574 } 6575 6576 /** 6577 * Returns true if this view is currently attached to a window. 6578 */ 6579 public boolean isAttachedToWindow() { 6580 return mAttachInfo != null; 6581 } 6582 6583 /** 6584 * Returns true if this view has been through at least one layout since it 6585 * was last attached to or detached from a window. 6586 */ 6587 public boolean isLaidOut() { 6588 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6589 } 6590 6591 /** 6592 * If this view doesn't do any drawing on its own, set this flag to 6593 * allow further optimizations. By default, this flag is not set on 6594 * View, but could be set on some View subclasses such as ViewGroup. 6595 * 6596 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6597 * you should clear this flag. 6598 * 6599 * @param willNotDraw whether or not this View draw on its own 6600 */ 6601 public void setWillNotDraw(boolean willNotDraw) { 6602 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6603 } 6604 6605 /** 6606 * Returns whether or not this View draws on its own. 6607 * 6608 * @return true if this view has nothing to draw, false otherwise 6609 */ 6610 @ViewDebug.ExportedProperty(category = "drawing") 6611 public boolean willNotDraw() { 6612 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6613 } 6614 6615 /** 6616 * When a View's drawing cache is enabled, drawing is redirected to an 6617 * offscreen bitmap. Some views, like an ImageView, must be able to 6618 * bypass this mechanism if they already draw a single bitmap, to avoid 6619 * unnecessary usage of the memory. 6620 * 6621 * @param willNotCacheDrawing true if this view does not cache its 6622 * drawing, false otherwise 6623 */ 6624 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6625 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 6626 } 6627 6628 /** 6629 * Returns whether or not this View can cache its drawing or not. 6630 * 6631 * @return true if this view does not cache its drawing, false otherwise 6632 */ 6633 @ViewDebug.ExportedProperty(category = "drawing") 6634 public boolean willNotCacheDrawing() { 6635 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 6636 } 6637 6638 /** 6639 * Indicates whether this view reacts to click events or not. 6640 * 6641 * @return true if the view is clickable, false otherwise 6642 * 6643 * @see #setClickable(boolean) 6644 * @attr ref android.R.styleable#View_clickable 6645 */ 6646 @ViewDebug.ExportedProperty 6647 public boolean isClickable() { 6648 return (mViewFlags & CLICKABLE) == CLICKABLE; 6649 } 6650 6651 /** 6652 * Enables or disables click events for this view. When a view 6653 * is clickable it will change its state to "pressed" on every click. 6654 * Subclasses should set the view clickable to visually react to 6655 * user's clicks. 6656 * 6657 * @param clickable true to make the view clickable, false otherwise 6658 * 6659 * @see #isClickable() 6660 * @attr ref android.R.styleable#View_clickable 6661 */ 6662 public void setClickable(boolean clickable) { 6663 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 6664 } 6665 6666 /** 6667 * Indicates whether this view reacts to long click events or not. 6668 * 6669 * @return true if the view is long clickable, false otherwise 6670 * 6671 * @see #setLongClickable(boolean) 6672 * @attr ref android.R.styleable#View_longClickable 6673 */ 6674 public boolean isLongClickable() { 6675 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 6676 } 6677 6678 /** 6679 * Enables or disables long click events for this view. When a view is long 6680 * clickable it reacts to the user holding down the button for a longer 6681 * duration than a tap. This event can either launch the listener or a 6682 * context menu. 6683 * 6684 * @param longClickable true to make the view long clickable, false otherwise 6685 * @see #isLongClickable() 6686 * @attr ref android.R.styleable#View_longClickable 6687 */ 6688 public void setLongClickable(boolean longClickable) { 6689 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 6690 } 6691 6692 /** 6693 * Sets the pressed state for this view. 6694 * 6695 * @see #isClickable() 6696 * @see #setClickable(boolean) 6697 * 6698 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 6699 * the View's internal state from a previously set "pressed" state. 6700 */ 6701 public void setPressed(boolean pressed) { 6702 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 6703 6704 if (pressed) { 6705 mPrivateFlags |= PFLAG_PRESSED; 6706 } else { 6707 mPrivateFlags &= ~PFLAG_PRESSED; 6708 } 6709 6710 if (needsRefresh) { 6711 refreshDrawableState(); 6712 } 6713 dispatchSetPressed(pressed); 6714 } 6715 6716 /** 6717 * Dispatch setPressed to all of this View's children. 6718 * 6719 * @see #setPressed(boolean) 6720 * 6721 * @param pressed The new pressed state 6722 */ 6723 protected void dispatchSetPressed(boolean pressed) { 6724 } 6725 6726 /** 6727 * Indicates whether the view is currently in pressed state. Unless 6728 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 6729 * the pressed state. 6730 * 6731 * @see #setPressed(boolean) 6732 * @see #isClickable() 6733 * @see #setClickable(boolean) 6734 * 6735 * @return true if the view is currently pressed, false otherwise 6736 */ 6737 public boolean isPressed() { 6738 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 6739 } 6740 6741 /** 6742 * Indicates whether this view will save its state (that is, 6743 * whether its {@link #onSaveInstanceState} method will be called). 6744 * 6745 * @return Returns true if the view state saving is enabled, else false. 6746 * 6747 * @see #setSaveEnabled(boolean) 6748 * @attr ref android.R.styleable#View_saveEnabled 6749 */ 6750 public boolean isSaveEnabled() { 6751 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 6752 } 6753 6754 /** 6755 * Controls whether the saving of this view's state is 6756 * enabled (that is, whether its {@link #onSaveInstanceState} method 6757 * will be called). Note that even if freezing is enabled, the 6758 * view still must have an id assigned to it (via {@link #setId(int)}) 6759 * for its state to be saved. This flag can only disable the 6760 * saving of this view; any child views may still have their state saved. 6761 * 6762 * @param enabled Set to false to <em>disable</em> state saving, or true 6763 * (the default) to allow it. 6764 * 6765 * @see #isSaveEnabled() 6766 * @see #setId(int) 6767 * @see #onSaveInstanceState() 6768 * @attr ref android.R.styleable#View_saveEnabled 6769 */ 6770 public void setSaveEnabled(boolean enabled) { 6771 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 6772 } 6773 6774 /** 6775 * Gets whether the framework should discard touches when the view's 6776 * window is obscured by another visible window. 6777 * Refer to the {@link View} security documentation for more details. 6778 * 6779 * @return True if touch filtering is enabled. 6780 * 6781 * @see #setFilterTouchesWhenObscured(boolean) 6782 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6783 */ 6784 @ViewDebug.ExportedProperty 6785 public boolean getFilterTouchesWhenObscured() { 6786 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 6787 } 6788 6789 /** 6790 * Sets whether the framework should discard touches when the view's 6791 * window is obscured by another visible window. 6792 * Refer to the {@link View} security documentation for more details. 6793 * 6794 * @param enabled True if touch filtering should be enabled. 6795 * 6796 * @see #getFilterTouchesWhenObscured 6797 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 6798 */ 6799 public void setFilterTouchesWhenObscured(boolean enabled) { 6800 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 6801 FILTER_TOUCHES_WHEN_OBSCURED); 6802 } 6803 6804 /** 6805 * Indicates whether the entire hierarchy under this view will save its 6806 * state when a state saving traversal occurs from its parent. The default 6807 * is true; if false, these views will not be saved unless 6808 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6809 * 6810 * @return Returns true if the view state saving from parent is enabled, else false. 6811 * 6812 * @see #setSaveFromParentEnabled(boolean) 6813 */ 6814 public boolean isSaveFromParentEnabled() { 6815 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 6816 } 6817 6818 /** 6819 * Controls whether the entire hierarchy under this view will save its 6820 * state when a state saving traversal occurs from its parent. The default 6821 * is true; if false, these views will not be saved unless 6822 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 6823 * 6824 * @param enabled Set to false to <em>disable</em> state saving, or true 6825 * (the default) to allow it. 6826 * 6827 * @see #isSaveFromParentEnabled() 6828 * @see #setId(int) 6829 * @see #onSaveInstanceState() 6830 */ 6831 public void setSaveFromParentEnabled(boolean enabled) { 6832 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 6833 } 6834 6835 6836 /** 6837 * Returns whether this View is able to take focus. 6838 * 6839 * @return True if this view can take focus, or false otherwise. 6840 * @attr ref android.R.styleable#View_focusable 6841 */ 6842 @ViewDebug.ExportedProperty(category = "focus") 6843 public final boolean isFocusable() { 6844 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 6845 } 6846 6847 /** 6848 * When a view is focusable, it may not want to take focus when in touch mode. 6849 * For example, a button would like focus when the user is navigating via a D-pad 6850 * so that the user can click on it, but once the user starts touching the screen, 6851 * the button shouldn't take focus 6852 * @return Whether the view is focusable in touch mode. 6853 * @attr ref android.R.styleable#View_focusableInTouchMode 6854 */ 6855 @ViewDebug.ExportedProperty 6856 public final boolean isFocusableInTouchMode() { 6857 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 6858 } 6859 6860 /** 6861 * Find the nearest view in the specified direction that can take focus. 6862 * This does not actually give focus to that view. 6863 * 6864 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 6865 * 6866 * @return The nearest focusable in the specified direction, or null if none 6867 * can be found. 6868 */ 6869 public View focusSearch(@FocusRealDirection int direction) { 6870 if (mParent != null) { 6871 return mParent.focusSearch(this, direction); 6872 } else { 6873 return null; 6874 } 6875 } 6876 6877 /** 6878 * This method is the last chance for the focused view and its ancestors to 6879 * respond to an arrow key. This is called when the focused view did not 6880 * consume the key internally, nor could the view system find a new view in 6881 * the requested direction to give focus to. 6882 * 6883 * @param focused The currently focused view. 6884 * @param direction The direction focus wants to move. One of FOCUS_UP, 6885 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 6886 * @return True if the this view consumed this unhandled move. 6887 */ 6888 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 6889 return false; 6890 } 6891 6892 /** 6893 * If a user manually specified the next view id for a particular direction, 6894 * use the root to look up the view. 6895 * @param root The root view of the hierarchy containing this view. 6896 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 6897 * or FOCUS_BACKWARD. 6898 * @return The user specified next view, or null if there is none. 6899 */ 6900 View findUserSetNextFocus(View root, @FocusDirection int direction) { 6901 switch (direction) { 6902 case FOCUS_LEFT: 6903 if (mNextFocusLeftId == View.NO_ID) return null; 6904 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 6905 case FOCUS_RIGHT: 6906 if (mNextFocusRightId == View.NO_ID) return null; 6907 return findViewInsideOutShouldExist(root, mNextFocusRightId); 6908 case FOCUS_UP: 6909 if (mNextFocusUpId == View.NO_ID) return null; 6910 return findViewInsideOutShouldExist(root, mNextFocusUpId); 6911 case FOCUS_DOWN: 6912 if (mNextFocusDownId == View.NO_ID) return null; 6913 return findViewInsideOutShouldExist(root, mNextFocusDownId); 6914 case FOCUS_FORWARD: 6915 if (mNextFocusForwardId == View.NO_ID) return null; 6916 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 6917 case FOCUS_BACKWARD: { 6918 if (mID == View.NO_ID) return null; 6919 final int id = mID; 6920 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 6921 @Override 6922 public boolean apply(View t) { 6923 return t.mNextFocusForwardId == id; 6924 } 6925 }); 6926 } 6927 } 6928 return null; 6929 } 6930 6931 private View findViewInsideOutShouldExist(View root, int id) { 6932 if (mMatchIdPredicate == null) { 6933 mMatchIdPredicate = new MatchIdPredicate(); 6934 } 6935 mMatchIdPredicate.mId = id; 6936 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 6937 if (result == null) { 6938 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 6939 } 6940 return result; 6941 } 6942 6943 /** 6944 * Find and return all focusable views that are descendants of this view, 6945 * possibly including this view if it is focusable itself. 6946 * 6947 * @param direction The direction of the focus 6948 * @return A list of focusable views 6949 */ 6950 public ArrayList<View> getFocusables(@FocusDirection int direction) { 6951 ArrayList<View> result = new ArrayList<View>(24); 6952 addFocusables(result, direction); 6953 return result; 6954 } 6955 6956 /** 6957 * Add any focusable views that are descendants of this view (possibly 6958 * including this view if it is focusable itself) to views. If we are in touch mode, 6959 * only add views that are also focusable in touch mode. 6960 * 6961 * @param views Focusable views found so far 6962 * @param direction The direction of the focus 6963 */ 6964 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 6965 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 6966 } 6967 6968 /** 6969 * Adds any focusable views that are descendants of this view (possibly 6970 * including this view if it is focusable itself) to views. This method 6971 * adds all focusable views regardless if we are in touch mode or 6972 * only views focusable in touch mode if we are in touch mode or 6973 * only views that can take accessibility focus if accessibility is enabeld 6974 * depending on the focusable mode paramater. 6975 * 6976 * @param views Focusable views found so far or null if all we are interested is 6977 * the number of focusables. 6978 * @param direction The direction of the focus. 6979 * @param focusableMode The type of focusables to be added. 6980 * 6981 * @see #FOCUSABLES_ALL 6982 * @see #FOCUSABLES_TOUCH_MODE 6983 */ 6984 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 6985 @FocusableMode int focusableMode) { 6986 if (views == null) { 6987 return; 6988 } 6989 if (!isFocusable()) { 6990 return; 6991 } 6992 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 6993 && isInTouchMode() && !isFocusableInTouchMode()) { 6994 return; 6995 } 6996 views.add(this); 6997 } 6998 6999 /** 7000 * Finds the Views that contain given text. The containment is case insensitive. 7001 * The search is performed by either the text that the View renders or the content 7002 * description that describes the view for accessibility purposes and the view does 7003 * not render or both. Clients can specify how the search is to be performed via 7004 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7005 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7006 * 7007 * @param outViews The output list of matching Views. 7008 * @param searched The text to match against. 7009 * 7010 * @see #FIND_VIEWS_WITH_TEXT 7011 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7012 * @see #setContentDescription(CharSequence) 7013 */ 7014 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7015 @FindViewFlags int flags) { 7016 if (getAccessibilityNodeProvider() != null) { 7017 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7018 outViews.add(this); 7019 } 7020 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7021 && (searched != null && searched.length() > 0) 7022 && (mContentDescription != null && mContentDescription.length() > 0)) { 7023 String searchedLowerCase = searched.toString().toLowerCase(); 7024 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7025 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7026 outViews.add(this); 7027 } 7028 } 7029 } 7030 7031 /** 7032 * Find and return all touchable views that are descendants of this view, 7033 * possibly including this view if it is touchable itself. 7034 * 7035 * @return A list of touchable views 7036 */ 7037 public ArrayList<View> getTouchables() { 7038 ArrayList<View> result = new ArrayList<View>(); 7039 addTouchables(result); 7040 return result; 7041 } 7042 7043 /** 7044 * Add any touchable views that are descendants of this view (possibly 7045 * including this view if it is touchable itself) to views. 7046 * 7047 * @param views Touchable views found so far 7048 */ 7049 public void addTouchables(ArrayList<View> views) { 7050 final int viewFlags = mViewFlags; 7051 7052 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7053 && (viewFlags & ENABLED_MASK) == ENABLED) { 7054 views.add(this); 7055 } 7056 } 7057 7058 /** 7059 * Returns whether this View is accessibility focused. 7060 * 7061 * @return True if this View is accessibility focused. 7062 */ 7063 public boolean isAccessibilityFocused() { 7064 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7065 } 7066 7067 /** 7068 * Call this to try to give accessibility focus to this view. 7069 * 7070 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7071 * returns false or the view is no visible or the view already has accessibility 7072 * focus. 7073 * 7074 * See also {@link #focusSearch(int)}, which is what you call to say that you 7075 * have focus, and you want your parent to look for the next one. 7076 * 7077 * @return Whether this view actually took accessibility focus. 7078 * 7079 * @hide 7080 */ 7081 public boolean requestAccessibilityFocus() { 7082 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7083 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7084 return false; 7085 } 7086 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7087 return false; 7088 } 7089 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7090 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7091 ViewRootImpl viewRootImpl = getViewRootImpl(); 7092 if (viewRootImpl != null) { 7093 viewRootImpl.setAccessibilityFocus(this, null); 7094 } 7095 invalidate(); 7096 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7097 return true; 7098 } 7099 return false; 7100 } 7101 7102 /** 7103 * Call this to try to clear accessibility focus of this view. 7104 * 7105 * See also {@link #focusSearch(int)}, which is what you call to say that you 7106 * have focus, and you want your parent to look for the next one. 7107 * 7108 * @hide 7109 */ 7110 public void clearAccessibilityFocus() { 7111 clearAccessibilityFocusNoCallbacks(); 7112 // Clear the global reference of accessibility focus if this 7113 // view or any of its descendants had accessibility focus. 7114 ViewRootImpl viewRootImpl = getViewRootImpl(); 7115 if (viewRootImpl != null) { 7116 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7117 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7118 viewRootImpl.setAccessibilityFocus(null, null); 7119 } 7120 } 7121 } 7122 7123 private void sendAccessibilityHoverEvent(int eventType) { 7124 // Since we are not delivering to a client accessibility events from not 7125 // important views (unless the clinet request that) we need to fire the 7126 // event from the deepest view exposed to the client. As a consequence if 7127 // the user crosses a not exposed view the client will see enter and exit 7128 // of the exposed predecessor followed by and enter and exit of that same 7129 // predecessor when entering and exiting the not exposed descendant. This 7130 // is fine since the client has a clear idea which view is hovered at the 7131 // price of a couple more events being sent. This is a simple and 7132 // working solution. 7133 View source = this; 7134 while (true) { 7135 if (source.includeForAccessibility()) { 7136 source.sendAccessibilityEvent(eventType); 7137 return; 7138 } 7139 ViewParent parent = source.getParent(); 7140 if (parent instanceof View) { 7141 source = (View) parent; 7142 } else { 7143 return; 7144 } 7145 } 7146 } 7147 7148 /** 7149 * Clears accessibility focus without calling any callback methods 7150 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7151 * is used for clearing accessibility focus when giving this focus to 7152 * another view. 7153 */ 7154 void clearAccessibilityFocusNoCallbacks() { 7155 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7156 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7157 invalidate(); 7158 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7159 } 7160 } 7161 7162 /** 7163 * Call this to try to give focus to a specific view or to one of its 7164 * descendants. 7165 * 7166 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7167 * false), or if it is focusable and it is not focusable in touch mode 7168 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7169 * 7170 * See also {@link #focusSearch(int)}, which is what you call to say that you 7171 * have focus, and you want your parent to look for the next one. 7172 * 7173 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7174 * {@link #FOCUS_DOWN} and <code>null</code>. 7175 * 7176 * @return Whether this view or one of its descendants actually took focus. 7177 */ 7178 public final boolean requestFocus() { 7179 return requestFocus(View.FOCUS_DOWN); 7180 } 7181 7182 /** 7183 * Call this to try to give focus to a specific view or to one of its 7184 * descendants and give it a hint about what direction focus is heading. 7185 * 7186 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7187 * false), or if it is focusable and it is not focusable in touch mode 7188 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7189 * 7190 * See also {@link #focusSearch(int)}, which is what you call to say that you 7191 * have focus, and you want your parent to look for the next one. 7192 * 7193 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7194 * <code>null</code> set for the previously focused rectangle. 7195 * 7196 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7197 * @return Whether this view or one of its descendants actually took focus. 7198 */ 7199 public final boolean requestFocus(int direction) { 7200 return requestFocus(direction, null); 7201 } 7202 7203 /** 7204 * Call this to try to give focus to a specific view or to one of its descendants 7205 * and give it hints about the direction and a specific rectangle that the focus 7206 * is coming from. The rectangle can help give larger views a finer grained hint 7207 * about where focus is coming from, and therefore, where to show selection, or 7208 * forward focus change internally. 7209 * 7210 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7211 * false), or if it is focusable and it is not focusable in touch mode 7212 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7213 * 7214 * A View will not take focus if it is not visible. 7215 * 7216 * A View will not take focus if one of its parents has 7217 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7218 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7219 * 7220 * See also {@link #focusSearch(int)}, which is what you call to say that you 7221 * have focus, and you want your parent to look for the next one. 7222 * 7223 * You may wish to override this method if your custom {@link View} has an internal 7224 * {@link View} that it wishes to forward the request to. 7225 * 7226 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7227 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7228 * to give a finer grained hint about where focus is coming from. May be null 7229 * if there is no hint. 7230 * @return Whether this view or one of its descendants actually took focus. 7231 */ 7232 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7233 return requestFocusNoSearch(direction, previouslyFocusedRect); 7234 } 7235 7236 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7237 // need to be focusable 7238 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7239 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7240 return false; 7241 } 7242 7243 // need to be focusable in touch mode if in touch mode 7244 if (isInTouchMode() && 7245 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7246 return false; 7247 } 7248 7249 // need to not have any parents blocking us 7250 if (hasAncestorThatBlocksDescendantFocus()) { 7251 return false; 7252 } 7253 7254 handleFocusGainInternal(direction, previouslyFocusedRect); 7255 return true; 7256 } 7257 7258 /** 7259 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7260 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7261 * touch mode to request focus when they are touched. 7262 * 7263 * @return Whether this view or one of its descendants actually took focus. 7264 * 7265 * @see #isInTouchMode() 7266 * 7267 */ 7268 public final boolean requestFocusFromTouch() { 7269 // Leave touch mode if we need to 7270 if (isInTouchMode()) { 7271 ViewRootImpl viewRoot = getViewRootImpl(); 7272 if (viewRoot != null) { 7273 viewRoot.ensureTouchMode(false); 7274 } 7275 } 7276 return requestFocus(View.FOCUS_DOWN); 7277 } 7278 7279 /** 7280 * @return Whether any ancestor of this view blocks descendant focus. 7281 */ 7282 private boolean hasAncestorThatBlocksDescendantFocus() { 7283 ViewParent ancestor = mParent; 7284 while (ancestor instanceof ViewGroup) { 7285 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7286 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { 7287 return true; 7288 } else { 7289 ancestor = vgAncestor.getParent(); 7290 } 7291 } 7292 return false; 7293 } 7294 7295 /** 7296 * Gets the mode for determining whether this View is important for accessibility 7297 * which is if it fires accessibility events and if it is reported to 7298 * accessibility services that query the screen. 7299 * 7300 * @return The mode for determining whether a View is important for accessibility. 7301 * 7302 * @attr ref android.R.styleable#View_importantForAccessibility 7303 * 7304 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7305 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7306 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7307 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7308 */ 7309 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7310 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7311 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7312 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7313 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7314 to = "noHideDescendants") 7315 }) 7316 public int getImportantForAccessibility() { 7317 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7318 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7319 } 7320 7321 /** 7322 * Sets the live region mode for this view. This indicates to accessibility 7323 * services whether they should automatically notify the user about changes 7324 * to the view's content description or text, or to the content descriptions 7325 * or text of the view's children (where applicable). 7326 * <p> 7327 * For example, in a login screen with a TextView that displays an "incorrect 7328 * password" notification, that view should be marked as a live region with 7329 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7330 * <p> 7331 * To disable change notifications for this view, use 7332 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7333 * mode for most views. 7334 * <p> 7335 * To indicate that the user should be notified of changes, use 7336 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7337 * <p> 7338 * If the view's changes should interrupt ongoing speech and notify the user 7339 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7340 * 7341 * @param mode The live region mode for this view, one of: 7342 * <ul> 7343 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7344 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7345 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7346 * </ul> 7347 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7348 */ 7349 public void setAccessibilityLiveRegion(int mode) { 7350 if (mode != getAccessibilityLiveRegion()) { 7351 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7352 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7353 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7354 notifyViewAccessibilityStateChangedIfNeeded( 7355 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7356 } 7357 } 7358 7359 /** 7360 * Gets the live region mode for this View. 7361 * 7362 * @return The live region mode for the view. 7363 * 7364 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7365 * 7366 * @see #setAccessibilityLiveRegion(int) 7367 */ 7368 public int getAccessibilityLiveRegion() { 7369 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7370 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7371 } 7372 7373 /** 7374 * Sets how to determine whether this view is important for accessibility 7375 * which is if it fires accessibility events and if it is reported to 7376 * accessibility services that query the screen. 7377 * 7378 * @param mode How to determine whether this view is important for accessibility. 7379 * 7380 * @attr ref android.R.styleable#View_importantForAccessibility 7381 * 7382 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7383 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7384 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7385 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7386 */ 7387 public void setImportantForAccessibility(int mode) { 7388 final int oldMode = getImportantForAccessibility(); 7389 if (mode != oldMode) { 7390 // If we're moving between AUTO and another state, we might not need 7391 // to send a subtree changed notification. We'll store the computed 7392 // importance, since we'll need to check it later to make sure. 7393 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7394 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7395 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7396 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7397 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7398 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7399 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7400 notifySubtreeAccessibilityStateChangedIfNeeded(); 7401 } else { 7402 notifyViewAccessibilityStateChangedIfNeeded( 7403 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7404 } 7405 } 7406 } 7407 7408 /** 7409 * Computes whether this view should be exposed for accessibility. In 7410 * general, views that are interactive or provide information are exposed 7411 * while views that serve only as containers are hidden. 7412 * <p> 7413 * If an ancestor of this view has importance 7414 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7415 * returns <code>false</code>. 7416 * <p> 7417 * Otherwise, the value is computed according to the view's 7418 * {@link #getImportantForAccessibility()} value: 7419 * <ol> 7420 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7421 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7422 * </code> 7423 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7424 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7425 * view satisfies any of the following: 7426 * <ul> 7427 * <li>Is actionable, e.g. {@link #isClickable()}, 7428 * {@link #isLongClickable()}, or {@link #isFocusable()} 7429 * <li>Has an {@link AccessibilityDelegate} 7430 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7431 * {@link OnKeyListener}, etc. 7432 * <li>Is an accessibility live region, e.g. 7433 * {@link #getAccessibilityLiveRegion()} is not 7434 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7435 * </ul> 7436 * </ol> 7437 * 7438 * @return Whether the view is exposed for accessibility. 7439 * @see #setImportantForAccessibility(int) 7440 * @see #getImportantForAccessibility() 7441 */ 7442 public boolean isImportantForAccessibility() { 7443 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7444 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7445 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7446 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7447 return false; 7448 } 7449 7450 // Check parent mode to ensure we're not hidden. 7451 ViewParent parent = mParent; 7452 while (parent instanceof View) { 7453 if (((View) parent).getImportantForAccessibility() 7454 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7455 return false; 7456 } 7457 parent = parent.getParent(); 7458 } 7459 7460 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7461 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7462 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7463 } 7464 7465 /** 7466 * Gets the parent for accessibility purposes. Note that the parent for 7467 * accessibility is not necessary the immediate parent. It is the first 7468 * predecessor that is important for accessibility. 7469 * 7470 * @return The parent for accessibility purposes. 7471 */ 7472 public ViewParent getParentForAccessibility() { 7473 if (mParent instanceof View) { 7474 View parentView = (View) mParent; 7475 if (parentView.includeForAccessibility()) { 7476 return mParent; 7477 } else { 7478 return mParent.getParentForAccessibility(); 7479 } 7480 } 7481 return null; 7482 } 7483 7484 /** 7485 * Adds the children of a given View for accessibility. Since some Views are 7486 * not important for accessibility the children for accessibility are not 7487 * necessarily direct children of the view, rather they are the first level of 7488 * descendants important for accessibility. 7489 * 7490 * @param children The list of children for accessibility. 7491 */ 7492 public void addChildrenForAccessibility(ArrayList<View> children) { 7493 7494 } 7495 7496 /** 7497 * Whether to regard this view for accessibility. A view is regarded for 7498 * accessibility if it is important for accessibility or the querying 7499 * accessibility service has explicitly requested that view not 7500 * important for accessibility are regarded. 7501 * 7502 * @return Whether to regard the view for accessibility. 7503 * 7504 * @hide 7505 */ 7506 public boolean includeForAccessibility() { 7507 if (mAttachInfo != null) { 7508 return (mAttachInfo.mAccessibilityFetchFlags 7509 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7510 || isImportantForAccessibility(); 7511 } 7512 return false; 7513 } 7514 7515 /** 7516 * Returns whether the View is considered actionable from 7517 * accessibility perspective. Such view are important for 7518 * accessibility. 7519 * 7520 * @return True if the view is actionable for accessibility. 7521 * 7522 * @hide 7523 */ 7524 public boolean isActionableForAccessibility() { 7525 return (isClickable() || isLongClickable() || isFocusable()); 7526 } 7527 7528 /** 7529 * Returns whether the View has registered callbacks which makes it 7530 * important for accessibility. 7531 * 7532 * @return True if the view is actionable for accessibility. 7533 */ 7534 private boolean hasListenersForAccessibility() { 7535 ListenerInfo info = getListenerInfo(); 7536 return mTouchDelegate != null || info.mOnKeyListener != null 7537 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7538 || info.mOnHoverListener != null || info.mOnDragListener != null; 7539 } 7540 7541 /** 7542 * Notifies that the accessibility state of this view changed. The change 7543 * is local to this view and does not represent structural changes such 7544 * as children and parent. For example, the view became focusable. The 7545 * notification is at at most once every 7546 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7547 * to avoid unnecessary load to the system. Also once a view has a pending 7548 * notification this method is a NOP until the notification has been sent. 7549 * 7550 * @hide 7551 */ 7552 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7553 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7554 return; 7555 } 7556 if (mSendViewStateChangedAccessibilityEvent == null) { 7557 mSendViewStateChangedAccessibilityEvent = 7558 new SendViewStateChangedAccessibilityEvent(); 7559 } 7560 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7561 } 7562 7563 /** 7564 * Notifies that the accessibility state of this view changed. The change 7565 * is *not* local to this view and does represent structural changes such 7566 * as children and parent. For example, the view size changed. The 7567 * notification is at at most once every 7568 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7569 * to avoid unnecessary load to the system. Also once a view has a pending 7570 * notifucation this method is a NOP until the notification has been sent. 7571 * 7572 * @hide 7573 */ 7574 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7575 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7576 return; 7577 } 7578 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7579 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7580 if (mParent != null) { 7581 try { 7582 mParent.notifySubtreeAccessibilityStateChanged( 7583 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7584 } catch (AbstractMethodError e) { 7585 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7586 " does not fully implement ViewParent", e); 7587 } 7588 } 7589 } 7590 } 7591 7592 /** 7593 * Reset the flag indicating the accessibility state of the subtree rooted 7594 * at this view changed. 7595 */ 7596 void resetSubtreeAccessibilityStateChanged() { 7597 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7598 } 7599 7600 /** 7601 * Performs the specified accessibility action on the view. For 7602 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7603 * <p> 7604 * If an {@link AccessibilityDelegate} has been specified via calling 7605 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7606 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 7607 * is responsible for handling this call. 7608 * </p> 7609 * 7610 * @param action The action to perform. 7611 * @param arguments Optional action arguments. 7612 * @return Whether the action was performed. 7613 */ 7614 public boolean performAccessibilityAction(int action, Bundle arguments) { 7615 if (mAccessibilityDelegate != null) { 7616 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 7617 } else { 7618 return performAccessibilityActionInternal(action, arguments); 7619 } 7620 } 7621 7622 /** 7623 * @see #performAccessibilityAction(int, Bundle) 7624 * 7625 * Note: Called from the default {@link AccessibilityDelegate}. 7626 */ 7627 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 7628 switch (action) { 7629 case AccessibilityNodeInfo.ACTION_CLICK: { 7630 if (isClickable()) { 7631 performClick(); 7632 return true; 7633 } 7634 } break; 7635 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 7636 if (isLongClickable()) { 7637 performLongClick(); 7638 return true; 7639 } 7640 } break; 7641 case AccessibilityNodeInfo.ACTION_FOCUS: { 7642 if (!hasFocus()) { 7643 // Get out of touch mode since accessibility 7644 // wants to move focus around. 7645 getViewRootImpl().ensureTouchMode(false); 7646 return requestFocus(); 7647 } 7648 } break; 7649 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 7650 if (hasFocus()) { 7651 clearFocus(); 7652 return !isFocused(); 7653 } 7654 } break; 7655 case AccessibilityNodeInfo.ACTION_SELECT: { 7656 if (!isSelected()) { 7657 setSelected(true); 7658 return isSelected(); 7659 } 7660 } break; 7661 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 7662 if (isSelected()) { 7663 setSelected(false); 7664 return !isSelected(); 7665 } 7666 } break; 7667 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 7668 if (!isAccessibilityFocused()) { 7669 return requestAccessibilityFocus(); 7670 } 7671 } break; 7672 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 7673 if (isAccessibilityFocused()) { 7674 clearAccessibilityFocus(); 7675 return true; 7676 } 7677 } break; 7678 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 7679 if (arguments != null) { 7680 final int granularity = arguments.getInt( 7681 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7682 final boolean extendSelection = arguments.getBoolean( 7683 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7684 return traverseAtGranularity(granularity, true, extendSelection); 7685 } 7686 } break; 7687 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 7688 if (arguments != null) { 7689 final int granularity = arguments.getInt( 7690 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 7691 final boolean extendSelection = arguments.getBoolean( 7692 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 7693 return traverseAtGranularity(granularity, false, extendSelection); 7694 } 7695 } break; 7696 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 7697 CharSequence text = getIterableTextForAccessibility(); 7698 if (text == null) { 7699 return false; 7700 } 7701 final int start = (arguments != null) ? arguments.getInt( 7702 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 7703 final int end = (arguments != null) ? arguments.getInt( 7704 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 7705 // Only cursor position can be specified (selection length == 0) 7706 if ((getAccessibilitySelectionStart() != start 7707 || getAccessibilitySelectionEnd() != end) 7708 && (start == end)) { 7709 setAccessibilitySelection(start, end); 7710 notifyViewAccessibilityStateChangedIfNeeded( 7711 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7712 return true; 7713 } 7714 } break; 7715 } 7716 return false; 7717 } 7718 7719 private boolean traverseAtGranularity(int granularity, boolean forward, 7720 boolean extendSelection) { 7721 CharSequence text = getIterableTextForAccessibility(); 7722 if (text == null || text.length() == 0) { 7723 return false; 7724 } 7725 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 7726 if (iterator == null) { 7727 return false; 7728 } 7729 int current = getAccessibilitySelectionEnd(); 7730 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7731 current = forward ? 0 : text.length(); 7732 } 7733 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 7734 if (range == null) { 7735 return false; 7736 } 7737 final int segmentStart = range[0]; 7738 final int segmentEnd = range[1]; 7739 int selectionStart; 7740 int selectionEnd; 7741 if (extendSelection && isAccessibilitySelectionExtendable()) { 7742 selectionStart = getAccessibilitySelectionStart(); 7743 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 7744 selectionStart = forward ? segmentStart : segmentEnd; 7745 } 7746 selectionEnd = forward ? segmentEnd : segmentStart; 7747 } else { 7748 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 7749 } 7750 setAccessibilitySelection(selectionStart, selectionEnd); 7751 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 7752 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 7753 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 7754 return true; 7755 } 7756 7757 /** 7758 * Gets the text reported for accessibility purposes. 7759 * 7760 * @return The accessibility text. 7761 * 7762 * @hide 7763 */ 7764 public CharSequence getIterableTextForAccessibility() { 7765 return getContentDescription(); 7766 } 7767 7768 /** 7769 * Gets whether accessibility selection can be extended. 7770 * 7771 * @return If selection is extensible. 7772 * 7773 * @hide 7774 */ 7775 public boolean isAccessibilitySelectionExtendable() { 7776 return false; 7777 } 7778 7779 /** 7780 * @hide 7781 */ 7782 public int getAccessibilitySelectionStart() { 7783 return mAccessibilityCursorPosition; 7784 } 7785 7786 /** 7787 * @hide 7788 */ 7789 public int getAccessibilitySelectionEnd() { 7790 return getAccessibilitySelectionStart(); 7791 } 7792 7793 /** 7794 * @hide 7795 */ 7796 public void setAccessibilitySelection(int start, int end) { 7797 if (start == end && end == mAccessibilityCursorPosition) { 7798 return; 7799 } 7800 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 7801 mAccessibilityCursorPosition = start; 7802 } else { 7803 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 7804 } 7805 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7806 } 7807 7808 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 7809 int fromIndex, int toIndex) { 7810 if (mParent == null) { 7811 return; 7812 } 7813 AccessibilityEvent event = AccessibilityEvent.obtain( 7814 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 7815 onInitializeAccessibilityEvent(event); 7816 onPopulateAccessibilityEvent(event); 7817 event.setFromIndex(fromIndex); 7818 event.setToIndex(toIndex); 7819 event.setAction(action); 7820 event.setMovementGranularity(granularity); 7821 mParent.requestSendAccessibilityEvent(this, event); 7822 } 7823 7824 /** 7825 * @hide 7826 */ 7827 public TextSegmentIterator getIteratorForGranularity(int granularity) { 7828 switch (granularity) { 7829 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 7830 CharSequence text = getIterableTextForAccessibility(); 7831 if (text != null && text.length() > 0) { 7832 CharacterTextSegmentIterator iterator = 7833 CharacterTextSegmentIterator.getInstance( 7834 mContext.getResources().getConfiguration().locale); 7835 iterator.initialize(text.toString()); 7836 return iterator; 7837 } 7838 } break; 7839 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 7840 CharSequence text = getIterableTextForAccessibility(); 7841 if (text != null && text.length() > 0) { 7842 WordTextSegmentIterator iterator = 7843 WordTextSegmentIterator.getInstance( 7844 mContext.getResources().getConfiguration().locale); 7845 iterator.initialize(text.toString()); 7846 return iterator; 7847 } 7848 } break; 7849 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 7850 CharSequence text = getIterableTextForAccessibility(); 7851 if (text != null && text.length() > 0) { 7852 ParagraphTextSegmentIterator iterator = 7853 ParagraphTextSegmentIterator.getInstance(); 7854 iterator.initialize(text.toString()); 7855 return iterator; 7856 } 7857 } break; 7858 } 7859 return null; 7860 } 7861 7862 /** 7863 * @hide 7864 */ 7865 public void dispatchStartTemporaryDetach() { 7866 onStartTemporaryDetach(); 7867 } 7868 7869 /** 7870 * This is called when a container is going to temporarily detach a child, with 7871 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 7872 * It will either be followed by {@link #onFinishTemporaryDetach()} or 7873 * {@link #onDetachedFromWindow()} when the container is done. 7874 */ 7875 public void onStartTemporaryDetach() { 7876 removeUnsetPressCallback(); 7877 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 7878 } 7879 7880 /** 7881 * @hide 7882 */ 7883 public void dispatchFinishTemporaryDetach() { 7884 onFinishTemporaryDetach(); 7885 } 7886 7887 /** 7888 * Called after {@link #onStartTemporaryDetach} when the container is done 7889 * changing the view. 7890 */ 7891 public void onFinishTemporaryDetach() { 7892 } 7893 7894 /** 7895 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 7896 * for this view's window. Returns null if the view is not currently attached 7897 * to the window. Normally you will not need to use this directly, but 7898 * just use the standard high-level event callbacks like 7899 * {@link #onKeyDown(int, KeyEvent)}. 7900 */ 7901 public KeyEvent.DispatcherState getKeyDispatcherState() { 7902 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 7903 } 7904 7905 /** 7906 * Dispatch a key event before it is processed by any input method 7907 * associated with the view hierarchy. This can be used to intercept 7908 * key events in special situations before the IME consumes them; a 7909 * typical example would be handling the BACK key to update the application's 7910 * UI instead of allowing the IME to see it and close itself. 7911 * 7912 * @param event The key event to be dispatched. 7913 * @return True if the event was handled, false otherwise. 7914 */ 7915 public boolean dispatchKeyEventPreIme(KeyEvent event) { 7916 return onKeyPreIme(event.getKeyCode(), event); 7917 } 7918 7919 /** 7920 * Dispatch a key event to the next view on the focus path. This path runs 7921 * from the top of the view tree down to the currently focused view. If this 7922 * view has focus, it will dispatch to itself. Otherwise it will dispatch 7923 * the next node down the focus path. This method also fires any key 7924 * listeners. 7925 * 7926 * @param event The key event to be dispatched. 7927 * @return True if the event was handled, false otherwise. 7928 */ 7929 public boolean dispatchKeyEvent(KeyEvent event) { 7930 if (mInputEventConsistencyVerifier != null) { 7931 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 7932 } 7933 7934 // Give any attached key listener a first crack at the event. 7935 //noinspection SimplifiableIfStatement 7936 ListenerInfo li = mListenerInfo; 7937 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7938 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 7939 return true; 7940 } 7941 7942 if (event.dispatch(this, mAttachInfo != null 7943 ? mAttachInfo.mKeyDispatchState : null, this)) { 7944 return true; 7945 } 7946 7947 if (mInputEventConsistencyVerifier != null) { 7948 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7949 } 7950 return false; 7951 } 7952 7953 /** 7954 * Dispatches a key shortcut event. 7955 * 7956 * @param event The key event to be dispatched. 7957 * @return True if the event was handled by the view, false otherwise. 7958 */ 7959 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 7960 return onKeyShortcut(event.getKeyCode(), event); 7961 } 7962 7963 /** 7964 * Pass the touch screen motion event down to the target view, or this 7965 * view if it is the target. 7966 * 7967 * @param event The motion event to be dispatched. 7968 * @return True if the event was handled by the view, false otherwise. 7969 */ 7970 public boolean dispatchTouchEvent(MotionEvent event) { 7971 if (mInputEventConsistencyVerifier != null) { 7972 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 7973 } 7974 7975 if (onFilterTouchEventForSecurity(event)) { 7976 //noinspection SimplifiableIfStatement 7977 ListenerInfo li = mListenerInfo; 7978 if (li != null && li.mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 7979 && li.mOnTouchListener.onTouch(this, event)) { 7980 return true; 7981 } 7982 7983 if (onTouchEvent(event)) { 7984 return true; 7985 } 7986 } 7987 7988 if (mInputEventConsistencyVerifier != null) { 7989 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 7990 } 7991 return false; 7992 } 7993 7994 /** 7995 * Filter the touch event to apply security policies. 7996 * 7997 * @param event The motion event to be filtered. 7998 * @return True if the event should be dispatched, false if the event should be dropped. 7999 * 8000 * @see #getFilterTouchesWhenObscured 8001 */ 8002 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8003 //noinspection RedundantIfStatement 8004 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8005 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8006 // Window is obscured, drop this touch. 8007 return false; 8008 } 8009 return true; 8010 } 8011 8012 /** 8013 * Pass a trackball motion event down to the focused view. 8014 * 8015 * @param event The motion event to be dispatched. 8016 * @return True if the event was handled by the view, false otherwise. 8017 */ 8018 public boolean dispatchTrackballEvent(MotionEvent event) { 8019 if (mInputEventConsistencyVerifier != null) { 8020 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8021 } 8022 8023 return onTrackballEvent(event); 8024 } 8025 8026 /** 8027 * Dispatch a generic motion event. 8028 * <p> 8029 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8030 * are delivered to the view under the pointer. All other generic motion events are 8031 * delivered to the focused view. Hover events are handled specially and are delivered 8032 * to {@link #onHoverEvent(MotionEvent)}. 8033 * </p> 8034 * 8035 * @param event The motion event to be dispatched. 8036 * @return True if the event was handled by the view, false otherwise. 8037 */ 8038 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8039 if (mInputEventConsistencyVerifier != null) { 8040 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8041 } 8042 8043 final int source = event.getSource(); 8044 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8045 final int action = event.getAction(); 8046 if (action == MotionEvent.ACTION_HOVER_ENTER 8047 || action == MotionEvent.ACTION_HOVER_MOVE 8048 || action == MotionEvent.ACTION_HOVER_EXIT) { 8049 if (dispatchHoverEvent(event)) { 8050 return true; 8051 } 8052 } else if (dispatchGenericPointerEvent(event)) { 8053 return true; 8054 } 8055 } else if (dispatchGenericFocusedEvent(event)) { 8056 return true; 8057 } 8058 8059 if (dispatchGenericMotionEventInternal(event)) { 8060 return true; 8061 } 8062 8063 if (mInputEventConsistencyVerifier != null) { 8064 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8065 } 8066 return false; 8067 } 8068 8069 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8070 //noinspection SimplifiableIfStatement 8071 ListenerInfo li = mListenerInfo; 8072 if (li != null && li.mOnGenericMotionListener != null 8073 && (mViewFlags & ENABLED_MASK) == ENABLED 8074 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8075 return true; 8076 } 8077 8078 if (onGenericMotionEvent(event)) { 8079 return true; 8080 } 8081 8082 if (mInputEventConsistencyVerifier != null) { 8083 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8084 } 8085 return false; 8086 } 8087 8088 /** 8089 * Dispatch a hover event. 8090 * <p> 8091 * Do not call this method directly. 8092 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8093 * </p> 8094 * 8095 * @param event The motion event to be dispatched. 8096 * @return True if the event was handled by the view, false otherwise. 8097 */ 8098 protected boolean dispatchHoverEvent(MotionEvent event) { 8099 ListenerInfo li = mListenerInfo; 8100 //noinspection SimplifiableIfStatement 8101 if (li != null && li.mOnHoverListener != null 8102 && (mViewFlags & ENABLED_MASK) == ENABLED 8103 && li.mOnHoverListener.onHover(this, event)) { 8104 return true; 8105 } 8106 8107 return onHoverEvent(event); 8108 } 8109 8110 /** 8111 * Returns true if the view has a child to which it has recently sent 8112 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8113 * it does not have a hovered child, then it must be the innermost hovered view. 8114 * @hide 8115 */ 8116 protected boolean hasHoveredChild() { 8117 return false; 8118 } 8119 8120 /** 8121 * Dispatch a generic motion event to the view under the first pointer. 8122 * <p> 8123 * Do not call this method directly. 8124 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8125 * </p> 8126 * 8127 * @param event The motion event to be dispatched. 8128 * @return True if the event was handled by the view, false otherwise. 8129 */ 8130 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8131 return false; 8132 } 8133 8134 /** 8135 * Dispatch a generic motion event to the currently focused view. 8136 * <p> 8137 * Do not call this method directly. 8138 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8139 * </p> 8140 * 8141 * @param event The motion event to be dispatched. 8142 * @return True if the event was handled by the view, false otherwise. 8143 */ 8144 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8145 return false; 8146 } 8147 8148 /** 8149 * Dispatch a pointer event. 8150 * <p> 8151 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8152 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8153 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8154 * and should not be expected to handle other pointing device features. 8155 * </p> 8156 * 8157 * @param event The motion event to be dispatched. 8158 * @return True if the event was handled by the view, false otherwise. 8159 * @hide 8160 */ 8161 public final boolean dispatchPointerEvent(MotionEvent event) { 8162 if (event.isTouchEvent()) { 8163 return dispatchTouchEvent(event); 8164 } else { 8165 return dispatchGenericMotionEvent(event); 8166 } 8167 } 8168 8169 /** 8170 * Called when the window containing this view gains or loses window focus. 8171 * ViewGroups should override to route to their children. 8172 * 8173 * @param hasFocus True if the window containing this view now has focus, 8174 * false otherwise. 8175 */ 8176 public void dispatchWindowFocusChanged(boolean hasFocus) { 8177 onWindowFocusChanged(hasFocus); 8178 } 8179 8180 /** 8181 * Called when the window containing this view gains or loses focus. Note 8182 * that this is separate from view focus: to receive key events, both 8183 * your view and its window must have focus. If a window is displayed 8184 * on top of yours that takes input focus, then your own window will lose 8185 * focus but the view focus will remain unchanged. 8186 * 8187 * @param hasWindowFocus True if the window containing this view now has 8188 * focus, false otherwise. 8189 */ 8190 public void onWindowFocusChanged(boolean hasWindowFocus) { 8191 InputMethodManager imm = InputMethodManager.peekInstance(); 8192 if (!hasWindowFocus) { 8193 if (isPressed()) { 8194 setPressed(false); 8195 } 8196 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8197 imm.focusOut(this); 8198 } 8199 removeLongPressCallback(); 8200 removeTapCallback(); 8201 onFocusLost(); 8202 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8203 imm.focusIn(this); 8204 } 8205 refreshDrawableState(); 8206 } 8207 8208 /** 8209 * Returns true if this view is in a window that currently has window focus. 8210 * Note that this is not the same as the view itself having focus. 8211 * 8212 * @return True if this view is in a window that currently has window focus. 8213 */ 8214 public boolean hasWindowFocus() { 8215 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8216 } 8217 8218 /** 8219 * Dispatch a view visibility change down the view hierarchy. 8220 * ViewGroups should override to route to their children. 8221 * @param changedView The view whose visibility changed. Could be 'this' or 8222 * an ancestor view. 8223 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8224 * {@link #INVISIBLE} or {@link #GONE}. 8225 */ 8226 protected void dispatchVisibilityChanged(@NonNull View changedView, 8227 @Visibility int visibility) { 8228 onVisibilityChanged(changedView, visibility); 8229 } 8230 8231 /** 8232 * Called when the visibility of the view or an ancestor of the view is changed. 8233 * @param changedView The view whose visibility changed. Could be 'this' or 8234 * an ancestor view. 8235 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8236 * {@link #INVISIBLE} or {@link #GONE}. 8237 */ 8238 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8239 if (visibility == VISIBLE) { 8240 if (mAttachInfo != null) { 8241 initialAwakenScrollBars(); 8242 } else { 8243 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8244 } 8245 } 8246 } 8247 8248 /** 8249 * Dispatch a hint about whether this view is displayed. For instance, when 8250 * a View moves out of the screen, it might receives a display hint indicating 8251 * the view is not displayed. Applications should not <em>rely</em> on this hint 8252 * as there is no guarantee that they will receive one. 8253 * 8254 * @param hint A hint about whether or not this view is displayed: 8255 * {@link #VISIBLE} or {@link #INVISIBLE}. 8256 */ 8257 public void dispatchDisplayHint(@Visibility int hint) { 8258 onDisplayHint(hint); 8259 } 8260 8261 /** 8262 * Gives this view a hint about whether is displayed or not. For instance, when 8263 * a View moves out of the screen, it might receives a display hint indicating 8264 * the view is not displayed. Applications should not <em>rely</em> on this hint 8265 * as there is no guarantee that they will receive one. 8266 * 8267 * @param hint A hint about whether or not this view is displayed: 8268 * {@link #VISIBLE} or {@link #INVISIBLE}. 8269 */ 8270 protected void onDisplayHint(@Visibility int hint) { 8271 } 8272 8273 /** 8274 * Dispatch a window visibility change down the view hierarchy. 8275 * ViewGroups should override to route to their children. 8276 * 8277 * @param visibility The new visibility of the window. 8278 * 8279 * @see #onWindowVisibilityChanged(int) 8280 */ 8281 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8282 onWindowVisibilityChanged(visibility); 8283 } 8284 8285 /** 8286 * Called when the window containing has change its visibility 8287 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8288 * that this tells you whether or not your window is being made visible 8289 * to the window manager; this does <em>not</em> tell you whether or not 8290 * your window is obscured by other windows on the screen, even if it 8291 * is itself visible. 8292 * 8293 * @param visibility The new visibility of the window. 8294 */ 8295 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8296 if (visibility == VISIBLE) { 8297 initialAwakenScrollBars(); 8298 } 8299 } 8300 8301 /** 8302 * Returns the current visibility of the window this view is attached to 8303 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8304 * 8305 * @return Returns the current visibility of the view's window. 8306 */ 8307 @Visibility 8308 public int getWindowVisibility() { 8309 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8310 } 8311 8312 /** 8313 * Retrieve the overall visible display size in which the window this view is 8314 * attached to has been positioned in. This takes into account screen 8315 * decorations above the window, for both cases where the window itself 8316 * is being position inside of them or the window is being placed under 8317 * then and covered insets are used for the window to position its content 8318 * inside. In effect, this tells you the available area where content can 8319 * be placed and remain visible to users. 8320 * 8321 * <p>This function requires an IPC back to the window manager to retrieve 8322 * the requested information, so should not be used in performance critical 8323 * code like drawing. 8324 * 8325 * @param outRect Filled in with the visible display frame. If the view 8326 * is not attached to a window, this is simply the raw display size. 8327 */ 8328 public void getWindowVisibleDisplayFrame(Rect outRect) { 8329 if (mAttachInfo != null) { 8330 try { 8331 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8332 } catch (RemoteException e) { 8333 return; 8334 } 8335 // XXX This is really broken, and probably all needs to be done 8336 // in the window manager, and we need to know more about whether 8337 // we want the area behind or in front of the IME. 8338 final Rect insets = mAttachInfo.mVisibleInsets; 8339 outRect.left += insets.left; 8340 outRect.top += insets.top; 8341 outRect.right -= insets.right; 8342 outRect.bottom -= insets.bottom; 8343 return; 8344 } 8345 // The view is not attached to a display so we don't have a context. 8346 // Make a best guess about the display size. 8347 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8348 d.getRectSize(outRect); 8349 } 8350 8351 /** 8352 * Dispatch a notification about a resource configuration change down 8353 * the view hierarchy. 8354 * ViewGroups should override to route to their children. 8355 * 8356 * @param newConfig The new resource configuration. 8357 * 8358 * @see #onConfigurationChanged(android.content.res.Configuration) 8359 */ 8360 public void dispatchConfigurationChanged(Configuration newConfig) { 8361 onConfigurationChanged(newConfig); 8362 } 8363 8364 /** 8365 * Called when the current configuration of the resources being used 8366 * by the application have changed. You can use this to decide when 8367 * to reload resources that can changed based on orientation and other 8368 * configuration characterstics. You only need to use this if you are 8369 * not relying on the normal {@link android.app.Activity} mechanism of 8370 * recreating the activity instance upon a configuration change. 8371 * 8372 * @param newConfig The new resource configuration. 8373 */ 8374 protected void onConfigurationChanged(Configuration newConfig) { 8375 } 8376 8377 /** 8378 * Private function to aggregate all per-view attributes in to the view 8379 * root. 8380 */ 8381 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8382 performCollectViewAttributes(attachInfo, visibility); 8383 } 8384 8385 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8386 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8387 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8388 attachInfo.mKeepScreenOn = true; 8389 } 8390 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8391 ListenerInfo li = mListenerInfo; 8392 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8393 attachInfo.mHasSystemUiListeners = true; 8394 } 8395 } 8396 } 8397 8398 void needGlobalAttributesUpdate(boolean force) { 8399 final AttachInfo ai = mAttachInfo; 8400 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8401 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8402 || ai.mHasSystemUiListeners) { 8403 ai.mRecomputeGlobalAttributes = true; 8404 } 8405 } 8406 } 8407 8408 /** 8409 * Returns whether the device is currently in touch mode. Touch mode is entered 8410 * once the user begins interacting with the device by touch, and affects various 8411 * things like whether focus is always visible to the user. 8412 * 8413 * @return Whether the device is in touch mode. 8414 */ 8415 @ViewDebug.ExportedProperty 8416 public boolean isInTouchMode() { 8417 if (mAttachInfo != null) { 8418 return mAttachInfo.mInTouchMode; 8419 } else { 8420 return ViewRootImpl.isInTouchMode(); 8421 } 8422 } 8423 8424 /** 8425 * Returns the context the view is running in, through which it can 8426 * access the current theme, resources, etc. 8427 * 8428 * @return The view's Context. 8429 */ 8430 @ViewDebug.CapturedViewProperty 8431 public final Context getContext() { 8432 return mContext; 8433 } 8434 8435 /** 8436 * Handle a key event before it is processed by any input method 8437 * associated with the view hierarchy. This can be used to intercept 8438 * key events in special situations before the IME consumes them; a 8439 * typical example would be handling the BACK key to update the application's 8440 * UI instead of allowing the IME to see it and close itself. 8441 * 8442 * @param keyCode The value in event.getKeyCode(). 8443 * @param event Description of the key event. 8444 * @return If you handled the event, return true. If you want to allow the 8445 * event to be handled by the next receiver, return false. 8446 */ 8447 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8448 return false; 8449 } 8450 8451 /** 8452 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8453 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8454 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8455 * is released, if the view is enabled and clickable. 8456 * 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 * @param keyCode A key code that represents the button pressed, from 8462 * {@link android.view.KeyEvent}. 8463 * @param event The KeyEvent object that defines the button action. 8464 */ 8465 public boolean onKeyDown(int keyCode, KeyEvent event) { 8466 boolean result = false; 8467 8468 if (KeyEvent.isConfirmKey(keyCode)) { 8469 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8470 return true; 8471 } 8472 // Long clickable items don't necessarily have to be clickable 8473 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8474 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8475 (event.getRepeatCount() == 0)) { 8476 setPressed(true); 8477 checkForLongClick(0); 8478 return true; 8479 } 8480 } 8481 return result; 8482 } 8483 8484 /** 8485 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8486 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8487 * the event). 8488 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8489 * although some may elect to do so in some situations. Do not rely on this to 8490 * catch software key presses. 8491 */ 8492 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8493 return false; 8494 } 8495 8496 /** 8497 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8498 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8499 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8500 * {@link KeyEvent#KEYCODE_ENTER} is released. 8501 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8502 * although some may elect to do so in some situations. Do not rely on this to 8503 * catch software key presses. 8504 * 8505 * @param keyCode A key code that represents the button pressed, from 8506 * {@link android.view.KeyEvent}. 8507 * @param event The KeyEvent object that defines the button action. 8508 */ 8509 public boolean onKeyUp(int keyCode, KeyEvent event) { 8510 if (KeyEvent.isConfirmKey(keyCode)) { 8511 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8512 return true; 8513 } 8514 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8515 setPressed(false); 8516 8517 if (!mHasPerformedLongPress) { 8518 // This is a tap, so remove the longpress check 8519 removeLongPressCallback(); 8520 return performClick(); 8521 } 8522 } 8523 } 8524 return false; 8525 } 8526 8527 /** 8528 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8529 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8530 * the event). 8531 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8532 * although some may elect to do so in some situations. Do not rely on this to 8533 * catch software key presses. 8534 * 8535 * @param keyCode A key code that represents the button pressed, from 8536 * {@link android.view.KeyEvent}. 8537 * @param repeatCount The number of times the action was made. 8538 * @param event The KeyEvent object that defines the button action. 8539 */ 8540 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8541 return false; 8542 } 8543 8544 /** 8545 * Called on the focused view when a key shortcut event is not handled. 8546 * Override this method to implement local key shortcuts for the View. 8547 * Key shortcuts can also be implemented by setting the 8548 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8549 * 8550 * @param keyCode The value in event.getKeyCode(). 8551 * @param event Description of the key event. 8552 * @return If you handled the event, return true. If you want to allow the 8553 * event to be handled by the next receiver, return false. 8554 */ 8555 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8556 return false; 8557 } 8558 8559 /** 8560 * Check whether the called view is a text editor, in which case it 8561 * would make sense to automatically display a soft input window for 8562 * it. Subclasses should override this if they implement 8563 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8564 * a call on that method would return a non-null InputConnection, and 8565 * they are really a first-class editor that the user would normally 8566 * start typing on when the go into a window containing your view. 8567 * 8568 * <p>The default implementation always returns false. This does 8569 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8570 * will not be called or the user can not otherwise perform edits on your 8571 * view; it is just a hint to the system that this is not the primary 8572 * purpose of this view. 8573 * 8574 * @return Returns true if this view is a text editor, else false. 8575 */ 8576 public boolean onCheckIsTextEditor() { 8577 return false; 8578 } 8579 8580 /** 8581 * Create a new InputConnection for an InputMethod to interact 8582 * with the view. The default implementation returns null, since it doesn't 8583 * support input methods. You can override this to implement such support. 8584 * This is only needed for views that take focus and text input. 8585 * 8586 * <p>When implementing this, you probably also want to implement 8587 * {@link #onCheckIsTextEditor()} to indicate you will return a 8588 * non-null InputConnection.</p> 8589 * 8590 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 8591 * object correctly and in its entirety, so that the connected IME can rely 8592 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 8593 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 8594 * must be filled in with the correct cursor position for IMEs to work correctly 8595 * with your application.</p> 8596 * 8597 * @param outAttrs Fill in with attribute information about the connection. 8598 */ 8599 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 8600 return null; 8601 } 8602 8603 /** 8604 * Called by the {@link android.view.inputmethod.InputMethodManager} 8605 * when a view who is not the current 8606 * input connection target is trying to make a call on the manager. The 8607 * default implementation returns false; you can override this to return 8608 * true for certain views if you are performing InputConnection proxying 8609 * to them. 8610 * @param view The View that is making the InputMethodManager call. 8611 * @return Return true to allow the call, false to reject. 8612 */ 8613 public boolean checkInputConnectionProxy(View view) { 8614 return false; 8615 } 8616 8617 /** 8618 * Show the context menu for this view. It is not safe to hold on to the 8619 * menu after returning from this method. 8620 * 8621 * You should normally not overload this method. Overload 8622 * {@link #onCreateContextMenu(ContextMenu)} or define an 8623 * {@link OnCreateContextMenuListener} to add items to the context menu. 8624 * 8625 * @param menu The context menu to populate 8626 */ 8627 public void createContextMenu(ContextMenu menu) { 8628 ContextMenuInfo menuInfo = getContextMenuInfo(); 8629 8630 // Sets the current menu info so all items added to menu will have 8631 // my extra info set. 8632 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 8633 8634 onCreateContextMenu(menu); 8635 ListenerInfo li = mListenerInfo; 8636 if (li != null && li.mOnCreateContextMenuListener != null) { 8637 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 8638 } 8639 8640 // Clear the extra information so subsequent items that aren't mine don't 8641 // have my extra info. 8642 ((MenuBuilder)menu).setCurrentMenuInfo(null); 8643 8644 if (mParent != null) { 8645 mParent.createContextMenu(menu); 8646 } 8647 } 8648 8649 /** 8650 * Views should implement this if they have extra information to associate 8651 * with the context menu. The return result is supplied as a parameter to 8652 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 8653 * callback. 8654 * 8655 * @return Extra information about the item for which the context menu 8656 * should be shown. This information will vary across different 8657 * subclasses of View. 8658 */ 8659 protected ContextMenuInfo getContextMenuInfo() { 8660 return null; 8661 } 8662 8663 /** 8664 * Views should implement this if the view itself is going to add items to 8665 * the context menu. 8666 * 8667 * @param menu the context menu to populate 8668 */ 8669 protected void onCreateContextMenu(ContextMenu menu) { 8670 } 8671 8672 /** 8673 * Implement this method to handle trackball motion events. The 8674 * <em>relative</em> movement of the trackball since the last event 8675 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 8676 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 8677 * that a movement of 1 corresponds to the user pressing one DPAD key (so 8678 * they will often be fractional values, representing the more fine-grained 8679 * movement information available from a trackball). 8680 * 8681 * @param event The motion event. 8682 * @return True if the event was handled, false otherwise. 8683 */ 8684 public boolean onTrackballEvent(MotionEvent event) { 8685 return false; 8686 } 8687 8688 /** 8689 * Implement this method to handle generic motion events. 8690 * <p> 8691 * Generic motion events describe joystick movements, mouse hovers, track pad 8692 * touches, scroll wheel movements and other input events. The 8693 * {@link MotionEvent#getSource() source} of the motion event specifies 8694 * the class of input that was received. Implementations of this method 8695 * must examine the bits in the source before processing the event. 8696 * The following code example shows how this is done. 8697 * </p><p> 8698 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8699 * are delivered to the view under the pointer. All other generic motion events are 8700 * delivered to the focused view. 8701 * </p> 8702 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 8703 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 8704 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 8705 * // process the joystick movement... 8706 * return true; 8707 * } 8708 * } 8709 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 8710 * switch (event.getAction()) { 8711 * case MotionEvent.ACTION_HOVER_MOVE: 8712 * // process the mouse hover movement... 8713 * return true; 8714 * case MotionEvent.ACTION_SCROLL: 8715 * // process the scroll wheel movement... 8716 * return true; 8717 * } 8718 * } 8719 * return super.onGenericMotionEvent(event); 8720 * }</pre> 8721 * 8722 * @param event The generic motion event being processed. 8723 * @return True if the event was handled, false otherwise. 8724 */ 8725 public boolean onGenericMotionEvent(MotionEvent event) { 8726 return false; 8727 } 8728 8729 /** 8730 * Implement this method to handle hover events. 8731 * <p> 8732 * This method is called whenever a pointer is hovering into, over, or out of the 8733 * bounds of a view and the view is not currently being touched. 8734 * Hover events are represented as pointer events with action 8735 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 8736 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 8737 * </p> 8738 * <ul> 8739 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 8740 * when the pointer enters the bounds of the view.</li> 8741 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 8742 * when the pointer has already entered the bounds of the view and has moved.</li> 8743 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 8744 * when the pointer has exited the bounds of the view or when the pointer is 8745 * about to go down due to a button click, tap, or similar user action that 8746 * causes the view to be touched.</li> 8747 * </ul> 8748 * <p> 8749 * The view should implement this method to return true to indicate that it is 8750 * handling the hover event, such as by changing its drawable state. 8751 * </p><p> 8752 * The default implementation calls {@link #setHovered} to update the hovered state 8753 * of the view when a hover enter or hover exit event is received, if the view 8754 * is enabled and is clickable. The default implementation also sends hover 8755 * accessibility events. 8756 * </p> 8757 * 8758 * @param event The motion event that describes the hover. 8759 * @return True if the view handled the hover event. 8760 * 8761 * @see #isHovered 8762 * @see #setHovered 8763 * @see #onHoverChanged 8764 */ 8765 public boolean onHoverEvent(MotionEvent event) { 8766 // The root view may receive hover (or touch) events that are outside the bounds of 8767 // the window. This code ensures that we only send accessibility events for 8768 // hovers that are actually within the bounds of the root view. 8769 final int action = event.getActionMasked(); 8770 if (!mSendingHoverAccessibilityEvents) { 8771 if ((action == MotionEvent.ACTION_HOVER_ENTER 8772 || action == MotionEvent.ACTION_HOVER_MOVE) 8773 && !hasHoveredChild() 8774 && pointInView(event.getX(), event.getY())) { 8775 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 8776 mSendingHoverAccessibilityEvents = true; 8777 } 8778 } else { 8779 if (action == MotionEvent.ACTION_HOVER_EXIT 8780 || (action == MotionEvent.ACTION_MOVE 8781 && !pointInView(event.getX(), event.getY()))) { 8782 mSendingHoverAccessibilityEvents = false; 8783 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 8784 } 8785 } 8786 8787 if (isHoverable()) { 8788 switch (action) { 8789 case MotionEvent.ACTION_HOVER_ENTER: 8790 setHovered(true); 8791 break; 8792 case MotionEvent.ACTION_HOVER_EXIT: 8793 setHovered(false); 8794 break; 8795 } 8796 8797 // Dispatch the event to onGenericMotionEvent before returning true. 8798 // This is to provide compatibility with existing applications that 8799 // handled HOVER_MOVE events in onGenericMotionEvent and that would 8800 // break because of the new default handling for hoverable views 8801 // in onHoverEvent. 8802 // Note that onGenericMotionEvent will be called by default when 8803 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 8804 dispatchGenericMotionEventInternal(event); 8805 // The event was already handled by calling setHovered(), so always 8806 // return true. 8807 return true; 8808 } 8809 8810 return false; 8811 } 8812 8813 /** 8814 * Returns true if the view should handle {@link #onHoverEvent} 8815 * by calling {@link #setHovered} to change its hovered state. 8816 * 8817 * @return True if the view is hoverable. 8818 */ 8819 private boolean isHoverable() { 8820 final int viewFlags = mViewFlags; 8821 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8822 return false; 8823 } 8824 8825 return (viewFlags & CLICKABLE) == CLICKABLE 8826 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8827 } 8828 8829 /** 8830 * Returns true if the view is currently hovered. 8831 * 8832 * @return True if the view is currently hovered. 8833 * 8834 * @see #setHovered 8835 * @see #onHoverChanged 8836 */ 8837 @ViewDebug.ExportedProperty 8838 public boolean isHovered() { 8839 return (mPrivateFlags & PFLAG_HOVERED) != 0; 8840 } 8841 8842 /** 8843 * Sets whether the view is currently hovered. 8844 * <p> 8845 * Calling this method also changes the drawable state of the view. This 8846 * enables the view to react to hover by using different drawable resources 8847 * to change its appearance. 8848 * </p><p> 8849 * The {@link #onHoverChanged} method is called when the hovered state changes. 8850 * </p> 8851 * 8852 * @param hovered True if the view is hovered. 8853 * 8854 * @see #isHovered 8855 * @see #onHoverChanged 8856 */ 8857 public void setHovered(boolean hovered) { 8858 if (hovered) { 8859 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 8860 mPrivateFlags |= PFLAG_HOVERED; 8861 refreshDrawableState(); 8862 onHoverChanged(true); 8863 } 8864 } else { 8865 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 8866 mPrivateFlags &= ~PFLAG_HOVERED; 8867 refreshDrawableState(); 8868 onHoverChanged(false); 8869 } 8870 } 8871 } 8872 8873 /** 8874 * Implement this method to handle hover state changes. 8875 * <p> 8876 * This method is called whenever the hover state changes as a result of a 8877 * call to {@link #setHovered}. 8878 * </p> 8879 * 8880 * @param hovered The current hover state, as returned by {@link #isHovered}. 8881 * 8882 * @see #isHovered 8883 * @see #setHovered 8884 */ 8885 public void onHoverChanged(boolean hovered) { 8886 } 8887 8888 /** 8889 * Implement this method to handle touch screen motion events. 8890 * <p> 8891 * If this method is used to detect click actions, it is recommended that 8892 * the actions be performed by implementing and calling 8893 * {@link #performClick()}. This will ensure consistent system behavior, 8894 * including: 8895 * <ul> 8896 * <li>obeying click sound preferences 8897 * <li>dispatching OnClickListener calls 8898 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 8899 * accessibility features are enabled 8900 * </ul> 8901 * 8902 * @param event The motion event. 8903 * @return True if the event was handled, false otherwise. 8904 */ 8905 public boolean onTouchEvent(MotionEvent event) { 8906 final float x = event.getX(); 8907 final float y = event.getY(); 8908 final int viewFlags = mViewFlags; 8909 8910 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8911 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 8912 clearHotspot(R.attr.state_pressed); 8913 setPressed(false); 8914 } 8915 // A disabled view that is clickable still consumes the touch 8916 // events, it just doesn't respond to them. 8917 return (((viewFlags & CLICKABLE) == CLICKABLE || 8918 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 8919 } 8920 8921 if (mTouchDelegate != null) { 8922 if (mTouchDelegate.onTouchEvent(event)) { 8923 return true; 8924 } 8925 } 8926 8927 if (((viewFlags & CLICKABLE) == CLICKABLE || 8928 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 8929 switch (event.getAction()) { 8930 case MotionEvent.ACTION_UP: 8931 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 8932 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 8933 // take focus if we don't have it already and we should in 8934 // touch mode. 8935 boolean focusTaken = false; 8936 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 8937 focusTaken = requestFocus(); 8938 } 8939 8940 if (prepressed) { 8941 // The button is being released before we actually 8942 // showed it as pressed. Make it show the pressed 8943 // state now (before scheduling the click) to ensure 8944 // the user sees it. 8945 setHotspot(R.attr.state_pressed, x, y); 8946 setPressed(true); 8947 } 8948 8949 if (!mHasPerformedLongPress) { 8950 // This is a tap, so remove the longpress check 8951 removeLongPressCallback(); 8952 8953 // Only perform take click actions if we were in the pressed state 8954 if (!focusTaken) { 8955 // Use a Runnable and post this rather than calling 8956 // performClick directly. This lets other visual state 8957 // of the view update before click actions start. 8958 if (mPerformClick == null) { 8959 mPerformClick = new PerformClick(); 8960 } 8961 if (!post(mPerformClick)) { 8962 performClick(); 8963 } 8964 } 8965 } 8966 8967 if (mUnsetPressedState == null) { 8968 mUnsetPressedState = new UnsetPressedState(); 8969 } 8970 8971 if (prepressed) { 8972 postDelayed(mUnsetPressedState, 8973 ViewConfiguration.getPressedStateDuration()); 8974 } else if (!post(mUnsetPressedState)) { 8975 // If the post failed, unpress right now 8976 mUnsetPressedState.run(); 8977 } 8978 8979 removeTapCallback(); 8980 } else { 8981 clearHotspot(R.attr.state_pressed); 8982 } 8983 break; 8984 8985 case MotionEvent.ACTION_DOWN: 8986 mHasPerformedLongPress = false; 8987 8988 if (performButtonActionOnTouchDown(event)) { 8989 break; 8990 } 8991 8992 // Walk up the hierarchy to determine if we're inside a scrolling container. 8993 boolean isInScrollingContainer = isInScrollingContainer(); 8994 8995 // For views inside a scrolling container, delay the pressed feedback for 8996 // a short period in case this is a scroll. 8997 if (isInScrollingContainer) { 8998 mPrivateFlags |= PFLAG_PREPRESSED; 8999 if (mPendingCheckForTap == null) { 9000 mPendingCheckForTap = new CheckForTap(); 9001 } 9002 mPendingCheckForTap.x = event.getX(); 9003 mPendingCheckForTap.y = event.getY(); 9004 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9005 } else { 9006 // Not inside a scrolling container, so show the feedback right away 9007 setHotspot(R.attr.state_pressed, x, y); 9008 setPressed(true); 9009 checkForLongClick(0); 9010 } 9011 break; 9012 9013 case MotionEvent.ACTION_CANCEL: 9014 clearHotspot(R.attr.state_pressed); 9015 setPressed(false); 9016 removeTapCallback(); 9017 removeLongPressCallback(); 9018 break; 9019 9020 case MotionEvent.ACTION_MOVE: 9021 setHotspot(R.attr.state_pressed, x, y); 9022 9023 // Be lenient about moving outside of buttons 9024 if (!pointInView(x, y, mTouchSlop)) { 9025 // Outside button 9026 removeTapCallback(); 9027 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9028 // Remove any future long press/tap checks 9029 removeLongPressCallback(); 9030 9031 setPressed(false); 9032 } 9033 } 9034 break; 9035 } 9036 9037 return true; 9038 } 9039 9040 return false; 9041 } 9042 9043 private void setHotspot(int id, float x, float y) { 9044 final Drawable bg = mBackground; 9045 if (bg != null && bg.supportsHotspots()) { 9046 bg.setHotspot(id, x, y); 9047 } 9048 } 9049 9050 private void clearHotspot(int id) { 9051 final Drawable bg = mBackground; 9052 if (bg != null && bg.supportsHotspots()) { 9053 bg.removeHotspot(id); 9054 } 9055 } 9056 9057 /** 9058 * @hide 9059 */ 9060 public boolean isInScrollingContainer() { 9061 ViewParent p = getParent(); 9062 while (p != null && p instanceof ViewGroup) { 9063 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9064 return true; 9065 } 9066 p = p.getParent(); 9067 } 9068 return false; 9069 } 9070 9071 /** 9072 * Remove the longpress detection timer. 9073 */ 9074 private void removeLongPressCallback() { 9075 if (mPendingCheckForLongPress != null) { 9076 removeCallbacks(mPendingCheckForLongPress); 9077 } 9078 } 9079 9080 /** 9081 * Remove the pending click action 9082 */ 9083 private void removePerformClickCallback() { 9084 if (mPerformClick != null) { 9085 removeCallbacks(mPerformClick); 9086 } 9087 } 9088 9089 /** 9090 * Remove the prepress detection timer. 9091 */ 9092 private void removeUnsetPressCallback() { 9093 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9094 clearHotspot(R.attr.state_pressed); 9095 setPressed(false); 9096 removeCallbacks(mUnsetPressedState); 9097 } 9098 } 9099 9100 /** 9101 * Remove the tap detection timer. 9102 */ 9103 private void removeTapCallback() { 9104 if (mPendingCheckForTap != null) { 9105 mPrivateFlags &= ~PFLAG_PREPRESSED; 9106 removeCallbacks(mPendingCheckForTap); 9107 } 9108 } 9109 9110 /** 9111 * Cancels a pending long press. Your subclass can use this if you 9112 * want the context menu to come up if the user presses and holds 9113 * at the same place, but you don't want it to come up if they press 9114 * and then move around enough to cause scrolling. 9115 */ 9116 public void cancelLongPress() { 9117 removeLongPressCallback(); 9118 9119 /* 9120 * The prepressed state handled by the tap callback is a display 9121 * construct, but the tap callback will post a long press callback 9122 * less its own timeout. Remove it here. 9123 */ 9124 removeTapCallback(); 9125 } 9126 9127 /** 9128 * Remove the pending callback for sending a 9129 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9130 */ 9131 private void removeSendViewScrolledAccessibilityEventCallback() { 9132 if (mSendViewScrolledAccessibilityEvent != null) { 9133 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9134 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9135 } 9136 } 9137 9138 /** 9139 * Sets the TouchDelegate for this View. 9140 */ 9141 public void setTouchDelegate(TouchDelegate delegate) { 9142 mTouchDelegate = delegate; 9143 } 9144 9145 /** 9146 * Gets the TouchDelegate for this View. 9147 */ 9148 public TouchDelegate getTouchDelegate() { 9149 return mTouchDelegate; 9150 } 9151 9152 /** 9153 * Set flags controlling behavior of this view. 9154 * 9155 * @param flags Constant indicating the value which should be set 9156 * @param mask Constant indicating the bit range that should be changed 9157 */ 9158 void setFlags(int flags, int mask) { 9159 final boolean accessibilityEnabled = 9160 AccessibilityManager.getInstance(mContext).isEnabled(); 9161 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9162 9163 int old = mViewFlags; 9164 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9165 9166 int changed = mViewFlags ^ old; 9167 if (changed == 0) { 9168 return; 9169 } 9170 int privateFlags = mPrivateFlags; 9171 9172 /* Check if the FOCUSABLE bit has changed */ 9173 if (((changed & FOCUSABLE_MASK) != 0) && 9174 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9175 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9176 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9177 /* Give up focus if we are no longer focusable */ 9178 clearFocus(); 9179 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9180 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9181 /* 9182 * Tell the view system that we are now available to take focus 9183 * if no one else already has it. 9184 */ 9185 if (mParent != null) mParent.focusableViewAvailable(this); 9186 } 9187 } 9188 9189 final int newVisibility = flags & VISIBILITY_MASK; 9190 if (newVisibility == VISIBLE) { 9191 if ((changed & VISIBILITY_MASK) != 0) { 9192 /* 9193 * If this view is becoming visible, invalidate it in case it changed while 9194 * it was not visible. Marking it drawn ensures that the invalidation will 9195 * go through. 9196 */ 9197 mPrivateFlags |= PFLAG_DRAWN; 9198 invalidate(true); 9199 9200 needGlobalAttributesUpdate(true); 9201 9202 // a view becoming visible is worth notifying the parent 9203 // about in case nothing has focus. even if this specific view 9204 // isn't focusable, it may contain something that is, so let 9205 // the root view try to give this focus if nothing else does. 9206 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9207 mParent.focusableViewAvailable(this); 9208 } 9209 } 9210 } 9211 9212 /* Check if the GONE bit has changed */ 9213 if ((changed & GONE) != 0) { 9214 needGlobalAttributesUpdate(false); 9215 requestLayout(); 9216 9217 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9218 if (hasFocus()) clearFocus(); 9219 clearAccessibilityFocus(); 9220 destroyDrawingCache(); 9221 if (mParent instanceof View) { 9222 // GONE views noop invalidation, so invalidate the parent 9223 ((View) mParent).invalidate(true); 9224 } 9225 // Mark the view drawn to ensure that it gets invalidated properly the next 9226 // time it is visible and gets invalidated 9227 mPrivateFlags |= PFLAG_DRAWN; 9228 } 9229 if (mAttachInfo != null) { 9230 mAttachInfo.mViewVisibilityChanged = true; 9231 } 9232 } 9233 9234 /* Check if the VISIBLE bit has changed */ 9235 if ((changed & INVISIBLE) != 0) { 9236 needGlobalAttributesUpdate(false); 9237 /* 9238 * If this view is becoming invisible, set the DRAWN flag so that 9239 * the next invalidate() will not be skipped. 9240 */ 9241 mPrivateFlags |= PFLAG_DRAWN; 9242 9243 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9244 // root view becoming invisible shouldn't clear focus and accessibility focus 9245 if (getRootView() != this) { 9246 if (hasFocus()) clearFocus(); 9247 clearAccessibilityFocus(); 9248 } 9249 } 9250 if (mAttachInfo != null) { 9251 mAttachInfo.mViewVisibilityChanged = true; 9252 } 9253 } 9254 9255 if ((changed & VISIBILITY_MASK) != 0) { 9256 // If the view is invisible, cleanup its display list to free up resources 9257 if (newVisibility != VISIBLE && mAttachInfo != null) { 9258 cleanupDraw(); 9259 } 9260 9261 if (mParent instanceof ViewGroup) { 9262 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9263 (changed & VISIBILITY_MASK), newVisibility); 9264 ((View) mParent).invalidate(true); 9265 } else if (mParent != null) { 9266 mParent.invalidateChild(this, null); 9267 } 9268 dispatchVisibilityChanged(this, newVisibility); 9269 9270 notifySubtreeAccessibilityStateChangedIfNeeded(); 9271 } 9272 9273 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9274 destroyDrawingCache(); 9275 } 9276 9277 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9278 destroyDrawingCache(); 9279 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9280 invalidateParentCaches(); 9281 } 9282 9283 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9284 destroyDrawingCache(); 9285 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9286 } 9287 9288 if ((changed & DRAW_MASK) != 0) { 9289 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9290 if (mBackground != null) { 9291 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9292 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9293 } else { 9294 mPrivateFlags |= PFLAG_SKIP_DRAW; 9295 } 9296 } else { 9297 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9298 } 9299 requestLayout(); 9300 invalidate(true); 9301 } 9302 9303 if ((changed & KEEP_SCREEN_ON) != 0) { 9304 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9305 mParent.recomputeViewAttributes(this); 9306 } 9307 } 9308 9309 if (accessibilityEnabled) { 9310 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9311 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9312 if (oldIncludeForAccessibility != includeForAccessibility()) { 9313 notifySubtreeAccessibilityStateChangedIfNeeded(); 9314 } else { 9315 notifyViewAccessibilityStateChangedIfNeeded( 9316 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9317 } 9318 } else if ((changed & ENABLED_MASK) != 0) { 9319 notifyViewAccessibilityStateChangedIfNeeded( 9320 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9321 } 9322 } 9323 } 9324 9325 /** 9326 * Change the view's z order in the tree, so it's on top of other sibling 9327 * views. This ordering change may affect layout, if the parent container 9328 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9329 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9330 * method should be followed by calls to {@link #requestLayout()} and 9331 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9332 * with the new child ordering. 9333 * 9334 * @see ViewGroup#bringChildToFront(View) 9335 */ 9336 public void bringToFront() { 9337 if (mParent != null) { 9338 mParent.bringChildToFront(this); 9339 } 9340 } 9341 9342 /** 9343 * This is called in response to an internal scroll in this view (i.e., the 9344 * view scrolled its own contents). This is typically as a result of 9345 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9346 * called. 9347 * 9348 * @param l Current horizontal scroll origin. 9349 * @param t Current vertical scroll origin. 9350 * @param oldl Previous horizontal scroll origin. 9351 * @param oldt Previous vertical scroll origin. 9352 */ 9353 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9354 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9355 postSendViewScrolledAccessibilityEventCallback(); 9356 } 9357 9358 mBackgroundSizeChanged = true; 9359 9360 final AttachInfo ai = mAttachInfo; 9361 if (ai != null) { 9362 ai.mViewScrollChanged = true; 9363 } 9364 } 9365 9366 /** 9367 * Interface definition for a callback to be invoked when the layout bounds of a view 9368 * changes due to layout processing. 9369 */ 9370 public interface OnLayoutChangeListener { 9371 /** 9372 * Called when the layout bounds of a view changes due to layout processing. 9373 * 9374 * @param v The view whose bounds have changed. 9375 * @param left The new value of the view's left property. 9376 * @param top The new value of the view's top property. 9377 * @param right The new value of the view's right property. 9378 * @param bottom The new value of the view's bottom property. 9379 * @param oldLeft The previous value of the view's left property. 9380 * @param oldTop The previous value of the view's top property. 9381 * @param oldRight The previous value of the view's right property. 9382 * @param oldBottom The previous value of the view's bottom property. 9383 */ 9384 void onLayoutChange(View v, int left, int top, int right, int bottom, 9385 int oldLeft, int oldTop, int oldRight, int oldBottom); 9386 } 9387 9388 /** 9389 * This is called during layout when the size of this view has changed. If 9390 * you were just added to the view hierarchy, you're called with the old 9391 * values of 0. 9392 * 9393 * @param w Current width of this view. 9394 * @param h Current height of this view. 9395 * @param oldw Old width of this view. 9396 * @param oldh Old height of this view. 9397 */ 9398 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9399 } 9400 9401 /** 9402 * Called by draw to draw the child views. This may be overridden 9403 * by derived classes to gain control just before its children are drawn 9404 * (but after its own view has been drawn). 9405 * @param canvas the canvas on which to draw the view 9406 */ 9407 protected void dispatchDraw(Canvas canvas) { 9408 9409 } 9410 9411 /** 9412 * Gets the parent of this view. Note that the parent is a 9413 * ViewParent and not necessarily a View. 9414 * 9415 * @return Parent of this view. 9416 */ 9417 public final ViewParent getParent() { 9418 return mParent; 9419 } 9420 9421 /** 9422 * Set the horizontal scrolled position of your view. This will cause a call to 9423 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9424 * invalidated. 9425 * @param value the x position to scroll to 9426 */ 9427 public void setScrollX(int value) { 9428 scrollTo(value, mScrollY); 9429 } 9430 9431 /** 9432 * Set the vertical scrolled position of your view. This will cause a call to 9433 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9434 * invalidated. 9435 * @param value the y position to scroll to 9436 */ 9437 public void setScrollY(int value) { 9438 scrollTo(mScrollX, value); 9439 } 9440 9441 /** 9442 * Return the scrolled left position of this view. This is the left edge of 9443 * the displayed part of your view. You do not need to draw any pixels 9444 * farther left, since those are outside of the frame of your view on 9445 * screen. 9446 * 9447 * @return The left edge of the displayed part of your view, in pixels. 9448 */ 9449 public final int getScrollX() { 9450 return mScrollX; 9451 } 9452 9453 /** 9454 * Return the scrolled top position of this view. This is the top edge of 9455 * the displayed part of your view. You do not need to draw any pixels above 9456 * it, since those are outside of the frame of your view on screen. 9457 * 9458 * @return The top edge of the displayed part of your view, in pixels. 9459 */ 9460 public final int getScrollY() { 9461 return mScrollY; 9462 } 9463 9464 /** 9465 * Return the width of the your view. 9466 * 9467 * @return The width of your view, in pixels. 9468 */ 9469 @ViewDebug.ExportedProperty(category = "layout") 9470 public final int getWidth() { 9471 return mRight - mLeft; 9472 } 9473 9474 /** 9475 * Return the height of your view. 9476 * 9477 * @return The height of your view, in pixels. 9478 */ 9479 @ViewDebug.ExportedProperty(category = "layout") 9480 public final int getHeight() { 9481 return mBottom - mTop; 9482 } 9483 9484 /** 9485 * Return the visible drawing bounds of your view. Fills in the output 9486 * rectangle with the values from getScrollX(), getScrollY(), 9487 * getWidth(), and getHeight(). These bounds do not account for any 9488 * transformation properties currently set on the view, such as 9489 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9490 * 9491 * @param outRect The (scrolled) drawing bounds of the view. 9492 */ 9493 public void getDrawingRect(Rect outRect) { 9494 outRect.left = mScrollX; 9495 outRect.top = mScrollY; 9496 outRect.right = mScrollX + (mRight - mLeft); 9497 outRect.bottom = mScrollY + (mBottom - mTop); 9498 } 9499 9500 /** 9501 * Like {@link #getMeasuredWidthAndState()}, 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 width of this view. 9506 */ 9507 public final int getMeasuredWidth() { 9508 return mMeasuredWidth & MEASURED_SIZE_MASK; 9509 } 9510 9511 /** 9512 * Return the full width 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 #getWidth()} 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 getMeasuredWidthAndState() { 9521 return mMeasuredWidth; 9522 } 9523 9524 /** 9525 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9526 * raw width component (that is the result is masked by 9527 * {@link #MEASURED_SIZE_MASK}). 9528 * 9529 * @return The raw measured height of this view. 9530 */ 9531 public final int getMeasuredHeight() { 9532 return mMeasuredHeight & MEASURED_SIZE_MASK; 9533 } 9534 9535 /** 9536 * Return the full height measurement information for this view as computed 9537 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9538 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9539 * This should be used during measurement and layout calculations only. Use 9540 * {@link #getHeight()} to see how wide a view is after layout. 9541 * 9542 * @return The measured width of this view as a bit mask. 9543 */ 9544 public final int getMeasuredHeightAndState() { 9545 return mMeasuredHeight; 9546 } 9547 9548 /** 9549 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9550 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9551 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9552 * and the height component is at the shifted bits 9553 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9554 */ 9555 public final int getMeasuredState() { 9556 return (mMeasuredWidth&MEASURED_STATE_MASK) 9557 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9558 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9559 } 9560 9561 /** 9562 * The transform matrix of this view, which is calculated based on the current 9563 * roation, scale, and pivot properties. 9564 * 9565 * @see #getRotation() 9566 * @see #getScaleX() 9567 * @see #getScaleY() 9568 * @see #getPivotX() 9569 * @see #getPivotY() 9570 * @return The current transform matrix for the view 9571 */ 9572 public Matrix getMatrix() { 9573 ensureTransformationInfo(); 9574 final Matrix matrix = mTransformationInfo.mMatrix; 9575 mRenderNode.getMatrix(matrix); 9576 return matrix; 9577 } 9578 9579 /** 9580 * Returns true if the transform matrix is the identity matrix. 9581 * Recomputes the matrix if necessary. 9582 * 9583 * @return True if the transform matrix is the identity matrix, false otherwise. 9584 */ 9585 final boolean hasIdentityMatrix() { 9586 return mRenderNode.hasIdentityMatrix(); 9587 } 9588 9589 void ensureTransformationInfo() { 9590 if (mTransformationInfo == null) { 9591 mTransformationInfo = new TransformationInfo(); 9592 } 9593 } 9594 9595 /** 9596 * Utility method to retrieve the inverse of the current mMatrix property. 9597 * We cache the matrix to avoid recalculating it when transform properties 9598 * have not changed. 9599 * 9600 * @return The inverse of the current matrix of this view. 9601 */ 9602 final Matrix getInverseMatrix() { 9603 ensureTransformationInfo(); 9604 if (mTransformationInfo.mInverseMatrix == null) { 9605 mTransformationInfo.mInverseMatrix = new Matrix(); 9606 } 9607 final Matrix matrix = mTransformationInfo.mInverseMatrix; 9608 mRenderNode.getInverseMatrix(matrix); 9609 return matrix; 9610 } 9611 9612 /** 9613 * Gets the distance along the Z axis from the camera to this view. 9614 * 9615 * @see #setCameraDistance(float) 9616 * 9617 * @return The distance along the Z axis. 9618 */ 9619 public float getCameraDistance() { 9620 final float dpi = mResources.getDisplayMetrics().densityDpi; 9621 return -(mRenderNode.getCameraDistance() * dpi); 9622 } 9623 9624 /** 9625 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 9626 * views are drawn) from the camera to this view. The camera's distance 9627 * affects 3D transformations, for instance rotations around the X and Y 9628 * axis. If the rotationX or rotationY properties are changed and this view is 9629 * large (more than half the size of the screen), it is recommended to always 9630 * use a camera distance that's greater than the height (X axis rotation) or 9631 * the width (Y axis rotation) of this view.</p> 9632 * 9633 * <p>The distance of the camera from the view plane can have an affect on the 9634 * perspective distortion of the view when it is rotated around the x or y axis. 9635 * For example, a large distance will result in a large viewing angle, and there 9636 * will not be much perspective distortion of the view as it rotates. A short 9637 * distance may cause much more perspective distortion upon rotation, and can 9638 * also result in some drawing artifacts if the rotated view ends up partially 9639 * behind the camera (which is why the recommendation is to use a distance at 9640 * least as far as the size of the view, if the view is to be rotated.)</p> 9641 * 9642 * <p>The distance is expressed in "depth pixels." The default distance depends 9643 * on the screen density. For instance, on a medium density display, the 9644 * default distance is 1280. On a high density display, the default distance 9645 * is 1920.</p> 9646 * 9647 * <p>If you want to specify a distance that leads to visually consistent 9648 * results across various densities, use the following formula:</p> 9649 * <pre> 9650 * float scale = context.getResources().getDisplayMetrics().density; 9651 * view.setCameraDistance(distance * scale); 9652 * </pre> 9653 * 9654 * <p>The density scale factor of a high density display is 1.5, 9655 * and 1920 = 1280 * 1.5.</p> 9656 * 9657 * @param distance The distance in "depth pixels", if negative the opposite 9658 * value is used 9659 * 9660 * @see #setRotationX(float) 9661 * @see #setRotationY(float) 9662 */ 9663 public void setCameraDistance(float distance) { 9664 final float dpi = mResources.getDisplayMetrics().densityDpi; 9665 9666 invalidateViewProperty(true, false); 9667 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 9668 invalidateViewProperty(false, false); 9669 9670 invalidateParentIfNeededAndWasQuickRejected(); 9671 } 9672 9673 /** 9674 * The degrees that the view is rotated around the pivot point. 9675 * 9676 * @see #setRotation(float) 9677 * @see #getPivotX() 9678 * @see #getPivotY() 9679 * 9680 * @return The degrees of rotation. 9681 */ 9682 @ViewDebug.ExportedProperty(category = "drawing") 9683 public float getRotation() { 9684 return mRenderNode.getRotation(); 9685 } 9686 9687 /** 9688 * Sets the degrees that the view is rotated around the pivot point. Increasing values 9689 * result in clockwise rotation. 9690 * 9691 * @param rotation The degrees of rotation. 9692 * 9693 * @see #getRotation() 9694 * @see #getPivotX() 9695 * @see #getPivotY() 9696 * @see #setRotationX(float) 9697 * @see #setRotationY(float) 9698 * 9699 * @attr ref android.R.styleable#View_rotation 9700 */ 9701 public void setRotation(float rotation) { 9702 if (rotation != getRotation()) { 9703 // Double-invalidation is necessary to capture view's old and new areas 9704 invalidateViewProperty(true, false); 9705 mRenderNode.setRotation(rotation); 9706 invalidateViewProperty(false, true); 9707 9708 invalidateParentIfNeededAndWasQuickRejected(); 9709 } 9710 } 9711 9712 /** 9713 * The degrees that the view is rotated around the vertical axis through the pivot point. 9714 * 9715 * @see #getPivotX() 9716 * @see #getPivotY() 9717 * @see #setRotationY(float) 9718 * 9719 * @return The degrees of Y rotation. 9720 */ 9721 @ViewDebug.ExportedProperty(category = "drawing") 9722 public float getRotationY() { 9723 return mRenderNode.getRotationY(); 9724 } 9725 9726 /** 9727 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 9728 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 9729 * down the y axis. 9730 * 9731 * When rotating large views, it is recommended to adjust the camera distance 9732 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9733 * 9734 * @param rotationY The degrees of Y rotation. 9735 * 9736 * @see #getRotationY() 9737 * @see #getPivotX() 9738 * @see #getPivotY() 9739 * @see #setRotation(float) 9740 * @see #setRotationX(float) 9741 * @see #setCameraDistance(float) 9742 * 9743 * @attr ref android.R.styleable#View_rotationY 9744 */ 9745 public void setRotationY(float rotationY) { 9746 if (rotationY != getRotationY()) { 9747 invalidateViewProperty(true, false); 9748 mRenderNode.setRotationY(rotationY); 9749 invalidateViewProperty(false, true); 9750 9751 invalidateParentIfNeededAndWasQuickRejected(); 9752 } 9753 } 9754 9755 /** 9756 * The degrees that the view is rotated around the horizontal axis through the pivot point. 9757 * 9758 * @see #getPivotX() 9759 * @see #getPivotY() 9760 * @see #setRotationX(float) 9761 * 9762 * @return The degrees of X rotation. 9763 */ 9764 @ViewDebug.ExportedProperty(category = "drawing") 9765 public float getRotationX() { 9766 return mRenderNode.getRotationX(); 9767 } 9768 9769 /** 9770 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 9771 * Increasing values result in clockwise rotation from the viewpoint of looking down the 9772 * x axis. 9773 * 9774 * When rotating large views, it is recommended to adjust the camera distance 9775 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 9776 * 9777 * @param rotationX The degrees of X rotation. 9778 * 9779 * @see #getRotationX() 9780 * @see #getPivotX() 9781 * @see #getPivotY() 9782 * @see #setRotation(float) 9783 * @see #setRotationY(float) 9784 * @see #setCameraDistance(float) 9785 * 9786 * @attr ref android.R.styleable#View_rotationX 9787 */ 9788 public void setRotationX(float rotationX) { 9789 if (rotationX != getRotationX()) { 9790 invalidateViewProperty(true, false); 9791 mRenderNode.setRotationX(rotationX); 9792 invalidateViewProperty(false, true); 9793 9794 invalidateParentIfNeededAndWasQuickRejected(); 9795 } 9796 } 9797 9798 /** 9799 * The amount that the view is scaled in x around the pivot point, as a proportion of 9800 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 9801 * 9802 * <p>By default, this is 1.0f. 9803 * 9804 * @see #getPivotX() 9805 * @see #getPivotY() 9806 * @return The scaling factor. 9807 */ 9808 @ViewDebug.ExportedProperty(category = "drawing") 9809 public float getScaleX() { 9810 return mRenderNode.getScaleX(); 9811 } 9812 9813 /** 9814 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 9815 * the view's unscaled width. A value of 1 means that no scaling is applied. 9816 * 9817 * @param scaleX The scaling factor. 9818 * @see #getPivotX() 9819 * @see #getPivotY() 9820 * 9821 * @attr ref android.R.styleable#View_scaleX 9822 */ 9823 public void setScaleX(float scaleX) { 9824 if (scaleX != getScaleX()) { 9825 invalidateViewProperty(true, false); 9826 mRenderNode.setScaleX(scaleX); 9827 invalidateViewProperty(false, true); 9828 9829 invalidateParentIfNeededAndWasQuickRejected(); 9830 } 9831 } 9832 9833 /** 9834 * The amount that the view is scaled in y around the pivot point, as a proportion of 9835 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 9836 * 9837 * <p>By default, this is 1.0f. 9838 * 9839 * @see #getPivotX() 9840 * @see #getPivotY() 9841 * @return The scaling factor. 9842 */ 9843 @ViewDebug.ExportedProperty(category = "drawing") 9844 public float getScaleY() { 9845 return mRenderNode.getScaleY(); 9846 } 9847 9848 /** 9849 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 9850 * the view's unscaled width. A value of 1 means that no scaling is applied. 9851 * 9852 * @param scaleY The scaling factor. 9853 * @see #getPivotX() 9854 * @see #getPivotY() 9855 * 9856 * @attr ref android.R.styleable#View_scaleY 9857 */ 9858 public void setScaleY(float scaleY) { 9859 if (scaleY != getScaleY()) { 9860 invalidateViewProperty(true, false); 9861 mRenderNode.setScaleY(scaleY); 9862 invalidateViewProperty(false, true); 9863 9864 invalidateParentIfNeededAndWasQuickRejected(); 9865 } 9866 } 9867 9868 /** 9869 * The x location of the point around which the view is {@link #setRotation(float) rotated} 9870 * and {@link #setScaleX(float) scaled}. 9871 * 9872 * @see #getRotation() 9873 * @see #getScaleX() 9874 * @see #getScaleY() 9875 * @see #getPivotY() 9876 * @return The x location of the pivot point. 9877 * 9878 * @attr ref android.R.styleable#View_transformPivotX 9879 */ 9880 @ViewDebug.ExportedProperty(category = "drawing") 9881 public float getPivotX() { 9882 return mRenderNode.getPivotX(); 9883 } 9884 9885 /** 9886 * Sets the x location of the point around which the view is 9887 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 9888 * By default, the pivot point is centered on the object. 9889 * Setting this property disables this behavior and causes the view to use only the 9890 * explicitly set pivotX and pivotY values. 9891 * 9892 * @param pivotX The x location of the pivot point. 9893 * @see #getRotation() 9894 * @see #getScaleX() 9895 * @see #getScaleY() 9896 * @see #getPivotY() 9897 * 9898 * @attr ref android.R.styleable#View_transformPivotX 9899 */ 9900 public void setPivotX(float pivotX) { 9901 if (mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 9902 invalidateViewProperty(true, false); 9903 mRenderNode.setPivotX(pivotX); 9904 invalidateViewProperty(false, true); 9905 9906 invalidateParentIfNeededAndWasQuickRejected(); 9907 } 9908 } 9909 9910 /** 9911 * The y location of the point around which the view is {@link #setRotation(float) rotated} 9912 * and {@link #setScaleY(float) scaled}. 9913 * 9914 * @see #getRotation() 9915 * @see #getScaleX() 9916 * @see #getScaleY() 9917 * @see #getPivotY() 9918 * @return The y location of the pivot point. 9919 * 9920 * @attr ref android.R.styleable#View_transformPivotY 9921 */ 9922 @ViewDebug.ExportedProperty(category = "drawing") 9923 public float getPivotY() { 9924 return mRenderNode.getPivotY(); 9925 } 9926 9927 /** 9928 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 9929 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 9930 * Setting this property disables this behavior and causes the view to use only the 9931 * explicitly set pivotX and pivotY values. 9932 * 9933 * @param pivotY The y location of the pivot point. 9934 * @see #getRotation() 9935 * @see #getScaleX() 9936 * @see #getScaleY() 9937 * @see #getPivotY() 9938 * 9939 * @attr ref android.R.styleable#View_transformPivotY 9940 */ 9941 public void setPivotY(float pivotY) { 9942 if (mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 9943 invalidateViewProperty(true, false); 9944 mRenderNode.setPivotY(pivotY); 9945 invalidateViewProperty(false, true); 9946 9947 invalidateParentIfNeededAndWasQuickRejected(); 9948 } 9949 } 9950 9951 /** 9952 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 9953 * completely transparent and 1 means the view is completely opaque. 9954 * 9955 * <p>By default this is 1.0f. 9956 * @return The opacity of the view. 9957 */ 9958 @ViewDebug.ExportedProperty(category = "drawing") 9959 public float getAlpha() { 9960 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 9961 } 9962 9963 /** 9964 * Returns whether this View has content which overlaps. 9965 * 9966 * <p>This function, intended to be overridden by specific View types, is an optimization when 9967 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 9968 * an offscreen buffer and then composited into place, which can be expensive. If the view has 9969 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 9970 * directly. An example of overlapping rendering is a TextView with a background image, such as 9971 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 9972 * ImageView with only the foreground image. The default implementation returns true; subclasses 9973 * should override if they have cases which can be optimized.</p> 9974 * 9975 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 9976 * necessitates that a View return true if it uses the methods internally without passing the 9977 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 9978 * 9979 * @return true if the content in this view might overlap, false otherwise. 9980 */ 9981 public boolean hasOverlappingRendering() { 9982 return true; 9983 } 9984 9985 /** 9986 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 9987 * completely transparent and 1 means the view is completely opaque.</p> 9988 * 9989 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 9990 * performance implications, especially for large views. It is best to use the alpha property 9991 * sparingly and transiently, as in the case of fading animations.</p> 9992 * 9993 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 9994 * strongly recommended for performance reasons to either override 9995 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 9996 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 9997 * 9998 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 9999 * responsible for applying the opacity itself.</p> 10000 * 10001 * <p>Note that if the view is backed by a 10002 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10003 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10004 * 1.0 will supercede the alpha of the layer paint.</p> 10005 * 10006 * @param alpha The opacity of the view. 10007 * 10008 * @see #hasOverlappingRendering() 10009 * @see #setLayerType(int, android.graphics.Paint) 10010 * 10011 * @attr ref android.R.styleable#View_alpha 10012 */ 10013 public void setAlpha(float alpha) { 10014 ensureTransformationInfo(); 10015 if (mTransformationInfo.mAlpha != alpha) { 10016 mTransformationInfo.mAlpha = alpha; 10017 if (onSetAlpha((int) (alpha * 255))) { 10018 mPrivateFlags |= PFLAG_ALPHA_SET; 10019 // subclass is handling alpha - don't optimize rendering cache invalidation 10020 invalidateParentCaches(); 10021 invalidate(true); 10022 } else { 10023 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10024 invalidateViewProperty(true, false); 10025 mRenderNode.setAlpha(getFinalAlpha()); 10026 } 10027 } 10028 } 10029 10030 /** 10031 * Faster version of setAlpha() which performs the same steps except there are 10032 * no calls to invalidate(). The caller of this function should perform proper invalidation 10033 * on the parent and this object. The return value indicates whether the subclass handles 10034 * alpha (the return value for onSetAlpha()). 10035 * 10036 * @param alpha The new value for the alpha property 10037 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10038 * the new value for the alpha property is different from the old value 10039 */ 10040 boolean setAlphaNoInvalidation(float alpha) { 10041 ensureTransformationInfo(); 10042 if (mTransformationInfo.mAlpha != alpha) { 10043 mTransformationInfo.mAlpha = alpha; 10044 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10045 if (subclassHandlesAlpha) { 10046 mPrivateFlags |= PFLAG_ALPHA_SET; 10047 return true; 10048 } else { 10049 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10050 mRenderNode.setAlpha(getFinalAlpha()); 10051 } 10052 } 10053 return false; 10054 } 10055 10056 /** 10057 * This property is hidden and intended only for use by the Fade transition, which 10058 * animates it to produce a visual translucency that does not side-effect (or get 10059 * affected by) the real alpha property. This value is composited with the other 10060 * alpha value (and the AlphaAnimation value, when that is present) to produce 10061 * a final visual translucency result, which is what is passed into the DisplayList. 10062 * 10063 * @hide 10064 */ 10065 public void setTransitionAlpha(float alpha) { 10066 ensureTransformationInfo(); 10067 if (mTransformationInfo.mTransitionAlpha != alpha) { 10068 mTransformationInfo.mTransitionAlpha = alpha; 10069 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10070 invalidateViewProperty(true, false); 10071 mRenderNode.setAlpha(getFinalAlpha()); 10072 } 10073 } 10074 10075 /** 10076 * Calculates the visual alpha of this view, which is a combination of the actual 10077 * alpha value and the transitionAlpha value (if set). 10078 */ 10079 private float getFinalAlpha() { 10080 if (mTransformationInfo != null) { 10081 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10082 } 10083 return 1; 10084 } 10085 10086 /** 10087 * This property is hidden and intended only for use by the Fade transition, which 10088 * animates it to produce a visual translucency that does not side-effect (or get 10089 * affected by) the real alpha property. This value is composited with the other 10090 * alpha value (and the AlphaAnimation value, when that is present) to produce 10091 * a final visual translucency result, which is what is passed into the DisplayList. 10092 * 10093 * @hide 10094 */ 10095 public float getTransitionAlpha() { 10096 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10097 } 10098 10099 /** 10100 * Top position of this view relative to its parent. 10101 * 10102 * @return The top of this view, in pixels. 10103 */ 10104 @ViewDebug.CapturedViewProperty 10105 public final int getTop() { 10106 return mTop; 10107 } 10108 10109 /** 10110 * Sets the top position of this view relative to its parent. This method is meant to be called 10111 * by the layout system and should not generally be called otherwise, because the property 10112 * may be changed at any time by the layout. 10113 * 10114 * @param top The top of this view, in pixels. 10115 */ 10116 public final void setTop(int top) { 10117 if (top != mTop) { 10118 final boolean matrixIsIdentity = hasIdentityMatrix(); 10119 if (matrixIsIdentity) { 10120 if (mAttachInfo != null) { 10121 int minTop; 10122 int yLoc; 10123 if (top < mTop) { 10124 minTop = top; 10125 yLoc = top - mTop; 10126 } else { 10127 minTop = mTop; 10128 yLoc = 0; 10129 } 10130 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10131 } 10132 } else { 10133 // Double-invalidation is necessary to capture view's old and new areas 10134 invalidate(true); 10135 } 10136 10137 int width = mRight - mLeft; 10138 int oldHeight = mBottom - mTop; 10139 10140 mTop = top; 10141 mRenderNode.setTop(mTop); 10142 10143 sizeChange(width, mBottom - mTop, width, oldHeight); 10144 10145 if (!matrixIsIdentity) { 10146 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10147 invalidate(true); 10148 } 10149 mBackgroundSizeChanged = true; 10150 invalidateParentIfNeeded(); 10151 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10152 // View was rejected last time it was drawn by its parent; this may have changed 10153 invalidateParentIfNeeded(); 10154 } 10155 } 10156 } 10157 10158 /** 10159 * Bottom position of this view relative to its parent. 10160 * 10161 * @return The bottom of this view, in pixels. 10162 */ 10163 @ViewDebug.CapturedViewProperty 10164 public final int getBottom() { 10165 return mBottom; 10166 } 10167 10168 /** 10169 * True if this view has changed since the last time being drawn. 10170 * 10171 * @return The dirty state of this view. 10172 */ 10173 public boolean isDirty() { 10174 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10175 } 10176 10177 /** 10178 * Sets the bottom position of this view relative to its parent. This method is meant to be 10179 * called by the layout system and should not generally be called otherwise, because the 10180 * property may be changed at any time by the layout. 10181 * 10182 * @param bottom The bottom of this view, in pixels. 10183 */ 10184 public final void setBottom(int bottom) { 10185 if (bottom != mBottom) { 10186 final boolean matrixIsIdentity = hasIdentityMatrix(); 10187 if (matrixIsIdentity) { 10188 if (mAttachInfo != null) { 10189 int maxBottom; 10190 if (bottom < mBottom) { 10191 maxBottom = mBottom; 10192 } else { 10193 maxBottom = bottom; 10194 } 10195 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10196 } 10197 } else { 10198 // Double-invalidation is necessary to capture view's old and new areas 10199 invalidate(true); 10200 } 10201 10202 int width = mRight - mLeft; 10203 int oldHeight = mBottom - mTop; 10204 10205 mBottom = bottom; 10206 mRenderNode.setBottom(mBottom); 10207 10208 sizeChange(width, mBottom - mTop, width, oldHeight); 10209 10210 if (!matrixIsIdentity) { 10211 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10212 invalidate(true); 10213 } 10214 mBackgroundSizeChanged = true; 10215 invalidateParentIfNeeded(); 10216 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10217 // View was rejected last time it was drawn by its parent; this may have changed 10218 invalidateParentIfNeeded(); 10219 } 10220 } 10221 } 10222 10223 /** 10224 * Left position of this view relative to its parent. 10225 * 10226 * @return The left edge of this view, in pixels. 10227 */ 10228 @ViewDebug.CapturedViewProperty 10229 public final int getLeft() { 10230 return mLeft; 10231 } 10232 10233 /** 10234 * Sets the left position of this view relative to its parent. This method is meant to be called 10235 * by the layout system and should not generally be called otherwise, because the property 10236 * may be changed at any time by the layout. 10237 * 10238 * @param left The left of this view, in pixels. 10239 */ 10240 public final void setLeft(int left) { 10241 if (left != mLeft) { 10242 final boolean matrixIsIdentity = hasIdentityMatrix(); 10243 if (matrixIsIdentity) { 10244 if (mAttachInfo != null) { 10245 int minLeft; 10246 int xLoc; 10247 if (left < mLeft) { 10248 minLeft = left; 10249 xLoc = left - mLeft; 10250 } else { 10251 minLeft = mLeft; 10252 xLoc = 0; 10253 } 10254 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10255 } 10256 } else { 10257 // Double-invalidation is necessary to capture view's old and new areas 10258 invalidate(true); 10259 } 10260 10261 int oldWidth = mRight - mLeft; 10262 int height = mBottom - mTop; 10263 10264 mLeft = left; 10265 mRenderNode.setLeft(left); 10266 10267 sizeChange(mRight - mLeft, height, oldWidth, height); 10268 10269 if (!matrixIsIdentity) { 10270 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10271 invalidate(true); 10272 } 10273 mBackgroundSizeChanged = true; 10274 invalidateParentIfNeeded(); 10275 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10276 // View was rejected last time it was drawn by its parent; this may have changed 10277 invalidateParentIfNeeded(); 10278 } 10279 } 10280 } 10281 10282 /** 10283 * Right position of this view relative to its parent. 10284 * 10285 * @return The right edge of this view, in pixels. 10286 */ 10287 @ViewDebug.CapturedViewProperty 10288 public final int getRight() { 10289 return mRight; 10290 } 10291 10292 /** 10293 * Sets the right position of this view relative to its parent. This method is meant to be called 10294 * by the layout system and should not generally be called otherwise, because the property 10295 * may be changed at any time by the layout. 10296 * 10297 * @param right The right of this view, in pixels. 10298 */ 10299 public final void setRight(int right) { 10300 if (right != mRight) { 10301 final boolean matrixIsIdentity = hasIdentityMatrix(); 10302 if (matrixIsIdentity) { 10303 if (mAttachInfo != null) { 10304 int maxRight; 10305 if (right < mRight) { 10306 maxRight = mRight; 10307 } else { 10308 maxRight = right; 10309 } 10310 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10311 } 10312 } else { 10313 // Double-invalidation is necessary to capture view's old and new areas 10314 invalidate(true); 10315 } 10316 10317 int oldWidth = mRight - mLeft; 10318 int height = mBottom - mTop; 10319 10320 mRight = right; 10321 mRenderNode.setRight(mRight); 10322 10323 sizeChange(mRight - mLeft, height, oldWidth, height); 10324 10325 if (!matrixIsIdentity) { 10326 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10327 invalidate(true); 10328 } 10329 mBackgroundSizeChanged = true; 10330 invalidateParentIfNeeded(); 10331 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10332 // View was rejected last time it was drawn by its parent; this may have changed 10333 invalidateParentIfNeeded(); 10334 } 10335 } 10336 } 10337 10338 /** 10339 * The visual x position of this view, in pixels. This is equivalent to the 10340 * {@link #setTranslationX(float) translationX} property plus the current 10341 * {@link #getLeft() left} property. 10342 * 10343 * @return The visual x position of this view, in pixels. 10344 */ 10345 @ViewDebug.ExportedProperty(category = "drawing") 10346 public float getX() { 10347 return mLeft + getTranslationX(); 10348 } 10349 10350 /** 10351 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10352 * {@link #setTranslationX(float) translationX} property to be the difference between 10353 * the x value passed in and the current {@link #getLeft() left} property. 10354 * 10355 * @param x The visual x position of this view, in pixels. 10356 */ 10357 public void setX(float x) { 10358 setTranslationX(x - mLeft); 10359 } 10360 10361 /** 10362 * The visual y position of this view, in pixels. This is equivalent to the 10363 * {@link #setTranslationY(float) translationY} property plus the current 10364 * {@link #getTop() top} property. 10365 * 10366 * @return The visual y position of this view, in pixels. 10367 */ 10368 @ViewDebug.ExportedProperty(category = "drawing") 10369 public float getY() { 10370 return mTop + getTranslationY(); 10371 } 10372 10373 /** 10374 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10375 * {@link #setTranslationY(float) translationY} property to be the difference between 10376 * the y value passed in and the current {@link #getTop() top} property. 10377 * 10378 * @param y The visual y position of this view, in pixels. 10379 */ 10380 public void setY(float y) { 10381 setTranslationY(y - mTop); 10382 } 10383 10384 10385 /** 10386 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10387 * This position is post-layout, in addition to wherever the object's 10388 * layout placed it. 10389 * 10390 * @return The horizontal position of this view relative to its left position, in pixels. 10391 */ 10392 @ViewDebug.ExportedProperty(category = "drawing") 10393 public float getTranslationX() { 10394 return mRenderNode.getTranslationX(); 10395 } 10396 10397 /** 10398 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10399 * This effectively positions the object post-layout, in addition to wherever the object's 10400 * layout placed it. 10401 * 10402 * @param translationX The horizontal position of this view relative to its left position, 10403 * in pixels. 10404 * 10405 * @attr ref android.R.styleable#View_translationX 10406 */ 10407 public void setTranslationX(float translationX) { 10408 if (translationX != getTranslationX()) { 10409 invalidateViewProperty(true, false); 10410 mRenderNode.setTranslationX(translationX); 10411 invalidateViewProperty(false, true); 10412 10413 invalidateParentIfNeededAndWasQuickRejected(); 10414 } 10415 } 10416 10417 /** 10418 * The vertical location of this view relative to its {@link #getTop() top} position. 10419 * This position is post-layout, in addition to wherever the object's 10420 * layout placed it. 10421 * 10422 * @return The vertical position of this view relative to its top position, 10423 * in pixels. 10424 */ 10425 @ViewDebug.ExportedProperty(category = "drawing") 10426 public float getTranslationY() { 10427 return mRenderNode.getTranslationY(); 10428 } 10429 10430 /** 10431 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10432 * This effectively positions the object post-layout, in addition to wherever the object's 10433 * layout placed it. 10434 * 10435 * @param translationY The vertical position of this view relative to its top position, 10436 * in pixels. 10437 * 10438 * @attr ref android.R.styleable#View_translationY 10439 */ 10440 public void setTranslationY(float translationY) { 10441 if (translationY != getTranslationY()) { 10442 invalidateViewProperty(true, false); 10443 mRenderNode.setTranslationY(translationY); 10444 invalidateViewProperty(false, true); 10445 10446 invalidateParentIfNeededAndWasQuickRejected(); 10447 } 10448 } 10449 10450 /** 10451 * The depth location of this view relative to its parent. 10452 * 10453 * @return The depth of this view relative to its parent. 10454 */ 10455 @ViewDebug.ExportedProperty(category = "drawing") 10456 public float getTranslationZ() { 10457 return mRenderNode.getTranslationZ(); 10458 } 10459 10460 /** 10461 * Sets the depth location of this view relative to its parent. 10462 * 10463 * @attr ref android.R.styleable#View_translationZ 10464 */ 10465 public void setTranslationZ(float translationZ) { 10466 if (translationZ != getTranslationZ()) { 10467 invalidateViewProperty(true, false); 10468 mRenderNode.setTranslationZ(translationZ); 10469 invalidateViewProperty(false, true); 10470 10471 invalidateParentIfNeededAndWasQuickRejected(); 10472 } 10473 } 10474 10475 /** 10476 * Returns a ValueAnimator which can animate a clipping circle. 10477 * <p> 10478 * The View will be clipped to the animating circle. 10479 * <p> 10480 * Any shadow cast by the View will respect the circular clip from this animator. 10481 * 10482 * @param centerX The x coordinate of the center of the animating circle. 10483 * @param centerY The y coordinate of the center of the animating circle. 10484 * @param startRadius The starting radius of the animating circle. 10485 * @param endRadius The ending radius of the animating circle. 10486 */ 10487 public final ValueAnimator createRevealAnimator(int centerX, int centerY, 10488 float startRadius, float endRadius) { 10489 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10490 startRadius, endRadius, false); 10491 } 10492 10493 /** 10494 * Returns a ValueAnimator which can animate a clearing circle. 10495 * <p> 10496 * The View is prevented from drawing within the circle, so the content 10497 * behind the View shows through. 10498 * 10499 * @param centerX The x coordinate of the center of the animating circle. 10500 * @param centerY The y coordinate of the center of the animating circle. 10501 * @param startRadius The starting radius of the animating circle. 10502 * @param endRadius The ending radius of the animating circle. 10503 * 10504 * @hide 10505 */ 10506 public final ValueAnimator createClearCircleAnimator(int centerX, int centerY, 10507 float startRadius, float endRadius) { 10508 return RevealAnimator.ofRevealCircle(this, centerX, centerY, 10509 startRadius, endRadius, true); 10510 } 10511 10512 /** 10513 * Sets the outline of the view, which defines the shape of the shadow it 10514 * casts. 10515 * <p> 10516 * If the outline is not set or is null, shadows will be cast from the 10517 * bounds of the View. 10518 * 10519 * @param outline The new outline of the view. 10520 * Must be {@link android.graphics.Outline#isValid() valid.} 10521 */ 10522 public void setOutline(@Nullable Outline outline) { 10523 if (outline != null && !outline.isValid()) { 10524 throw new IllegalArgumentException("Outline must not be invalid"); 10525 } 10526 10527 mPrivateFlags3 |= PFLAG3_OUTLINE_DEFINED; 10528 10529 if (outline == null) { 10530 mOutline = null; 10531 } else { 10532 // always copy the path since caller may reuse 10533 if (mOutline == null) { 10534 mOutline = new Outline(outline); 10535 } 10536 } 10537 mRenderNode.setOutline(mOutline); 10538 } 10539 10540 // TODO: remove 10541 public final boolean getClipToOutline() { return false; } 10542 public void setClipToOutline(boolean clipToOutline) {} 10543 10544 private void queryOutlineFromBackgroundIfUndefined() { 10545 if ((mPrivateFlags3 & PFLAG3_OUTLINE_DEFINED) == 0) { 10546 // Outline not currently defined, query from background 10547 if (mOutline == null) { 10548 mOutline = new Outline(); 10549 } else { 10550 mOutline.markInvalid(); 10551 } 10552 if (mBackground.getOutline(mOutline)) { 10553 if (!mOutline.isValid()) { 10554 throw new IllegalStateException("Background drawable failed to build outline"); 10555 } 10556 mRenderNode.setOutline(mOutline); 10557 } else { 10558 mRenderNode.setOutline(null); 10559 } 10560 } 10561 } 10562 10563 /** 10564 * Private API to be used for reveal animation 10565 * 10566 * @hide 10567 */ 10568 public void setRevealClip(boolean shouldClip, boolean inverseClip, 10569 float x, float y, float radius) { 10570 mRenderNode.setRevealClip(shouldClip, inverseClip, x, y, radius); 10571 // TODO: Handle this invalidate in a better way, or purely in native. 10572 invalidate(); 10573 } 10574 10575 /** 10576 * Hit rectangle in parent's coordinates 10577 * 10578 * @param outRect The hit rectangle of the view. 10579 */ 10580 public void getHitRect(Rect outRect) { 10581 if (hasIdentityMatrix() || mAttachInfo == null) { 10582 outRect.set(mLeft, mTop, mRight, mBottom); 10583 } else { 10584 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 10585 tmpRect.set(0, 0, getWidth(), getHeight()); 10586 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 10587 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 10588 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 10589 } 10590 } 10591 10592 /** 10593 * Determines whether the given point, in local coordinates is inside the view. 10594 */ 10595 /*package*/ final boolean pointInView(float localX, float localY) { 10596 return localX >= 0 && localX < (mRight - mLeft) 10597 && localY >= 0 && localY < (mBottom - mTop); 10598 } 10599 10600 /** 10601 * Utility method to determine whether the given point, in local coordinates, 10602 * is inside the view, where the area of the view is expanded by the slop factor. 10603 * This method is called while processing touch-move events to determine if the event 10604 * is still within the view. 10605 * 10606 * @hide 10607 */ 10608 public boolean pointInView(float localX, float localY, float slop) { 10609 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 10610 localY < ((mBottom - mTop) + slop); 10611 } 10612 10613 /** 10614 * When a view has focus and the user navigates away from it, the next view is searched for 10615 * starting from the rectangle filled in by this method. 10616 * 10617 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 10618 * of the view. However, if your view maintains some idea of internal selection, 10619 * such as a cursor, or a selected row or column, you should override this method and 10620 * fill in a more specific rectangle. 10621 * 10622 * @param r The rectangle to fill in, in this view's coordinates. 10623 */ 10624 public void getFocusedRect(Rect r) { 10625 getDrawingRect(r); 10626 } 10627 10628 /** 10629 * If some part of this view is not clipped by any of its parents, then 10630 * return that area in r in global (root) coordinates. To convert r to local 10631 * coordinates (without taking possible View rotations into account), offset 10632 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 10633 * If the view is completely clipped or translated out, return false. 10634 * 10635 * @param r If true is returned, r holds the global coordinates of the 10636 * visible portion of this view. 10637 * @param globalOffset If true is returned, globalOffset holds the dx,dy 10638 * between this view and its root. globalOffet may be null. 10639 * @return true if r is non-empty (i.e. part of the view is visible at the 10640 * root level. 10641 */ 10642 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 10643 int width = mRight - mLeft; 10644 int height = mBottom - mTop; 10645 if (width > 0 && height > 0) { 10646 r.set(0, 0, width, height); 10647 if (globalOffset != null) { 10648 globalOffset.set(-mScrollX, -mScrollY); 10649 } 10650 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 10651 } 10652 return false; 10653 } 10654 10655 public final boolean getGlobalVisibleRect(Rect r) { 10656 return getGlobalVisibleRect(r, null); 10657 } 10658 10659 public final boolean getLocalVisibleRect(Rect r) { 10660 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 10661 if (getGlobalVisibleRect(r, offset)) { 10662 r.offset(-offset.x, -offset.y); // make r local 10663 return true; 10664 } 10665 return false; 10666 } 10667 10668 /** 10669 * Offset this view's vertical location by the specified number of pixels. 10670 * 10671 * @param offset the number of pixels to offset the view by 10672 */ 10673 public void offsetTopAndBottom(int offset) { 10674 if (offset != 0) { 10675 final boolean matrixIsIdentity = hasIdentityMatrix(); 10676 if (matrixIsIdentity) { 10677 if (isHardwareAccelerated()) { 10678 invalidateViewProperty(false, false); 10679 } else { 10680 final ViewParent p = mParent; 10681 if (p != null && mAttachInfo != null) { 10682 final Rect r = mAttachInfo.mTmpInvalRect; 10683 int minTop; 10684 int maxBottom; 10685 int yLoc; 10686 if (offset < 0) { 10687 minTop = mTop + offset; 10688 maxBottom = mBottom; 10689 yLoc = offset; 10690 } else { 10691 minTop = mTop; 10692 maxBottom = mBottom + offset; 10693 yLoc = 0; 10694 } 10695 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 10696 p.invalidateChild(this, r); 10697 } 10698 } 10699 } else { 10700 invalidateViewProperty(false, false); 10701 } 10702 10703 mTop += offset; 10704 mBottom += offset; 10705 mRenderNode.offsetTopAndBottom(offset); 10706 if (isHardwareAccelerated()) { 10707 invalidateViewProperty(false, false); 10708 } else { 10709 if (!matrixIsIdentity) { 10710 invalidateViewProperty(false, true); 10711 } 10712 invalidateParentIfNeeded(); 10713 } 10714 } 10715 } 10716 10717 /** 10718 * Offset this view's horizontal location by the specified amount of pixels. 10719 * 10720 * @param offset the number of pixels to offset the view by 10721 */ 10722 public void offsetLeftAndRight(int offset) { 10723 if (offset != 0) { 10724 final boolean matrixIsIdentity = hasIdentityMatrix(); 10725 if (matrixIsIdentity) { 10726 if (isHardwareAccelerated()) { 10727 invalidateViewProperty(false, false); 10728 } else { 10729 final ViewParent p = mParent; 10730 if (p != null && mAttachInfo != null) { 10731 final Rect r = mAttachInfo.mTmpInvalRect; 10732 int minLeft; 10733 int maxRight; 10734 if (offset < 0) { 10735 minLeft = mLeft + offset; 10736 maxRight = mRight; 10737 } else { 10738 minLeft = mLeft; 10739 maxRight = mRight + offset; 10740 } 10741 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 10742 p.invalidateChild(this, r); 10743 } 10744 } 10745 } else { 10746 invalidateViewProperty(false, false); 10747 } 10748 10749 mLeft += offset; 10750 mRight += offset; 10751 mRenderNode.offsetLeftAndRight(offset); 10752 if (isHardwareAccelerated()) { 10753 invalidateViewProperty(false, false); 10754 } else { 10755 if (!matrixIsIdentity) { 10756 invalidateViewProperty(false, true); 10757 } 10758 invalidateParentIfNeeded(); 10759 } 10760 } 10761 } 10762 10763 /** 10764 * Get the LayoutParams associated with this view. All views should have 10765 * layout parameters. These supply parameters to the <i>parent</i> of this 10766 * view specifying how it should be arranged. There are many subclasses of 10767 * ViewGroup.LayoutParams, and these correspond to the different subclasses 10768 * of ViewGroup that are responsible for arranging their children. 10769 * 10770 * This method may return null if this View is not attached to a parent 10771 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 10772 * was not invoked successfully. When a View is attached to a parent 10773 * ViewGroup, this method must not return null. 10774 * 10775 * @return The LayoutParams associated with this view, or null if no 10776 * parameters have been set yet 10777 */ 10778 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 10779 public ViewGroup.LayoutParams getLayoutParams() { 10780 return mLayoutParams; 10781 } 10782 10783 /** 10784 * Set the layout parameters associated with this view. These supply 10785 * parameters to the <i>parent</i> of this view specifying how it should be 10786 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 10787 * correspond to the different subclasses of ViewGroup that are responsible 10788 * for arranging their children. 10789 * 10790 * @param params The layout parameters for this view, cannot be null 10791 */ 10792 public void setLayoutParams(ViewGroup.LayoutParams params) { 10793 if (params == null) { 10794 throw new NullPointerException("Layout parameters cannot be null"); 10795 } 10796 mLayoutParams = params; 10797 resolveLayoutParams(); 10798 if (mParent instanceof ViewGroup) { 10799 ((ViewGroup) mParent).onSetLayoutParams(this, params); 10800 } 10801 requestLayout(); 10802 } 10803 10804 /** 10805 * Resolve the layout parameters depending on the resolved layout direction 10806 * 10807 * @hide 10808 */ 10809 public void resolveLayoutParams() { 10810 if (mLayoutParams != null) { 10811 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 10812 } 10813 } 10814 10815 /** 10816 * Set the scrolled position of your view. This will cause a call to 10817 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10818 * invalidated. 10819 * @param x the x position to scroll to 10820 * @param y the y position to scroll to 10821 */ 10822 public void scrollTo(int x, int y) { 10823 if (mScrollX != x || mScrollY != y) { 10824 int oldX = mScrollX; 10825 int oldY = mScrollY; 10826 mScrollX = x; 10827 mScrollY = y; 10828 invalidateParentCaches(); 10829 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 10830 if (!awakenScrollBars()) { 10831 postInvalidateOnAnimation(); 10832 } 10833 } 10834 } 10835 10836 /** 10837 * Move the scrolled position of your view. This will cause a call to 10838 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10839 * invalidated. 10840 * @param x the amount of pixels to scroll by horizontally 10841 * @param y the amount of pixels to scroll by vertically 10842 */ 10843 public void scrollBy(int x, int y) { 10844 scrollTo(mScrollX + x, mScrollY + y); 10845 } 10846 10847 /** 10848 * <p>Trigger the scrollbars to draw. When invoked this method starts an 10849 * animation to fade the scrollbars out after a default delay. If a subclass 10850 * provides animated scrolling, the start delay should equal the duration 10851 * of the scrolling animation.</p> 10852 * 10853 * <p>The animation starts only if at least one of the scrollbars is 10854 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 10855 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10856 * this method returns true, and false otherwise. If the animation is 10857 * started, this method calls {@link #invalidate()}; in that case the 10858 * caller should not call {@link #invalidate()}.</p> 10859 * 10860 * <p>This method should be invoked every time a subclass directly updates 10861 * the scroll parameters.</p> 10862 * 10863 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 10864 * and {@link #scrollTo(int, int)}.</p> 10865 * 10866 * @return true if the animation is played, false otherwise 10867 * 10868 * @see #awakenScrollBars(int) 10869 * @see #scrollBy(int, int) 10870 * @see #scrollTo(int, int) 10871 * @see #isHorizontalScrollBarEnabled() 10872 * @see #isVerticalScrollBarEnabled() 10873 * @see #setHorizontalScrollBarEnabled(boolean) 10874 * @see #setVerticalScrollBarEnabled(boolean) 10875 */ 10876 protected boolean awakenScrollBars() { 10877 return mScrollCache != null && 10878 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 10879 } 10880 10881 /** 10882 * Trigger the scrollbars to draw. 10883 * This method differs from awakenScrollBars() only in its default duration. 10884 * initialAwakenScrollBars() will show the scroll bars for longer than 10885 * usual to give the user more of a chance to notice them. 10886 * 10887 * @return true if the animation is played, false otherwise. 10888 */ 10889 private boolean initialAwakenScrollBars() { 10890 return mScrollCache != null && 10891 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 10892 } 10893 10894 /** 10895 * <p> 10896 * Trigger the scrollbars to draw. When invoked this method starts an 10897 * animation to fade the scrollbars out after a fixed delay. If a subclass 10898 * provides animated scrolling, the start delay should equal the duration of 10899 * the scrolling animation. 10900 * </p> 10901 * 10902 * <p> 10903 * The animation starts only if at least one of the scrollbars is enabled, 10904 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10905 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10906 * this method returns true, and false otherwise. If the animation is 10907 * started, this method calls {@link #invalidate()}; in that case the caller 10908 * should not call {@link #invalidate()}. 10909 * </p> 10910 * 10911 * <p> 10912 * This method should be invoked everytime a subclass directly updates the 10913 * scroll parameters. 10914 * </p> 10915 * 10916 * @param startDelay the delay, in milliseconds, after which the animation 10917 * should start; when the delay is 0, the animation starts 10918 * immediately 10919 * @return true if the animation is played, false otherwise 10920 * 10921 * @see #scrollBy(int, int) 10922 * @see #scrollTo(int, int) 10923 * @see #isHorizontalScrollBarEnabled() 10924 * @see #isVerticalScrollBarEnabled() 10925 * @see #setHorizontalScrollBarEnabled(boolean) 10926 * @see #setVerticalScrollBarEnabled(boolean) 10927 */ 10928 protected boolean awakenScrollBars(int startDelay) { 10929 return awakenScrollBars(startDelay, true); 10930 } 10931 10932 /** 10933 * <p> 10934 * Trigger the scrollbars to draw. When invoked this method starts an 10935 * animation to fade the scrollbars out after a fixed delay. If a subclass 10936 * provides animated scrolling, the start delay should equal the duration of 10937 * the scrolling animation. 10938 * </p> 10939 * 10940 * <p> 10941 * The animation starts only if at least one of the scrollbars is enabled, 10942 * as specified by {@link #isHorizontalScrollBarEnabled()} and 10943 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 10944 * this method returns true, and false otherwise. If the animation is 10945 * started, this method calls {@link #invalidate()} if the invalidate parameter 10946 * is set to true; in that case the caller 10947 * should not call {@link #invalidate()}. 10948 * </p> 10949 * 10950 * <p> 10951 * This method should be invoked everytime a subclass directly updates the 10952 * scroll parameters. 10953 * </p> 10954 * 10955 * @param startDelay the delay, in milliseconds, after which the animation 10956 * should start; when the delay is 0, the animation starts 10957 * immediately 10958 * 10959 * @param invalidate Wheter this method should call invalidate 10960 * 10961 * @return true if the animation is played, false otherwise 10962 * 10963 * @see #scrollBy(int, int) 10964 * @see #scrollTo(int, int) 10965 * @see #isHorizontalScrollBarEnabled() 10966 * @see #isVerticalScrollBarEnabled() 10967 * @see #setHorizontalScrollBarEnabled(boolean) 10968 * @see #setVerticalScrollBarEnabled(boolean) 10969 */ 10970 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 10971 final ScrollabilityCache scrollCache = mScrollCache; 10972 10973 if (scrollCache == null || !scrollCache.fadeScrollBars) { 10974 return false; 10975 } 10976 10977 if (scrollCache.scrollBar == null) { 10978 scrollCache.scrollBar = new ScrollBarDrawable(); 10979 } 10980 10981 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 10982 10983 if (invalidate) { 10984 // Invalidate to show the scrollbars 10985 postInvalidateOnAnimation(); 10986 } 10987 10988 if (scrollCache.state == ScrollabilityCache.OFF) { 10989 // FIXME: this is copied from WindowManagerService. 10990 // We should get this value from the system when it 10991 // is possible to do so. 10992 final int KEY_REPEAT_FIRST_DELAY = 750; 10993 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 10994 } 10995 10996 // Tell mScrollCache when we should start fading. This may 10997 // extend the fade start time if one was already scheduled 10998 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 10999 scrollCache.fadeStartTime = fadeStartTime; 11000 scrollCache.state = ScrollabilityCache.ON; 11001 11002 // Schedule our fader to run, unscheduling any old ones first 11003 if (mAttachInfo != null) { 11004 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11005 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11006 } 11007 11008 return true; 11009 } 11010 11011 return false; 11012 } 11013 11014 /** 11015 * Do not invalidate views which are not visible and which are not running an animation. They 11016 * will not get drawn and they should not set dirty flags as if they will be drawn 11017 */ 11018 private boolean skipInvalidate() { 11019 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11020 (!(mParent instanceof ViewGroup) || 11021 !((ViewGroup) mParent).isViewTransitioning(this)); 11022 } 11023 11024 /** 11025 * Mark the area defined by dirty as needing to be drawn. If the view is 11026 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11027 * point in the future. 11028 * <p> 11029 * This must be called from a UI thread. To call from a non-UI thread, call 11030 * {@link #postInvalidate()}. 11031 * <p> 11032 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11033 * {@code dirty}. 11034 * 11035 * @param dirty the rectangle representing the bounds of the dirty region 11036 */ 11037 public void invalidate(Rect dirty) { 11038 final int scrollX = mScrollX; 11039 final int scrollY = mScrollY; 11040 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11041 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11042 } 11043 11044 /** 11045 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11046 * coordinates of the dirty rect are relative to the view. If the view is 11047 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11048 * point in the future. 11049 * <p> 11050 * This must be called from a UI thread. To call from a non-UI thread, call 11051 * {@link #postInvalidate()}. 11052 * 11053 * @param l the left position of the dirty region 11054 * @param t the top position of the dirty region 11055 * @param r the right position of the dirty region 11056 * @param b the bottom position of the dirty region 11057 */ 11058 public void invalidate(int l, int t, int r, int b) { 11059 final int scrollX = mScrollX; 11060 final int scrollY = mScrollY; 11061 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11062 } 11063 11064 /** 11065 * Invalidate the whole view. If the view is visible, 11066 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11067 * the future. 11068 * <p> 11069 * This must be called from a UI thread. To call from a non-UI thread, call 11070 * {@link #postInvalidate()}. 11071 */ 11072 public void invalidate() { 11073 invalidate(true); 11074 } 11075 11076 /** 11077 * This is where the invalidate() work actually happens. A full invalidate() 11078 * causes the drawing cache to be invalidated, but this function can be 11079 * called with invalidateCache set to false to skip that invalidation step 11080 * for cases that do not need it (for example, a component that remains at 11081 * the same dimensions with the same content). 11082 * 11083 * @param invalidateCache Whether the drawing cache for this view should be 11084 * invalidated as well. This is usually true for a full 11085 * invalidate, but may be set to false if the View's contents or 11086 * dimensions have not changed. 11087 */ 11088 void invalidate(boolean invalidateCache) { 11089 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11090 } 11091 11092 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11093 boolean fullInvalidate) { 11094 if (skipInvalidate()) { 11095 return; 11096 } 11097 11098 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11099 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11100 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11101 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11102 if (fullInvalidate) { 11103 mLastIsOpaque = isOpaque(); 11104 mPrivateFlags &= ~PFLAG_DRAWN; 11105 } 11106 11107 mPrivateFlags |= PFLAG_DIRTY; 11108 11109 if (invalidateCache) { 11110 mPrivateFlags |= PFLAG_INVALIDATED; 11111 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11112 } 11113 11114 // Propagate the damage rectangle to the parent view. 11115 final AttachInfo ai = mAttachInfo; 11116 final ViewParent p = mParent; 11117 if (p != null && ai != null && l < r && t < b) { 11118 final Rect damage = ai.mTmpInvalRect; 11119 damage.set(l, t, r, b); 11120 p.invalidateChild(this, damage); 11121 } 11122 11123 // Damage the entire projection receiver, if necessary. 11124 if (mBackground != null && mBackground.isProjected()) { 11125 final View receiver = getProjectionReceiver(); 11126 if (receiver != null) { 11127 receiver.damageInParent(); 11128 } 11129 } 11130 11131 // Damage the entire IsolatedZVolume recieving this view's shadow. 11132 if (isHardwareAccelerated() && getTranslationZ() != 0) { 11133 damageShadowReceiver(); 11134 } 11135 } 11136 } 11137 11138 /** 11139 * @return this view's projection receiver, or {@code null} if none exists 11140 */ 11141 private View getProjectionReceiver() { 11142 ViewParent p = getParent(); 11143 while (p != null && p instanceof View) { 11144 final View v = (View) p; 11145 if (v.isProjectionReceiver()) { 11146 return v; 11147 } 11148 p = p.getParent(); 11149 } 11150 11151 return null; 11152 } 11153 11154 /** 11155 * @return whether the view is a projection receiver 11156 */ 11157 private boolean isProjectionReceiver() { 11158 return mBackground != null; 11159 } 11160 11161 /** 11162 * Damage area of the screen that can be covered by this View's shadow. 11163 * 11164 * This method will guarantee that any changes to shadows cast by a View 11165 * are damaged on the screen for future redraw. 11166 */ 11167 private void damageShadowReceiver() { 11168 final AttachInfo ai = mAttachInfo; 11169 if (ai != null) { 11170 ViewParent p = getParent(); 11171 if (p != null && p instanceof ViewGroup) { 11172 final ViewGroup vg = (ViewGroup) p; 11173 vg.damageInParent(); 11174 } 11175 } 11176 } 11177 11178 /** 11179 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11180 * set any flags or handle all of the cases handled by the default invalidation methods. 11181 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11182 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11183 * walk up the hierarchy, transforming the dirty rect as necessary. 11184 * 11185 * The method also handles normal invalidation logic if display list properties are not 11186 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11187 * backup approach, to handle these cases used in the various property-setting methods. 11188 * 11189 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11190 * are not being used in this view 11191 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11192 * list properties are not being used in this view 11193 */ 11194 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11195 if (!isHardwareAccelerated() 11196 || !mRenderNode.isValid() 11197 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11198 if (invalidateParent) { 11199 invalidateParentCaches(); 11200 } 11201 if (forceRedraw) { 11202 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11203 } 11204 invalidate(false); 11205 } else { 11206 damageInParent(); 11207 } 11208 if (isHardwareAccelerated() && invalidateParent && getTranslationZ() != 0) { 11209 damageShadowReceiver(); 11210 } 11211 } 11212 11213 /** 11214 * Tells the parent view to damage this view's bounds. 11215 * 11216 * @hide 11217 */ 11218 protected void damageInParent() { 11219 final AttachInfo ai = mAttachInfo; 11220 final ViewParent p = mParent; 11221 if (p != null && ai != null) { 11222 final Rect r = ai.mTmpInvalRect; 11223 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11224 if (mParent instanceof ViewGroup) { 11225 ((ViewGroup) mParent).damageChild(this, r); 11226 } else { 11227 mParent.invalidateChild(this, r); 11228 } 11229 } 11230 } 11231 11232 /** 11233 * Utility method to transform a given Rect by the current matrix of this view. 11234 */ 11235 void transformRect(final Rect rect) { 11236 if (!getMatrix().isIdentity()) { 11237 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11238 boundingRect.set(rect); 11239 getMatrix().mapRect(boundingRect); 11240 rect.set((int) Math.floor(boundingRect.left), 11241 (int) Math.floor(boundingRect.top), 11242 (int) Math.ceil(boundingRect.right), 11243 (int) Math.ceil(boundingRect.bottom)); 11244 } 11245 } 11246 11247 /** 11248 * Used to indicate that the parent of this view should clear its caches. This functionality 11249 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11250 * which is necessary when various parent-managed properties of the view change, such as 11251 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11252 * clears the parent caches and does not causes an invalidate event. 11253 * 11254 * @hide 11255 */ 11256 protected void invalidateParentCaches() { 11257 if (mParent instanceof View) { 11258 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11259 } 11260 } 11261 11262 /** 11263 * Used to indicate that the parent of this view should be invalidated. This functionality 11264 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11265 * which is necessary when various parent-managed properties of the view change, such as 11266 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11267 * an invalidation event to the parent. 11268 * 11269 * @hide 11270 */ 11271 protected void invalidateParentIfNeeded() { 11272 if (isHardwareAccelerated() && mParent instanceof View) { 11273 ((View) mParent).invalidate(true); 11274 } 11275 } 11276 11277 /** 11278 * @hide 11279 */ 11280 protected void invalidateParentIfNeededAndWasQuickRejected() { 11281 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11282 // View was rejected last time it was drawn by its parent; this may have changed 11283 invalidateParentIfNeeded(); 11284 } 11285 } 11286 11287 /** 11288 * Indicates whether this View is opaque. An opaque View guarantees that it will 11289 * draw all the pixels overlapping its bounds using a fully opaque color. 11290 * 11291 * Subclasses of View should override this method whenever possible to indicate 11292 * whether an instance is opaque. Opaque Views are treated in a special way by 11293 * the View hierarchy, possibly allowing it to perform optimizations during 11294 * invalidate/draw passes. 11295 * 11296 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11297 */ 11298 @ViewDebug.ExportedProperty(category = "drawing") 11299 public boolean isOpaque() { 11300 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11301 getFinalAlpha() >= 1.0f; 11302 } 11303 11304 /** 11305 * @hide 11306 */ 11307 protected void computeOpaqueFlags() { 11308 // Opaque if: 11309 // - Has a background 11310 // - Background is opaque 11311 // - Doesn't have scrollbars or scrollbars overlay 11312 11313 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11314 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11315 } else { 11316 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11317 } 11318 11319 final int flags = mViewFlags; 11320 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11321 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11322 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11323 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11324 } else { 11325 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11326 } 11327 } 11328 11329 /** 11330 * @hide 11331 */ 11332 protected boolean hasOpaqueScrollbars() { 11333 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11334 } 11335 11336 /** 11337 * @return A handler associated with the thread running the View. This 11338 * handler can be used to pump events in the UI events queue. 11339 */ 11340 public Handler getHandler() { 11341 final AttachInfo attachInfo = mAttachInfo; 11342 if (attachInfo != null) { 11343 return attachInfo.mHandler; 11344 } 11345 return null; 11346 } 11347 11348 /** 11349 * Gets the view root associated with the View. 11350 * @return The view root, or null if none. 11351 * @hide 11352 */ 11353 public ViewRootImpl getViewRootImpl() { 11354 if (mAttachInfo != null) { 11355 return mAttachInfo.mViewRootImpl; 11356 } 11357 return null; 11358 } 11359 11360 /** 11361 * @hide 11362 */ 11363 public HardwareRenderer getHardwareRenderer() { 11364 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11365 } 11366 11367 /** 11368 * <p>Causes the Runnable to be added to the message queue. 11369 * The runnable will be run on the user interface thread.</p> 11370 * 11371 * @param action The Runnable that will be executed. 11372 * 11373 * @return Returns true if the Runnable was successfully placed in to the 11374 * message queue. Returns false on failure, usually because the 11375 * looper processing the message queue is exiting. 11376 * 11377 * @see #postDelayed 11378 * @see #removeCallbacks 11379 */ 11380 public boolean post(Runnable action) { 11381 final AttachInfo attachInfo = mAttachInfo; 11382 if (attachInfo != null) { 11383 return attachInfo.mHandler.post(action); 11384 } 11385 // Assume that post will succeed later 11386 ViewRootImpl.getRunQueue().post(action); 11387 return true; 11388 } 11389 11390 /** 11391 * <p>Causes the Runnable to be added to the message queue, to be run 11392 * after the specified amount of time elapses. 11393 * The runnable will be run on the user interface thread.</p> 11394 * 11395 * @param action The Runnable that will be executed. 11396 * @param delayMillis The delay (in milliseconds) until the Runnable 11397 * will be executed. 11398 * 11399 * @return true if the Runnable was successfully placed in to the 11400 * message queue. Returns false on failure, usually because the 11401 * looper processing the message queue is exiting. Note that a 11402 * result of true does not mean the Runnable will be processed -- 11403 * if the looper is quit before the delivery time of the message 11404 * occurs then the message will be dropped. 11405 * 11406 * @see #post 11407 * @see #removeCallbacks 11408 */ 11409 public boolean postDelayed(Runnable action, long delayMillis) { 11410 final AttachInfo attachInfo = mAttachInfo; 11411 if (attachInfo != null) { 11412 return attachInfo.mHandler.postDelayed(action, delayMillis); 11413 } 11414 // Assume that post will succeed later 11415 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11416 return true; 11417 } 11418 11419 /** 11420 * <p>Causes the Runnable to execute on the next animation time step. 11421 * The runnable will be run on the user interface thread.</p> 11422 * 11423 * @param action The Runnable that will be executed. 11424 * 11425 * @see #postOnAnimationDelayed 11426 * @see #removeCallbacks 11427 */ 11428 public void postOnAnimation(Runnable action) { 11429 final AttachInfo attachInfo = mAttachInfo; 11430 if (attachInfo != null) { 11431 attachInfo.mViewRootImpl.mChoreographer.postCallback( 11432 Choreographer.CALLBACK_ANIMATION, action, null); 11433 } else { 11434 // Assume that post will succeed later 11435 ViewRootImpl.getRunQueue().post(action); 11436 } 11437 } 11438 11439 /** 11440 * <p>Causes the Runnable to execute on the next animation time step, 11441 * after the specified amount of time elapses. 11442 * The runnable will be run on the user interface thread.</p> 11443 * 11444 * @param action The Runnable that will be executed. 11445 * @param delayMillis The delay (in milliseconds) until the Runnable 11446 * will be executed. 11447 * 11448 * @see #postOnAnimation 11449 * @see #removeCallbacks 11450 */ 11451 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 11452 final AttachInfo attachInfo = mAttachInfo; 11453 if (attachInfo != null) { 11454 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 11455 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 11456 } else { 11457 // Assume that post will succeed later 11458 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11459 } 11460 } 11461 11462 /** 11463 * <p>Removes the specified Runnable from the message queue.</p> 11464 * 11465 * @param action The Runnable to remove from the message handling queue 11466 * 11467 * @return true if this view could ask the Handler to remove the Runnable, 11468 * false otherwise. When the returned value is true, the Runnable 11469 * may or may not have been actually removed from the message queue 11470 * (for instance, if the Runnable was not in the queue already.) 11471 * 11472 * @see #post 11473 * @see #postDelayed 11474 * @see #postOnAnimation 11475 * @see #postOnAnimationDelayed 11476 */ 11477 public boolean removeCallbacks(Runnable action) { 11478 if (action != null) { 11479 final AttachInfo attachInfo = mAttachInfo; 11480 if (attachInfo != null) { 11481 attachInfo.mHandler.removeCallbacks(action); 11482 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 11483 Choreographer.CALLBACK_ANIMATION, action, null); 11484 } 11485 // Assume that post will succeed later 11486 ViewRootImpl.getRunQueue().removeCallbacks(action); 11487 } 11488 return true; 11489 } 11490 11491 /** 11492 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 11493 * Use this to invalidate the View from a non-UI thread.</p> 11494 * 11495 * <p>This method can be invoked from outside of the UI thread 11496 * only when this View is attached to a window.</p> 11497 * 11498 * @see #invalidate() 11499 * @see #postInvalidateDelayed(long) 11500 */ 11501 public void postInvalidate() { 11502 postInvalidateDelayed(0); 11503 } 11504 11505 /** 11506 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11507 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 11508 * 11509 * <p>This method can be invoked from outside of the UI thread 11510 * only when this View is attached to a window.</p> 11511 * 11512 * @param left The left coordinate of the rectangle to invalidate. 11513 * @param top The top coordinate of the rectangle to invalidate. 11514 * @param right The right coordinate of the rectangle to invalidate. 11515 * @param bottom The bottom coordinate of the rectangle to invalidate. 11516 * 11517 * @see #invalidate(int, int, int, int) 11518 * @see #invalidate(Rect) 11519 * @see #postInvalidateDelayed(long, int, int, int, int) 11520 */ 11521 public void postInvalidate(int left, int top, int right, int bottom) { 11522 postInvalidateDelayed(0, left, top, right, bottom); 11523 } 11524 11525 /** 11526 * <p>Cause an invalidate to happen on a subsequent cycle through the event 11527 * loop. Waits for the specified amount of time.</p> 11528 * 11529 * <p>This method can be invoked from outside of the UI thread 11530 * only when this View is attached to a window.</p> 11531 * 11532 * @param delayMilliseconds the duration in milliseconds to delay the 11533 * invalidation by 11534 * 11535 * @see #invalidate() 11536 * @see #postInvalidate() 11537 */ 11538 public void postInvalidateDelayed(long delayMilliseconds) { 11539 // We try only with the AttachInfo because there's no point in invalidating 11540 // if we are not attached to our window 11541 final AttachInfo attachInfo = mAttachInfo; 11542 if (attachInfo != null) { 11543 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 11544 } 11545 } 11546 11547 /** 11548 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 11549 * through the event loop. Waits for the specified amount of time.</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 * @param delayMilliseconds the duration in milliseconds to delay the 11555 * invalidation by 11556 * @param left The left coordinate of the rectangle to invalidate. 11557 * @param top The top coordinate of the rectangle to invalidate. 11558 * @param right The right coordinate of the rectangle to invalidate. 11559 * @param bottom The bottom coordinate of the rectangle to invalidate. 11560 * 11561 * @see #invalidate(int, int, int, int) 11562 * @see #invalidate(Rect) 11563 * @see #postInvalidate(int, int, int, int) 11564 */ 11565 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 11566 int right, int bottom) { 11567 11568 // We try only with the AttachInfo because there's no point in invalidating 11569 // if we are not attached to our window 11570 final AttachInfo attachInfo = mAttachInfo; 11571 if (attachInfo != null) { 11572 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11573 info.target = this; 11574 info.left = left; 11575 info.top = top; 11576 info.right = right; 11577 info.bottom = bottom; 11578 11579 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 11580 } 11581 } 11582 11583 /** 11584 * <p>Cause an invalidate to happen on the next animation time step, typically the 11585 * next display frame.</p> 11586 * 11587 * <p>This method can be invoked from outside of the UI thread 11588 * only when this View is attached to a window.</p> 11589 * 11590 * @see #invalidate() 11591 */ 11592 public void postInvalidateOnAnimation() { 11593 // We try only with the AttachInfo because there's no point in invalidating 11594 // if we are not attached to our window 11595 final AttachInfo attachInfo = mAttachInfo; 11596 if (attachInfo != null) { 11597 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 11598 } 11599 } 11600 11601 /** 11602 * <p>Cause an invalidate of the specified area to happen on the next animation 11603 * time step, typically the next display frame.</p> 11604 * 11605 * <p>This method can be invoked from outside of the UI thread 11606 * only when this View is attached to a window.</p> 11607 * 11608 * @param left The left coordinate of the rectangle to invalidate. 11609 * @param top The top coordinate of the rectangle to invalidate. 11610 * @param right The right coordinate of the rectangle to invalidate. 11611 * @param bottom The bottom coordinate of the rectangle to invalidate. 11612 * 11613 * @see #invalidate(int, int, int, int) 11614 * @see #invalidate(Rect) 11615 */ 11616 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 11617 // We try only with the AttachInfo because there's no point in invalidating 11618 // if we are not attached to our window 11619 final AttachInfo attachInfo = mAttachInfo; 11620 if (attachInfo != null) { 11621 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 11622 info.target = this; 11623 info.left = left; 11624 info.top = top; 11625 info.right = right; 11626 info.bottom = bottom; 11627 11628 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 11629 } 11630 } 11631 11632 /** 11633 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 11634 * This event is sent at most once every 11635 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 11636 */ 11637 private void postSendViewScrolledAccessibilityEventCallback() { 11638 if (mSendViewScrolledAccessibilityEvent == null) { 11639 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 11640 } 11641 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 11642 mSendViewScrolledAccessibilityEvent.mIsPending = true; 11643 postDelayed(mSendViewScrolledAccessibilityEvent, 11644 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 11645 } 11646 } 11647 11648 /** 11649 * Called by a parent to request that a child update its values for mScrollX 11650 * and mScrollY if necessary. This will typically be done if the child is 11651 * animating a scroll using a {@link android.widget.Scroller Scroller} 11652 * object. 11653 */ 11654 public void computeScroll() { 11655 } 11656 11657 /** 11658 * <p>Indicate whether the horizontal edges are faded when the view is 11659 * scrolled horizontally.</p> 11660 * 11661 * @return true if the horizontal edges should are faded on scroll, false 11662 * otherwise 11663 * 11664 * @see #setHorizontalFadingEdgeEnabled(boolean) 11665 * 11666 * @attr ref android.R.styleable#View_requiresFadingEdge 11667 */ 11668 public boolean isHorizontalFadingEdgeEnabled() { 11669 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 11670 } 11671 11672 /** 11673 * <p>Define whether the horizontal edges should be faded when this view 11674 * is scrolled horizontally.</p> 11675 * 11676 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 11677 * be faded when the view is scrolled 11678 * horizontally 11679 * 11680 * @see #isHorizontalFadingEdgeEnabled() 11681 * 11682 * @attr ref android.R.styleable#View_requiresFadingEdge 11683 */ 11684 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 11685 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 11686 if (horizontalFadingEdgeEnabled) { 11687 initScrollCache(); 11688 } 11689 11690 mViewFlags ^= FADING_EDGE_HORIZONTAL; 11691 } 11692 } 11693 11694 /** 11695 * <p>Indicate whether the vertical edges are faded when the view is 11696 * scrolled horizontally.</p> 11697 * 11698 * @return true if the vertical edges should are faded on scroll, false 11699 * otherwise 11700 * 11701 * @see #setVerticalFadingEdgeEnabled(boolean) 11702 * 11703 * @attr ref android.R.styleable#View_requiresFadingEdge 11704 */ 11705 public boolean isVerticalFadingEdgeEnabled() { 11706 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 11707 } 11708 11709 /** 11710 * <p>Define whether the vertical edges should be faded when this view 11711 * is scrolled vertically.</p> 11712 * 11713 * @param verticalFadingEdgeEnabled true if the vertical edges should 11714 * be faded when the view is scrolled 11715 * vertically 11716 * 11717 * @see #isVerticalFadingEdgeEnabled() 11718 * 11719 * @attr ref android.R.styleable#View_requiresFadingEdge 11720 */ 11721 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 11722 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 11723 if (verticalFadingEdgeEnabled) { 11724 initScrollCache(); 11725 } 11726 11727 mViewFlags ^= FADING_EDGE_VERTICAL; 11728 } 11729 } 11730 11731 /** 11732 * Returns the strength, or intensity, of the top faded edge. The strength is 11733 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11734 * returns 0.0 or 1.0 but no value in between. 11735 * 11736 * Subclasses should override this method to provide a smoother fade transition 11737 * when scrolling occurs. 11738 * 11739 * @return the intensity of the top fade as a float between 0.0f and 1.0f 11740 */ 11741 protected float getTopFadingEdgeStrength() { 11742 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 11743 } 11744 11745 /** 11746 * Returns the strength, or intensity, of the bottom faded edge. The strength is 11747 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11748 * returns 0.0 or 1.0 but no value in between. 11749 * 11750 * Subclasses should override this method to provide a smoother fade transition 11751 * when scrolling occurs. 11752 * 11753 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 11754 */ 11755 protected float getBottomFadingEdgeStrength() { 11756 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 11757 computeVerticalScrollRange() ? 1.0f : 0.0f; 11758 } 11759 11760 /** 11761 * Returns the strength, or intensity, of the left faded edge. The strength is 11762 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11763 * returns 0.0 or 1.0 but no value in between. 11764 * 11765 * Subclasses should override this method to provide a smoother fade transition 11766 * when scrolling occurs. 11767 * 11768 * @return the intensity of the left fade as a float between 0.0f and 1.0f 11769 */ 11770 protected float getLeftFadingEdgeStrength() { 11771 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 11772 } 11773 11774 /** 11775 * Returns the strength, or intensity, of the right faded edge. The strength is 11776 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 11777 * returns 0.0 or 1.0 but no value in between. 11778 * 11779 * Subclasses should override this method to provide a smoother fade transition 11780 * when scrolling occurs. 11781 * 11782 * @return the intensity of the right fade as a float between 0.0f and 1.0f 11783 */ 11784 protected float getRightFadingEdgeStrength() { 11785 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 11786 computeHorizontalScrollRange() ? 1.0f : 0.0f; 11787 } 11788 11789 /** 11790 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 11791 * scrollbar is not drawn by default.</p> 11792 * 11793 * @return true if the horizontal scrollbar should be painted, false 11794 * otherwise 11795 * 11796 * @see #setHorizontalScrollBarEnabled(boolean) 11797 */ 11798 public boolean isHorizontalScrollBarEnabled() { 11799 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 11800 } 11801 11802 /** 11803 * <p>Define whether the horizontal scrollbar should be drawn or not. The 11804 * scrollbar is not drawn by default.</p> 11805 * 11806 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 11807 * be painted 11808 * 11809 * @see #isHorizontalScrollBarEnabled() 11810 */ 11811 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 11812 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 11813 mViewFlags ^= SCROLLBARS_HORIZONTAL; 11814 computeOpaqueFlags(); 11815 resolvePadding(); 11816 } 11817 } 11818 11819 /** 11820 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 11821 * scrollbar is not drawn by default.</p> 11822 * 11823 * @return true if the vertical scrollbar should be painted, false 11824 * otherwise 11825 * 11826 * @see #setVerticalScrollBarEnabled(boolean) 11827 */ 11828 public boolean isVerticalScrollBarEnabled() { 11829 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 11830 } 11831 11832 /** 11833 * <p>Define whether the vertical scrollbar should be drawn or not. The 11834 * scrollbar is not drawn by default.</p> 11835 * 11836 * @param verticalScrollBarEnabled true if the vertical scrollbar should 11837 * be painted 11838 * 11839 * @see #isVerticalScrollBarEnabled() 11840 */ 11841 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 11842 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 11843 mViewFlags ^= SCROLLBARS_VERTICAL; 11844 computeOpaqueFlags(); 11845 resolvePadding(); 11846 } 11847 } 11848 11849 /** 11850 * @hide 11851 */ 11852 protected void recomputePadding() { 11853 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 11854 } 11855 11856 /** 11857 * Define whether scrollbars will fade when the view is not scrolling. 11858 * 11859 * @param fadeScrollbars wheter to enable fading 11860 * 11861 * @attr ref android.R.styleable#View_fadeScrollbars 11862 */ 11863 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 11864 initScrollCache(); 11865 final ScrollabilityCache scrollabilityCache = mScrollCache; 11866 scrollabilityCache.fadeScrollBars = fadeScrollbars; 11867 if (fadeScrollbars) { 11868 scrollabilityCache.state = ScrollabilityCache.OFF; 11869 } else { 11870 scrollabilityCache.state = ScrollabilityCache.ON; 11871 } 11872 } 11873 11874 /** 11875 * 11876 * Returns true if scrollbars will fade when this view is not scrolling 11877 * 11878 * @return true if scrollbar fading is enabled 11879 * 11880 * @attr ref android.R.styleable#View_fadeScrollbars 11881 */ 11882 public boolean isScrollbarFadingEnabled() { 11883 return mScrollCache != null && mScrollCache.fadeScrollBars; 11884 } 11885 11886 /** 11887 * 11888 * Returns the delay before scrollbars fade. 11889 * 11890 * @return the delay before scrollbars fade 11891 * 11892 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11893 */ 11894 public int getScrollBarDefaultDelayBeforeFade() { 11895 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 11896 mScrollCache.scrollBarDefaultDelayBeforeFade; 11897 } 11898 11899 /** 11900 * Define the delay before scrollbars fade. 11901 * 11902 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 11903 * 11904 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 11905 */ 11906 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 11907 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 11908 } 11909 11910 /** 11911 * 11912 * Returns the scrollbar fade duration. 11913 * 11914 * @return the scrollbar fade duration 11915 * 11916 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11917 */ 11918 public int getScrollBarFadeDuration() { 11919 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 11920 mScrollCache.scrollBarFadeDuration; 11921 } 11922 11923 /** 11924 * Define the scrollbar fade duration. 11925 * 11926 * @param scrollBarFadeDuration - the scrollbar fade duration 11927 * 11928 * @attr ref android.R.styleable#View_scrollbarFadeDuration 11929 */ 11930 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 11931 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 11932 } 11933 11934 /** 11935 * 11936 * Returns the scrollbar size. 11937 * 11938 * @return the scrollbar size 11939 * 11940 * @attr ref android.R.styleable#View_scrollbarSize 11941 */ 11942 public int getScrollBarSize() { 11943 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 11944 mScrollCache.scrollBarSize; 11945 } 11946 11947 /** 11948 * Define the scrollbar size. 11949 * 11950 * @param scrollBarSize - the scrollbar size 11951 * 11952 * @attr ref android.R.styleable#View_scrollbarSize 11953 */ 11954 public void setScrollBarSize(int scrollBarSize) { 11955 getScrollCache().scrollBarSize = scrollBarSize; 11956 } 11957 11958 /** 11959 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 11960 * inset. When inset, they add to the padding of the view. And the scrollbars 11961 * can be drawn inside the padding area or on the edge of the view. For example, 11962 * if a view has a background drawable and you want to draw the scrollbars 11963 * inside the padding specified by the drawable, you can use 11964 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 11965 * appear at the edge of the view, ignoring the padding, then you can use 11966 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 11967 * @param style the style of the scrollbars. Should be one of 11968 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 11969 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 11970 * @see #SCROLLBARS_INSIDE_OVERLAY 11971 * @see #SCROLLBARS_INSIDE_INSET 11972 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11973 * @see #SCROLLBARS_OUTSIDE_INSET 11974 * 11975 * @attr ref android.R.styleable#View_scrollbarStyle 11976 */ 11977 public void setScrollBarStyle(@ScrollBarStyle int style) { 11978 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 11979 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 11980 computeOpaqueFlags(); 11981 resolvePadding(); 11982 } 11983 } 11984 11985 /** 11986 * <p>Returns the current scrollbar style.</p> 11987 * @return the current scrollbar style 11988 * @see #SCROLLBARS_INSIDE_OVERLAY 11989 * @see #SCROLLBARS_INSIDE_INSET 11990 * @see #SCROLLBARS_OUTSIDE_OVERLAY 11991 * @see #SCROLLBARS_OUTSIDE_INSET 11992 * 11993 * @attr ref android.R.styleable#View_scrollbarStyle 11994 */ 11995 @ViewDebug.ExportedProperty(mapping = { 11996 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 11997 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 11998 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 11999 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12000 }) 12001 @ScrollBarStyle 12002 public int getScrollBarStyle() { 12003 return mViewFlags & SCROLLBARS_STYLE_MASK; 12004 } 12005 12006 /** 12007 * <p>Compute the horizontal range that the horizontal scrollbar 12008 * represents.</p> 12009 * 12010 * <p>The range is expressed in arbitrary units that must be the same as the 12011 * units used by {@link #computeHorizontalScrollExtent()} and 12012 * {@link #computeHorizontalScrollOffset()}.</p> 12013 * 12014 * <p>The default range is the drawing width of this view.</p> 12015 * 12016 * @return the total horizontal range represented by the horizontal 12017 * scrollbar 12018 * 12019 * @see #computeHorizontalScrollExtent() 12020 * @see #computeHorizontalScrollOffset() 12021 * @see android.widget.ScrollBarDrawable 12022 */ 12023 protected int computeHorizontalScrollRange() { 12024 return getWidth(); 12025 } 12026 12027 /** 12028 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12029 * within the horizontal range. This value is used to compute the position 12030 * of the thumb within the scrollbar's track.</p> 12031 * 12032 * <p>The range is expressed in arbitrary units that must be the same as the 12033 * units used by {@link #computeHorizontalScrollRange()} and 12034 * {@link #computeHorizontalScrollExtent()}.</p> 12035 * 12036 * <p>The default offset is the scroll offset of this view.</p> 12037 * 12038 * @return the horizontal offset of the scrollbar's thumb 12039 * 12040 * @see #computeHorizontalScrollRange() 12041 * @see #computeHorizontalScrollExtent() 12042 * @see android.widget.ScrollBarDrawable 12043 */ 12044 protected int computeHorizontalScrollOffset() { 12045 return mScrollX; 12046 } 12047 12048 /** 12049 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12050 * within the horizontal range. This value is used to compute the length 12051 * of the thumb within the scrollbar's track.</p> 12052 * 12053 * <p>The range is expressed in arbitrary units that must be the same as the 12054 * units used by {@link #computeHorizontalScrollRange()} and 12055 * {@link #computeHorizontalScrollOffset()}.</p> 12056 * 12057 * <p>The default extent is the drawing width of this view.</p> 12058 * 12059 * @return the horizontal extent of the scrollbar's thumb 12060 * 12061 * @see #computeHorizontalScrollRange() 12062 * @see #computeHorizontalScrollOffset() 12063 * @see android.widget.ScrollBarDrawable 12064 */ 12065 protected int computeHorizontalScrollExtent() { 12066 return getWidth(); 12067 } 12068 12069 /** 12070 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12071 * 12072 * <p>The range is expressed in arbitrary units that must be the same as the 12073 * units used by {@link #computeVerticalScrollExtent()} and 12074 * {@link #computeVerticalScrollOffset()}.</p> 12075 * 12076 * @return the total vertical range represented by the vertical scrollbar 12077 * 12078 * <p>The default range is the drawing height of this view.</p> 12079 * 12080 * @see #computeVerticalScrollExtent() 12081 * @see #computeVerticalScrollOffset() 12082 * @see android.widget.ScrollBarDrawable 12083 */ 12084 protected int computeVerticalScrollRange() { 12085 return getHeight(); 12086 } 12087 12088 /** 12089 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12090 * within the horizontal range. This value is used to compute the position 12091 * of the thumb within the scrollbar's track.</p> 12092 * 12093 * <p>The range is expressed in arbitrary units that must be the same as the 12094 * units used by {@link #computeVerticalScrollRange()} and 12095 * {@link #computeVerticalScrollExtent()}.</p> 12096 * 12097 * <p>The default offset is the scroll offset of this view.</p> 12098 * 12099 * @return the vertical offset of the scrollbar's thumb 12100 * 12101 * @see #computeVerticalScrollRange() 12102 * @see #computeVerticalScrollExtent() 12103 * @see android.widget.ScrollBarDrawable 12104 */ 12105 protected int computeVerticalScrollOffset() { 12106 return mScrollY; 12107 } 12108 12109 /** 12110 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12111 * within the vertical range. This value is used to compute the length 12112 * of the thumb within the scrollbar's track.</p> 12113 * 12114 * <p>The range is expressed in arbitrary units that must be the same as the 12115 * units used by {@link #computeVerticalScrollRange()} and 12116 * {@link #computeVerticalScrollOffset()}.</p> 12117 * 12118 * <p>The default extent is the drawing height of this view.</p> 12119 * 12120 * @return the vertical extent of the scrollbar's thumb 12121 * 12122 * @see #computeVerticalScrollRange() 12123 * @see #computeVerticalScrollOffset() 12124 * @see android.widget.ScrollBarDrawable 12125 */ 12126 protected int computeVerticalScrollExtent() { 12127 return getHeight(); 12128 } 12129 12130 /** 12131 * Check if this view can be scrolled horizontally in a certain direction. 12132 * 12133 * @param direction Negative to check scrolling left, positive to check scrolling right. 12134 * @return true if this view can be scrolled in the specified direction, false otherwise. 12135 */ 12136 public boolean canScrollHorizontally(int direction) { 12137 final int offset = computeHorizontalScrollOffset(); 12138 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12139 if (range == 0) return false; 12140 if (direction < 0) { 12141 return offset > 0; 12142 } else { 12143 return offset < range - 1; 12144 } 12145 } 12146 12147 /** 12148 * Check if this view can be scrolled vertically in a certain direction. 12149 * 12150 * @param direction Negative to check scrolling up, positive to check scrolling down. 12151 * @return true if this view can be scrolled in the specified direction, false otherwise. 12152 */ 12153 public boolean canScrollVertically(int direction) { 12154 final int offset = computeVerticalScrollOffset(); 12155 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12156 if (range == 0) return false; 12157 if (direction < 0) { 12158 return offset > 0; 12159 } else { 12160 return offset < range - 1; 12161 } 12162 } 12163 12164 /** 12165 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12166 * scrollbars are painted only if they have been awakened first.</p> 12167 * 12168 * @param canvas the canvas on which to draw the scrollbars 12169 * 12170 * @see #awakenScrollBars(int) 12171 */ 12172 protected final void onDrawScrollBars(Canvas canvas) { 12173 // scrollbars are drawn only when the animation is running 12174 final ScrollabilityCache cache = mScrollCache; 12175 if (cache != null) { 12176 12177 int state = cache.state; 12178 12179 if (state == ScrollabilityCache.OFF) { 12180 return; 12181 } 12182 12183 boolean invalidate = false; 12184 12185 if (state == ScrollabilityCache.FADING) { 12186 // We're fading -- get our fade interpolation 12187 if (cache.interpolatorValues == null) { 12188 cache.interpolatorValues = new float[1]; 12189 } 12190 12191 float[] values = cache.interpolatorValues; 12192 12193 // Stops the animation if we're done 12194 if (cache.scrollBarInterpolator.timeToValues(values) == 12195 Interpolator.Result.FREEZE_END) { 12196 cache.state = ScrollabilityCache.OFF; 12197 } else { 12198 cache.scrollBar.setAlpha(Math.round(values[0])); 12199 } 12200 12201 // This will make the scroll bars inval themselves after 12202 // drawing. We only want this when we're fading so that 12203 // we prevent excessive redraws 12204 invalidate = true; 12205 } else { 12206 // We're just on -- but we may have been fading before so 12207 // reset alpha 12208 cache.scrollBar.setAlpha(255); 12209 } 12210 12211 12212 final int viewFlags = mViewFlags; 12213 12214 final boolean drawHorizontalScrollBar = 12215 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12216 final boolean drawVerticalScrollBar = 12217 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12218 && !isVerticalScrollBarHidden(); 12219 12220 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12221 final int width = mRight - mLeft; 12222 final int height = mBottom - mTop; 12223 12224 final ScrollBarDrawable scrollBar = cache.scrollBar; 12225 12226 final int scrollX = mScrollX; 12227 final int scrollY = mScrollY; 12228 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12229 12230 int left; 12231 int top; 12232 int right; 12233 int bottom; 12234 12235 if (drawHorizontalScrollBar) { 12236 int size = scrollBar.getSize(false); 12237 if (size <= 0) { 12238 size = cache.scrollBarSize; 12239 } 12240 12241 scrollBar.setParameters(computeHorizontalScrollRange(), 12242 computeHorizontalScrollOffset(), 12243 computeHorizontalScrollExtent(), false); 12244 final int verticalScrollBarGap = drawVerticalScrollBar ? 12245 getVerticalScrollbarWidth() : 0; 12246 top = scrollY + height - size - (mUserPaddingBottom & inside); 12247 left = scrollX + (mPaddingLeft & inside); 12248 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12249 bottom = top + size; 12250 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12251 if (invalidate) { 12252 invalidate(left, top, right, bottom); 12253 } 12254 } 12255 12256 if (drawVerticalScrollBar) { 12257 int size = scrollBar.getSize(true); 12258 if (size <= 0) { 12259 size = cache.scrollBarSize; 12260 } 12261 12262 scrollBar.setParameters(computeVerticalScrollRange(), 12263 computeVerticalScrollOffset(), 12264 computeVerticalScrollExtent(), true); 12265 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12266 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12267 verticalScrollbarPosition = isLayoutRtl() ? 12268 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12269 } 12270 switch (verticalScrollbarPosition) { 12271 default: 12272 case SCROLLBAR_POSITION_RIGHT: 12273 left = scrollX + width - size - (mUserPaddingRight & inside); 12274 break; 12275 case SCROLLBAR_POSITION_LEFT: 12276 left = scrollX + (mUserPaddingLeft & inside); 12277 break; 12278 } 12279 top = scrollY + (mPaddingTop & inside); 12280 right = left + size; 12281 bottom = scrollY + height - (mUserPaddingBottom & inside); 12282 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12283 if (invalidate) { 12284 invalidate(left, top, right, bottom); 12285 } 12286 } 12287 } 12288 } 12289 } 12290 12291 /** 12292 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12293 * FastScroller is visible. 12294 * @return whether to temporarily hide the vertical scrollbar 12295 * @hide 12296 */ 12297 protected boolean isVerticalScrollBarHidden() { 12298 return false; 12299 } 12300 12301 /** 12302 * <p>Draw the horizontal scrollbar if 12303 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12304 * 12305 * @param canvas the canvas on which to draw the scrollbar 12306 * @param scrollBar the scrollbar's drawable 12307 * 12308 * @see #isHorizontalScrollBarEnabled() 12309 * @see #computeHorizontalScrollRange() 12310 * @see #computeHorizontalScrollExtent() 12311 * @see #computeHorizontalScrollOffset() 12312 * @see android.widget.ScrollBarDrawable 12313 * @hide 12314 */ 12315 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12316 int l, int t, int r, int b) { 12317 scrollBar.setBounds(l, t, r, b); 12318 scrollBar.draw(canvas); 12319 } 12320 12321 /** 12322 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12323 * returns true.</p> 12324 * 12325 * @param canvas the canvas on which to draw the scrollbar 12326 * @param scrollBar the scrollbar's drawable 12327 * 12328 * @see #isVerticalScrollBarEnabled() 12329 * @see #computeVerticalScrollRange() 12330 * @see #computeVerticalScrollExtent() 12331 * @see #computeVerticalScrollOffset() 12332 * @see android.widget.ScrollBarDrawable 12333 * @hide 12334 */ 12335 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12336 int l, int t, int r, int b) { 12337 scrollBar.setBounds(l, t, r, b); 12338 scrollBar.draw(canvas); 12339 } 12340 12341 /** 12342 * Implement this to do your drawing. 12343 * 12344 * @param canvas the canvas on which the background will be drawn 12345 */ 12346 protected void onDraw(Canvas canvas) { 12347 } 12348 12349 /* 12350 * Caller is responsible for calling requestLayout if necessary. 12351 * (This allows addViewInLayout to not request a new layout.) 12352 */ 12353 void assignParent(ViewParent parent) { 12354 if (mParent == null) { 12355 mParent = parent; 12356 } else if (parent == null) { 12357 mParent = null; 12358 } else { 12359 throw new RuntimeException("view " + this + " being added, but" 12360 + " it already has a parent"); 12361 } 12362 } 12363 12364 /** 12365 * This is called when the view is attached to a window. At this point it 12366 * has a Surface and will start drawing. Note that this function is 12367 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12368 * however it may be called any time before the first onDraw -- including 12369 * before or after {@link #onMeasure(int, int)}. 12370 * 12371 * @see #onDetachedFromWindow() 12372 */ 12373 protected void onAttachedToWindow() { 12374 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12375 mParent.requestTransparentRegion(this); 12376 } 12377 12378 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12379 initialAwakenScrollBars(); 12380 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12381 } 12382 12383 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12384 12385 jumpDrawablesToCurrentState(); 12386 12387 resetSubtreeAccessibilityStateChanged(); 12388 12389 if (isFocused()) { 12390 InputMethodManager imm = InputMethodManager.peekInstance(); 12391 imm.focusIn(this); 12392 } 12393 } 12394 12395 /** 12396 * Resolve all RTL related properties. 12397 * 12398 * @return true if resolution of RTL properties has been done 12399 * 12400 * @hide 12401 */ 12402 public boolean resolveRtlPropertiesIfNeeded() { 12403 if (!needRtlPropertiesResolution()) return false; 12404 12405 // Order is important here: LayoutDirection MUST be resolved first 12406 if (!isLayoutDirectionResolved()) { 12407 resolveLayoutDirection(); 12408 resolveLayoutParams(); 12409 } 12410 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12411 if (!isTextDirectionResolved()) { 12412 resolveTextDirection(); 12413 } 12414 if (!isTextAlignmentResolved()) { 12415 resolveTextAlignment(); 12416 } 12417 // Should resolve Drawables before Padding because we need the layout direction of the 12418 // Drawable to correctly resolve Padding. 12419 if (!isDrawablesResolved()) { 12420 resolveDrawables(); 12421 } 12422 if (!isPaddingResolved()) { 12423 resolvePadding(); 12424 } 12425 onRtlPropertiesChanged(getLayoutDirection()); 12426 return true; 12427 } 12428 12429 /** 12430 * Reset resolution of all RTL related properties. 12431 * 12432 * @hide 12433 */ 12434 public void resetRtlProperties() { 12435 resetResolvedLayoutDirection(); 12436 resetResolvedTextDirection(); 12437 resetResolvedTextAlignment(); 12438 resetResolvedPadding(); 12439 resetResolvedDrawables(); 12440 } 12441 12442 /** 12443 * @see #onScreenStateChanged(int) 12444 */ 12445 void dispatchScreenStateChanged(int screenState) { 12446 onScreenStateChanged(screenState); 12447 } 12448 12449 /** 12450 * This method is called whenever the state of the screen this view is 12451 * attached to changes. A state change will usually occurs when the screen 12452 * turns on or off (whether it happens automatically or the user does it 12453 * manually.) 12454 * 12455 * @param screenState The new state of the screen. Can be either 12456 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 12457 */ 12458 public void onScreenStateChanged(int screenState) { 12459 } 12460 12461 /** 12462 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 12463 */ 12464 private boolean hasRtlSupport() { 12465 return mContext.getApplicationInfo().hasRtlSupport(); 12466 } 12467 12468 /** 12469 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 12470 * RTL not supported) 12471 */ 12472 private boolean isRtlCompatibilityMode() { 12473 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 12474 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 12475 } 12476 12477 /** 12478 * @return true if RTL properties need resolution. 12479 * 12480 */ 12481 private boolean needRtlPropertiesResolution() { 12482 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 12483 } 12484 12485 /** 12486 * Called when any RTL property (layout direction or text direction or text alignment) has 12487 * been changed. 12488 * 12489 * Subclasses need to override this method to take care of cached information that depends on the 12490 * resolved layout direction, or to inform child views that inherit their layout direction. 12491 * 12492 * The default implementation does nothing. 12493 * 12494 * @param layoutDirection the direction of the layout 12495 * 12496 * @see #LAYOUT_DIRECTION_LTR 12497 * @see #LAYOUT_DIRECTION_RTL 12498 */ 12499 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 12500 } 12501 12502 /** 12503 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 12504 * that the parent directionality can and will be resolved before its children. 12505 * 12506 * @return true if resolution has been done, false otherwise. 12507 * 12508 * @hide 12509 */ 12510 public boolean resolveLayoutDirection() { 12511 // Clear any previous layout direction resolution 12512 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12513 12514 if (hasRtlSupport()) { 12515 // Set resolved depending on layout direction 12516 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 12517 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 12518 case LAYOUT_DIRECTION_INHERIT: 12519 // We cannot resolve yet. LTR is by default and let the resolution happen again 12520 // later to get the correct resolved value 12521 if (!canResolveLayoutDirection()) return false; 12522 12523 // Parent has not yet resolved, LTR is still the default 12524 try { 12525 if (!mParent.isLayoutDirectionResolved()) return false; 12526 12527 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 12528 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12529 } 12530 } catch (AbstractMethodError e) { 12531 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12532 " does not fully implement ViewParent", e); 12533 } 12534 break; 12535 case LAYOUT_DIRECTION_RTL: 12536 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12537 break; 12538 case LAYOUT_DIRECTION_LOCALE: 12539 if((LAYOUT_DIRECTION_RTL == 12540 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 12541 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 12542 } 12543 break; 12544 default: 12545 // Nothing to do, LTR by default 12546 } 12547 } 12548 12549 // Set to resolved 12550 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12551 return true; 12552 } 12553 12554 /** 12555 * Check if layout direction resolution can be done. 12556 * 12557 * @return true if layout direction resolution can be done otherwise return false. 12558 */ 12559 public boolean canResolveLayoutDirection() { 12560 switch (getRawLayoutDirection()) { 12561 case LAYOUT_DIRECTION_INHERIT: 12562 if (mParent != null) { 12563 try { 12564 return mParent.canResolveLayoutDirection(); 12565 } catch (AbstractMethodError e) { 12566 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 12567 " does not fully implement ViewParent", e); 12568 } 12569 } 12570 return false; 12571 12572 default: 12573 return true; 12574 } 12575 } 12576 12577 /** 12578 * Reset the resolved layout direction. Layout direction will be resolved during a call to 12579 * {@link #onMeasure(int, int)}. 12580 * 12581 * @hide 12582 */ 12583 public void resetResolvedLayoutDirection() { 12584 // Reset the current resolved bits 12585 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 12586 } 12587 12588 /** 12589 * @return true if the layout direction is inherited. 12590 * 12591 * @hide 12592 */ 12593 public boolean isLayoutDirectionInherited() { 12594 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 12595 } 12596 12597 /** 12598 * @return true if layout direction has been resolved. 12599 */ 12600 public boolean isLayoutDirectionResolved() { 12601 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 12602 } 12603 12604 /** 12605 * Return if padding has been resolved 12606 * 12607 * @hide 12608 */ 12609 boolean isPaddingResolved() { 12610 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 12611 } 12612 12613 /** 12614 * Resolves padding depending on layout direction, if applicable, and 12615 * recomputes internal padding values to adjust for scroll bars. 12616 * 12617 * @hide 12618 */ 12619 public void resolvePadding() { 12620 final int resolvedLayoutDirection = getLayoutDirection(); 12621 12622 if (!isRtlCompatibilityMode()) { 12623 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 12624 // If start / end padding are defined, they will be resolved (hence overriding) to 12625 // left / right or right / left depending on the resolved layout direction. 12626 // If start / end padding are not defined, use the left / right ones. 12627 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 12628 Rect padding = sThreadLocal.get(); 12629 if (padding == null) { 12630 padding = new Rect(); 12631 sThreadLocal.set(padding); 12632 } 12633 mBackground.getPadding(padding); 12634 if (!mLeftPaddingDefined) { 12635 mUserPaddingLeftInitial = padding.left; 12636 } 12637 if (!mRightPaddingDefined) { 12638 mUserPaddingRightInitial = padding.right; 12639 } 12640 } 12641 switch (resolvedLayoutDirection) { 12642 case LAYOUT_DIRECTION_RTL: 12643 if (mUserPaddingStart != UNDEFINED_PADDING) { 12644 mUserPaddingRight = mUserPaddingStart; 12645 } else { 12646 mUserPaddingRight = mUserPaddingRightInitial; 12647 } 12648 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12649 mUserPaddingLeft = mUserPaddingEnd; 12650 } else { 12651 mUserPaddingLeft = mUserPaddingLeftInitial; 12652 } 12653 break; 12654 case LAYOUT_DIRECTION_LTR: 12655 default: 12656 if (mUserPaddingStart != UNDEFINED_PADDING) { 12657 mUserPaddingLeft = mUserPaddingStart; 12658 } else { 12659 mUserPaddingLeft = mUserPaddingLeftInitial; 12660 } 12661 if (mUserPaddingEnd != UNDEFINED_PADDING) { 12662 mUserPaddingRight = mUserPaddingEnd; 12663 } else { 12664 mUserPaddingRight = mUserPaddingRightInitial; 12665 } 12666 } 12667 12668 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 12669 } 12670 12671 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12672 onRtlPropertiesChanged(resolvedLayoutDirection); 12673 12674 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 12675 } 12676 12677 /** 12678 * Reset the resolved layout direction. 12679 * 12680 * @hide 12681 */ 12682 public void resetResolvedPadding() { 12683 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 12684 } 12685 12686 /** 12687 * This is called when the view is detached from a window. At this point it 12688 * no longer has a surface for drawing. 12689 * 12690 * @see #onAttachedToWindow() 12691 */ 12692 protected void onDetachedFromWindow() { 12693 } 12694 12695 /** 12696 * This is a framework-internal mirror of onDetachedFromWindow() that's called 12697 * after onDetachedFromWindow(). 12698 * 12699 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 12700 * The super method should be called at the end of the overriden method to ensure 12701 * subclasses are destroyed first 12702 * 12703 * @hide 12704 */ 12705 protected void onDetachedFromWindowInternal() { 12706 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 12707 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12708 12709 removeUnsetPressCallback(); 12710 removeLongPressCallback(); 12711 removePerformClickCallback(); 12712 removeSendViewScrolledAccessibilityEventCallback(); 12713 12714 destroyDrawingCache(); 12715 destroyLayer(false); 12716 12717 cleanupDraw(); 12718 12719 mCurrentAnimation = null; 12720 } 12721 12722 private void cleanupDraw() { 12723 resetDisplayList(); 12724 if (mAttachInfo != null) { 12725 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 12726 } 12727 } 12728 12729 /** 12730 * This method ensures the hardware renderer is in a valid state 12731 * before executing the specified action. 12732 * 12733 * This method will attempt to set a valid state even if the window 12734 * the renderer is attached to was destroyed. 12735 * 12736 * This method is not guaranteed to work. If the hardware renderer 12737 * does not exist or cannot be put in a valid state, this method 12738 * will not executed the specified action. 12739 * 12740 * The specified action is executed synchronously. 12741 * 12742 * @param action The action to execute after the renderer is in a valid state 12743 * 12744 * @return True if the specified Runnable was executed, false otherwise 12745 * 12746 * @hide 12747 */ 12748 public boolean executeHardwareAction(Runnable action) { 12749 //noinspection SimplifiableIfStatement 12750 if (mAttachInfo != null && mAttachInfo.mHardwareRenderer != null) { 12751 return mAttachInfo.mHardwareRenderer.safelyRun(action); 12752 } 12753 return false; 12754 } 12755 12756 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 12757 } 12758 12759 /** 12760 * @return The number of times this view has been attached to a window 12761 */ 12762 protected int getWindowAttachCount() { 12763 return mWindowAttachCount; 12764 } 12765 12766 /** 12767 * Retrieve a unique token identifying the window this view is attached to. 12768 * @return Return the window's token for use in 12769 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 12770 */ 12771 public IBinder getWindowToken() { 12772 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 12773 } 12774 12775 /** 12776 * Retrieve the {@link WindowId} for the window this view is 12777 * currently attached to. 12778 */ 12779 public WindowId getWindowId() { 12780 if (mAttachInfo == null) { 12781 return null; 12782 } 12783 if (mAttachInfo.mWindowId == null) { 12784 try { 12785 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 12786 mAttachInfo.mWindowToken); 12787 mAttachInfo.mWindowId = new WindowId( 12788 mAttachInfo.mIWindowId); 12789 } catch (RemoteException e) { 12790 } 12791 } 12792 return mAttachInfo.mWindowId; 12793 } 12794 12795 /** 12796 * Retrieve a unique token identifying the top-level "real" window of 12797 * the window that this view is attached to. That is, this is like 12798 * {@link #getWindowToken}, except if the window this view in is a panel 12799 * window (attached to another containing window), then the token of 12800 * the containing window is returned instead. 12801 * 12802 * @return Returns the associated window token, either 12803 * {@link #getWindowToken()} or the containing window's token. 12804 */ 12805 public IBinder getApplicationWindowToken() { 12806 AttachInfo ai = mAttachInfo; 12807 if (ai != null) { 12808 IBinder appWindowToken = ai.mPanelParentWindowToken; 12809 if (appWindowToken == null) { 12810 appWindowToken = ai.mWindowToken; 12811 } 12812 return appWindowToken; 12813 } 12814 return null; 12815 } 12816 12817 /** 12818 * Gets the logical display to which the view's window has been attached. 12819 * 12820 * @return The logical display, or null if the view is not currently attached to a window. 12821 */ 12822 public Display getDisplay() { 12823 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 12824 } 12825 12826 /** 12827 * Retrieve private session object this view hierarchy is using to 12828 * communicate with the window manager. 12829 * @return the session object to communicate with the window manager 12830 */ 12831 /*package*/ IWindowSession getWindowSession() { 12832 return mAttachInfo != null ? mAttachInfo.mSession : null; 12833 } 12834 12835 /** 12836 * @param info the {@link android.view.View.AttachInfo} to associated with 12837 * this view 12838 */ 12839 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 12840 //System.out.println("Attached! " + this); 12841 mAttachInfo = info; 12842 if (mOverlay != null) { 12843 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 12844 } 12845 mWindowAttachCount++; 12846 // We will need to evaluate the drawable state at least once. 12847 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 12848 if (mFloatingTreeObserver != null) { 12849 info.mTreeObserver.merge(mFloatingTreeObserver); 12850 mFloatingTreeObserver = null; 12851 } 12852 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 12853 mAttachInfo.mScrollContainers.add(this); 12854 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 12855 } 12856 performCollectViewAttributes(mAttachInfo, visibility); 12857 onAttachedToWindow(); 12858 12859 ListenerInfo li = mListenerInfo; 12860 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12861 li != null ? li.mOnAttachStateChangeListeners : null; 12862 if (listeners != null && listeners.size() > 0) { 12863 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12864 // perform the dispatching. The iterator is a safe guard against listeners that 12865 // could mutate the list by calling the various add/remove methods. This prevents 12866 // the array from being modified while we iterate it. 12867 for (OnAttachStateChangeListener listener : listeners) { 12868 listener.onViewAttachedToWindow(this); 12869 } 12870 } 12871 12872 int vis = info.mWindowVisibility; 12873 if (vis != GONE) { 12874 onWindowVisibilityChanged(vis); 12875 } 12876 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 12877 // If nobody has evaluated the drawable state yet, then do it now. 12878 refreshDrawableState(); 12879 } 12880 needGlobalAttributesUpdate(false); 12881 } 12882 12883 void dispatchDetachedFromWindow() { 12884 AttachInfo info = mAttachInfo; 12885 if (info != null) { 12886 int vis = info.mWindowVisibility; 12887 if (vis != GONE) { 12888 onWindowVisibilityChanged(GONE); 12889 } 12890 } 12891 12892 onDetachedFromWindow(); 12893 onDetachedFromWindowInternal(); 12894 12895 ListenerInfo li = mListenerInfo; 12896 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 12897 li != null ? li.mOnAttachStateChangeListeners : null; 12898 if (listeners != null && listeners.size() > 0) { 12899 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 12900 // perform the dispatching. The iterator is a safe guard against listeners that 12901 // could mutate the list by calling the various add/remove methods. This prevents 12902 // the array from being modified while we iterate it. 12903 for (OnAttachStateChangeListener listener : listeners) { 12904 listener.onViewDetachedFromWindow(this); 12905 } 12906 } 12907 12908 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 12909 mAttachInfo.mScrollContainers.remove(this); 12910 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 12911 } 12912 12913 mAttachInfo = null; 12914 if (mOverlay != null) { 12915 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 12916 } 12917 } 12918 12919 /** 12920 * Cancel any deferred high-level input events that were previously posted to the event queue. 12921 * 12922 * <p>Many views post high-level events such as click handlers to the event queue 12923 * to run deferred in order to preserve a desired user experience - clearing visible 12924 * pressed states before executing, etc. This method will abort any events of this nature 12925 * that are currently in flight.</p> 12926 * 12927 * <p>Custom views that generate their own high-level deferred input events should override 12928 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 12929 * 12930 * <p>This will also cancel pending input events for any child views.</p> 12931 * 12932 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 12933 * This will not impact newer events posted after this call that may occur as a result of 12934 * lower-level input events still waiting in the queue. If you are trying to prevent 12935 * double-submitted events for the duration of some sort of asynchronous transaction 12936 * you should also take other steps to protect against unexpected double inputs e.g. calling 12937 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 12938 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 12939 */ 12940 public final void cancelPendingInputEvents() { 12941 dispatchCancelPendingInputEvents(); 12942 } 12943 12944 /** 12945 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 12946 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 12947 */ 12948 void dispatchCancelPendingInputEvents() { 12949 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 12950 onCancelPendingInputEvents(); 12951 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 12952 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 12953 " did not call through to super.onCancelPendingInputEvents()"); 12954 } 12955 } 12956 12957 /** 12958 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 12959 * a parent view. 12960 * 12961 * <p>This method is responsible for removing any pending high-level input events that were 12962 * posted to the event queue to run later. Custom view classes that post their own deferred 12963 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 12964 * {@link android.os.Handler} should override this method, call 12965 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 12966 * </p> 12967 */ 12968 public void onCancelPendingInputEvents() { 12969 removePerformClickCallback(); 12970 cancelLongPress(); 12971 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 12972 } 12973 12974 /** 12975 * Store this view hierarchy's frozen state into the given container. 12976 * 12977 * @param container The SparseArray in which to save the view's state. 12978 * 12979 * @see #restoreHierarchyState(android.util.SparseArray) 12980 * @see #dispatchSaveInstanceState(android.util.SparseArray) 12981 * @see #onSaveInstanceState() 12982 */ 12983 public void saveHierarchyState(SparseArray<Parcelable> container) { 12984 dispatchSaveInstanceState(container); 12985 } 12986 12987 /** 12988 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 12989 * this view and its children. May be overridden to modify how freezing happens to a 12990 * view's children; for example, some views may want to not store state for their children. 12991 * 12992 * @param container The SparseArray in which to save the view's state. 12993 * 12994 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 12995 * @see #saveHierarchyState(android.util.SparseArray) 12996 * @see #onSaveInstanceState() 12997 */ 12998 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 12999 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13000 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13001 Parcelable state = onSaveInstanceState(); 13002 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13003 throw new IllegalStateException( 13004 "Derived class did not call super.onSaveInstanceState()"); 13005 } 13006 if (state != null) { 13007 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13008 // + ": " + state); 13009 container.put(mID, state); 13010 } 13011 } 13012 } 13013 13014 /** 13015 * Hook allowing a view to generate a representation of its internal state 13016 * that can later be used to create a new instance with that same state. 13017 * This state should only contain information that is not persistent or can 13018 * not be reconstructed later. For example, you will never store your 13019 * current position on screen because that will be computed again when a 13020 * new instance of the view is placed in its view hierarchy. 13021 * <p> 13022 * Some examples of things you may store here: the current cursor position 13023 * in a text view (but usually not the text itself since that is stored in a 13024 * content provider or other persistent storage), the currently selected 13025 * item in a list view. 13026 * 13027 * @return Returns a Parcelable object containing the view's current dynamic 13028 * state, or null if there is nothing interesting to save. The 13029 * default implementation returns null. 13030 * @see #onRestoreInstanceState(android.os.Parcelable) 13031 * @see #saveHierarchyState(android.util.SparseArray) 13032 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13033 * @see #setSaveEnabled(boolean) 13034 */ 13035 protected Parcelable onSaveInstanceState() { 13036 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13037 return BaseSavedState.EMPTY_STATE; 13038 } 13039 13040 /** 13041 * Restore this view hierarchy's frozen state from the given container. 13042 * 13043 * @param container The SparseArray which holds previously frozen states. 13044 * 13045 * @see #saveHierarchyState(android.util.SparseArray) 13046 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13047 * @see #onRestoreInstanceState(android.os.Parcelable) 13048 */ 13049 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13050 dispatchRestoreInstanceState(container); 13051 } 13052 13053 /** 13054 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13055 * state for this view and its children. May be overridden to modify how restoring 13056 * happens to a view's children; for example, some views may want to not store state 13057 * for their children. 13058 * 13059 * @param container The SparseArray which holds previously saved state. 13060 * 13061 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13062 * @see #restoreHierarchyState(android.util.SparseArray) 13063 * @see #onRestoreInstanceState(android.os.Parcelable) 13064 */ 13065 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13066 if (mID != NO_ID) { 13067 Parcelable state = container.get(mID); 13068 if (state != null) { 13069 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13070 // + ": " + state); 13071 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13072 onRestoreInstanceState(state); 13073 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13074 throw new IllegalStateException( 13075 "Derived class did not call super.onRestoreInstanceState()"); 13076 } 13077 } 13078 } 13079 } 13080 13081 /** 13082 * Hook allowing a view to re-apply a representation of its internal state that had previously 13083 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13084 * null state. 13085 * 13086 * @param state The frozen state that had previously been returned by 13087 * {@link #onSaveInstanceState}. 13088 * 13089 * @see #onSaveInstanceState() 13090 * @see #restoreHierarchyState(android.util.SparseArray) 13091 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13092 */ 13093 protected void onRestoreInstanceState(Parcelable state) { 13094 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13095 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13096 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13097 + "received " + state.getClass().toString() + " instead. This usually happens " 13098 + "when two views of different type have the same id in the same hierarchy. " 13099 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13100 + "other views do not use the same id."); 13101 } 13102 } 13103 13104 /** 13105 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13106 * 13107 * @return the drawing start time in milliseconds 13108 */ 13109 public long getDrawingTime() { 13110 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13111 } 13112 13113 /** 13114 * <p>Enables or disables the duplication of the parent's state into this view. When 13115 * duplication is enabled, this view gets its drawable state from its parent rather 13116 * than from its own internal properties.</p> 13117 * 13118 * <p>Note: in the current implementation, setting this property to true after the 13119 * view was added to a ViewGroup might have no effect at all. This property should 13120 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13121 * 13122 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13123 * property is enabled, an exception will be thrown.</p> 13124 * 13125 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13126 * parent, these states should not be affected by this method.</p> 13127 * 13128 * @param enabled True to enable duplication of the parent's drawable state, false 13129 * to disable it. 13130 * 13131 * @see #getDrawableState() 13132 * @see #isDuplicateParentStateEnabled() 13133 */ 13134 public void setDuplicateParentStateEnabled(boolean enabled) { 13135 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13136 } 13137 13138 /** 13139 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13140 * 13141 * @return True if this view's drawable state is duplicated from the parent, 13142 * false otherwise 13143 * 13144 * @see #getDrawableState() 13145 * @see #setDuplicateParentStateEnabled(boolean) 13146 */ 13147 public boolean isDuplicateParentStateEnabled() { 13148 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13149 } 13150 13151 /** 13152 * <p>Specifies the type of layer backing this view. The layer can be 13153 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13154 * {@link #LAYER_TYPE_HARDWARE}.</p> 13155 * 13156 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13157 * instance that controls how the layer is composed on screen. The following 13158 * properties of the paint are taken into account when composing the layer:</p> 13159 * <ul> 13160 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13161 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13162 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13163 * </ul> 13164 * 13165 * <p>If this view has an alpha value set to < 1.0 by calling 13166 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13167 * by this view's alpha value.</p> 13168 * 13169 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13170 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13171 * for more information on when and how to use layers.</p> 13172 * 13173 * @param layerType The type of layer to use with this view, must be one of 13174 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13175 * {@link #LAYER_TYPE_HARDWARE} 13176 * @param paint The paint used to compose the layer. This argument is optional 13177 * and can be null. It is ignored when the layer type is 13178 * {@link #LAYER_TYPE_NONE} 13179 * 13180 * @see #getLayerType() 13181 * @see #LAYER_TYPE_NONE 13182 * @see #LAYER_TYPE_SOFTWARE 13183 * @see #LAYER_TYPE_HARDWARE 13184 * @see #setAlpha(float) 13185 * 13186 * @attr ref android.R.styleable#View_layerType 13187 */ 13188 public void setLayerType(int layerType, Paint paint) { 13189 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13190 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13191 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13192 } 13193 13194 if (layerType == mLayerType) { 13195 setLayerPaint(paint); 13196 return; 13197 } 13198 13199 // Destroy any previous software drawing cache if needed 13200 switch (mLayerType) { 13201 case LAYER_TYPE_HARDWARE: 13202 destroyLayer(false); 13203 // fall through - non-accelerated views may use software layer mechanism instead 13204 case LAYER_TYPE_SOFTWARE: 13205 destroyDrawingCache(); 13206 break; 13207 default: 13208 break; 13209 } 13210 13211 mLayerType = layerType; 13212 final boolean layerDisabled = mLayerType == LAYER_TYPE_NONE; 13213 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13214 mLocalDirtyRect = layerDisabled ? null : new Rect(); 13215 13216 invalidateParentCaches(); 13217 invalidate(true); 13218 } 13219 13220 /** 13221 * Updates the {@link Paint} object used with the current layer (used only if the current 13222 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13223 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13224 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13225 * ensure that the view gets redrawn immediately. 13226 * 13227 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13228 * instance that controls how the layer is composed on screen. The following 13229 * properties of the paint are taken into account when composing the layer:</p> 13230 * <ul> 13231 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13232 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13233 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13234 * </ul> 13235 * 13236 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13237 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13238 * 13239 * @param paint The paint used to compose the layer. This argument is optional 13240 * and can be null. It is ignored when the layer type is 13241 * {@link #LAYER_TYPE_NONE} 13242 * 13243 * @see #setLayerType(int, android.graphics.Paint) 13244 */ 13245 public void setLayerPaint(Paint paint) { 13246 int layerType = getLayerType(); 13247 if (layerType != LAYER_TYPE_NONE) { 13248 mLayerPaint = paint == null ? new Paint() : paint; 13249 if (layerType == LAYER_TYPE_HARDWARE) { 13250 HardwareLayer layer = getHardwareLayer(); 13251 if (layer != null) { 13252 layer.setLayerPaint(mLayerPaint); 13253 } 13254 invalidateViewProperty(false, false); 13255 } else { 13256 invalidate(); 13257 } 13258 } 13259 } 13260 13261 /** 13262 * Indicates whether this view has a static layer. A view with layer type 13263 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13264 * dynamic. 13265 */ 13266 boolean hasStaticLayer() { 13267 return true; 13268 } 13269 13270 /** 13271 * Indicates what type of layer is currently associated with this view. By default 13272 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13273 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13274 * for more information on the different types of layers. 13275 * 13276 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13277 * {@link #LAYER_TYPE_HARDWARE} 13278 * 13279 * @see #setLayerType(int, android.graphics.Paint) 13280 * @see #buildLayer() 13281 * @see #LAYER_TYPE_NONE 13282 * @see #LAYER_TYPE_SOFTWARE 13283 * @see #LAYER_TYPE_HARDWARE 13284 */ 13285 public int getLayerType() { 13286 return mLayerType; 13287 } 13288 13289 /** 13290 * Forces this view's layer to be created and this view to be rendered 13291 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13292 * invoking this method will have no effect. 13293 * 13294 * This method can for instance be used to render a view into its layer before 13295 * starting an animation. If this view is complex, rendering into the layer 13296 * before starting the animation will avoid skipping frames. 13297 * 13298 * @throws IllegalStateException If this view is not attached to a window 13299 * 13300 * @see #setLayerType(int, android.graphics.Paint) 13301 */ 13302 public void buildLayer() { 13303 if (mLayerType == LAYER_TYPE_NONE) return; 13304 13305 final AttachInfo attachInfo = mAttachInfo; 13306 if (attachInfo == null) { 13307 throw new IllegalStateException("This view must be attached to a window first"); 13308 } 13309 13310 switch (mLayerType) { 13311 case LAYER_TYPE_HARDWARE: 13312 getHardwareLayer(); 13313 // TODO: We need a better way to handle this case 13314 // If views have registered pre-draw listeners they need 13315 // to be notified before we build the layer. Those listeners 13316 // may however rely on other events to happen first so we 13317 // cannot just invoke them here until they don't cancel the 13318 // current frame 13319 if (!attachInfo.mTreeObserver.hasOnPreDrawListeners()) { 13320 attachInfo.mViewRootImpl.dispatchFlushHardwareLayerUpdates(); 13321 } 13322 break; 13323 case LAYER_TYPE_SOFTWARE: 13324 buildDrawingCache(true); 13325 break; 13326 } 13327 } 13328 13329 /** 13330 * <p>Returns a hardware layer that can be used to draw this view again 13331 * without executing its draw method.</p> 13332 * 13333 * @return A HardwareLayer ready to render, or null if an error occurred. 13334 */ 13335 HardwareLayer getHardwareLayer() { 13336 if (mAttachInfo == null || mAttachInfo.mHardwareRenderer == null || 13337 !mAttachInfo.mHardwareRenderer.isEnabled()) { 13338 return null; 13339 } 13340 13341 final int width = mRight - mLeft; 13342 final int height = mBottom - mTop; 13343 13344 if (width == 0 || height == 0) { 13345 return null; 13346 } 13347 13348 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || mHardwareLayer == null) { 13349 if (mHardwareLayer == null) { 13350 mHardwareLayer = mAttachInfo.mHardwareRenderer.createDisplayListLayer( 13351 width, height); 13352 mLocalDirtyRect.set(0, 0, width, height); 13353 } else if (mHardwareLayer.isValid()) { 13354 // This should not be necessary but applications that change 13355 // the parameters of their background drawable without calling 13356 // this.setBackground(Drawable) can leave the view in a bad state 13357 // (for instance isOpaque() returns true, but the background is 13358 // not opaque.) 13359 computeOpaqueFlags(); 13360 13361 if (mHardwareLayer.prepare(width, height, isOpaque())) { 13362 mLocalDirtyRect.set(0, 0, width, height); 13363 } 13364 } 13365 13366 // The layer is not valid if the underlying GPU resources cannot be allocated 13367 mHardwareLayer.flushChanges(); 13368 if (!mHardwareLayer.isValid()) { 13369 return null; 13370 } 13371 13372 mHardwareLayer.setLayerPaint(mLayerPaint); 13373 RenderNode displayList = mHardwareLayer.startRecording(); 13374 updateDisplayListIfDirty(displayList, true); 13375 mHardwareLayer.endRecording(mLocalDirtyRect); 13376 mLocalDirtyRect.setEmpty(); 13377 } 13378 13379 return mHardwareLayer; 13380 } 13381 13382 /** 13383 * Destroys this View's hardware layer if possible. 13384 * 13385 * @return True if the layer was destroyed, false otherwise. 13386 * 13387 * @see #setLayerType(int, android.graphics.Paint) 13388 * @see #LAYER_TYPE_HARDWARE 13389 */ 13390 boolean destroyLayer(boolean valid) { 13391 if (mHardwareLayer != null) { 13392 mHardwareLayer.destroy(); 13393 mHardwareLayer = null; 13394 13395 invalidate(true); 13396 invalidateParentCaches(); 13397 return true; 13398 } 13399 return false; 13400 } 13401 13402 /** 13403 * Destroys all hardware rendering resources. This method is invoked 13404 * when the system needs to reclaim resources. Upon execution of this 13405 * method, you should free any OpenGL resources created by the view. 13406 * 13407 * Note: you <strong>must</strong> call 13408 * <code>super.destroyHardwareResources()</code> when overriding 13409 * this method. 13410 * 13411 * @hide 13412 */ 13413 protected void destroyHardwareResources() { 13414 resetDisplayList(); 13415 destroyLayer(true); 13416 } 13417 13418 /** 13419 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13420 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13421 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13422 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13423 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13424 * null.</p> 13425 * 13426 * <p>Enabling the drawing cache is similar to 13427 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13428 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13429 * drawing cache has no effect on rendering because the system uses a different mechanism 13430 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13431 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13432 * for information on how to enable software and hardware layers.</p> 13433 * 13434 * <p>This API can be used to manually generate 13435 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13436 * {@link #getDrawingCache()}.</p> 13437 * 13438 * @param enabled true to enable the drawing cache, false otherwise 13439 * 13440 * @see #isDrawingCacheEnabled() 13441 * @see #getDrawingCache() 13442 * @see #buildDrawingCache() 13443 * @see #setLayerType(int, android.graphics.Paint) 13444 */ 13445 public void setDrawingCacheEnabled(boolean enabled) { 13446 mCachingFailed = false; 13447 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13448 } 13449 13450 /** 13451 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13452 * 13453 * @return true if the drawing cache is enabled 13454 * 13455 * @see #setDrawingCacheEnabled(boolean) 13456 * @see #getDrawingCache() 13457 */ 13458 @ViewDebug.ExportedProperty(category = "drawing") 13459 public boolean isDrawingCacheEnabled() { 13460 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13461 } 13462 13463 /** 13464 * Debugging utility which recursively outputs the dirty state of a view and its 13465 * descendants. 13466 * 13467 * @hide 13468 */ 13469 @SuppressWarnings({"UnusedDeclaration"}) 13470 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13471 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13472 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13473 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13474 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13475 if (clear) { 13476 mPrivateFlags &= clearMask; 13477 } 13478 if (this instanceof ViewGroup) { 13479 ViewGroup parent = (ViewGroup) this; 13480 final int count = parent.getChildCount(); 13481 for (int i = 0; i < count; i++) { 13482 final View child = parent.getChildAt(i); 13483 child.outputDirtyFlags(indent + " ", clear, clearMask); 13484 } 13485 } 13486 } 13487 13488 /** 13489 * This method is used by ViewGroup to cause its children to restore or recreate their 13490 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13491 * to recreate its own display list, which would happen if it went through the normal 13492 * draw/dispatchDraw mechanisms. 13493 * 13494 * @hide 13495 */ 13496 protected void dispatchGetDisplayList() {} 13497 13498 /** 13499 * A view that is not attached or hardware accelerated cannot create a display list. 13500 * This method checks these conditions and returns the appropriate result. 13501 * 13502 * @return true if view has the ability to create a display list, false otherwise. 13503 * 13504 * @hide 13505 */ 13506 public boolean canHaveDisplayList() { 13507 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13508 } 13509 13510 /** 13511 * Returns a DisplayList. If the incoming displayList is null, one will be created. 13512 * Otherwise, the same display list will be returned (after having been rendered into 13513 * along the way, depending on the invalidation state of the view). 13514 * 13515 * @param renderNode The previous version of this displayList, could be null. 13516 * @param isLayer Whether the requester of the display list is a layer. If so, 13517 * the view will avoid creating a layer inside the resulting display list. 13518 * @return A new or reused DisplayList object. 13519 */ 13520 private void updateDisplayListIfDirty(@NonNull RenderNode renderNode, boolean isLayer) { 13521 if (renderNode == null) { 13522 throw new IllegalArgumentException("RenderNode must not be null"); 13523 } 13524 if (!canHaveDisplayList()) { 13525 // can't populate RenderNode, don't try 13526 return; 13527 } 13528 13529 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13530 || !renderNode.isValid() 13531 || (!isLayer && mRecreateDisplayList)) { 13532 // Don't need to recreate the display list, just need to tell our 13533 // children to restore/recreate theirs 13534 if (renderNode.isValid() 13535 && !isLayer 13536 && !mRecreateDisplayList) { 13537 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13538 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13539 dispatchGetDisplayList(); 13540 13541 return; // no work needed 13542 } 13543 13544 if (!isLayer) { 13545 // If we got here, we're recreating it. Mark it as such to ensure that 13546 // we copy in child display lists into ours in drawChild() 13547 mRecreateDisplayList = true; 13548 } 13549 13550 boolean caching = false; 13551 int width = mRight - mLeft; 13552 int height = mBottom - mTop; 13553 int layerType = getLayerType(); 13554 13555 final HardwareCanvas canvas = renderNode.start(width, height); 13556 13557 try { 13558 if (!isLayer && layerType != LAYER_TYPE_NONE) { 13559 if (layerType == LAYER_TYPE_HARDWARE) { 13560 final HardwareLayer layer = getHardwareLayer(); 13561 if (layer != null && layer.isValid()) { 13562 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 13563 } else { 13564 canvas.saveLayer(0, 0, mRight - mLeft, mBottom - mTop, mLayerPaint, 13565 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | 13566 Canvas.CLIP_TO_LAYER_SAVE_FLAG); 13567 } 13568 caching = true; 13569 } else { 13570 buildDrawingCache(true); 13571 Bitmap cache = getDrawingCache(true); 13572 if (cache != null) { 13573 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 13574 caching = true; 13575 } 13576 } 13577 } else { 13578 13579 computeScroll(); 13580 13581 canvas.translate(-mScrollX, -mScrollY); 13582 if (!isLayer) { 13583 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13584 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13585 } 13586 13587 // Fast path for layouts with no backgrounds 13588 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13589 dispatchDraw(canvas); 13590 if (mOverlay != null && !mOverlay.isEmpty()) { 13591 mOverlay.getOverlayView().draw(canvas); 13592 } 13593 } else { 13594 draw(canvas); 13595 } 13596 } 13597 } finally { 13598 renderNode.end(canvas); 13599 renderNode.setCaching(caching); 13600 if (isLayer) { 13601 renderNode.setLeftTopRightBottom(0, 0, width, height); 13602 } else { 13603 setDisplayListProperties(renderNode); 13604 } 13605 } 13606 } else if (!isLayer) { 13607 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 13608 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13609 } 13610 } 13611 13612 /** 13613 * Returns a RenderNode with View draw content recorded, which can be 13614 * used to draw this view again without executing its draw method. 13615 * 13616 * @return A RenderNode ready to replay, or null if caching is not enabled. 13617 * 13618 * @hide 13619 */ 13620 public RenderNode getDisplayList() { 13621 updateDisplayListIfDirty(mRenderNode, false); 13622 return mRenderNode; 13623 } 13624 13625 private void resetDisplayList() { 13626 if (mRenderNode.isValid()) { 13627 mRenderNode.destroyDisplayListData(); 13628 } 13629 13630 if (mBackgroundDisplayList != null && mBackgroundDisplayList.isValid()) { 13631 mBackgroundDisplayList.destroyDisplayListData(); 13632 } 13633 } 13634 13635 /** 13636 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 13637 * 13638 * @return A non-scaled bitmap representing this view or null if cache is disabled. 13639 * 13640 * @see #getDrawingCache(boolean) 13641 */ 13642 public Bitmap getDrawingCache() { 13643 return getDrawingCache(false); 13644 } 13645 13646 /** 13647 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 13648 * is null when caching is disabled. If caching is enabled and the cache is not ready, 13649 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 13650 * draw from the cache when the cache is enabled. To benefit from the cache, you must 13651 * request the drawing cache by calling this method and draw it on screen if the 13652 * returned bitmap is not null.</p> 13653 * 13654 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13655 * this method will create a bitmap of the same size as this view. Because this bitmap 13656 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13657 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13658 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13659 * size than the view. This implies that your application must be able to handle this 13660 * size.</p> 13661 * 13662 * @param autoScale Indicates whether the generated bitmap should be scaled based on 13663 * the current density of the screen when the application is in compatibility 13664 * mode. 13665 * 13666 * @return A bitmap representing this view or null if cache is disabled. 13667 * 13668 * @see #setDrawingCacheEnabled(boolean) 13669 * @see #isDrawingCacheEnabled() 13670 * @see #buildDrawingCache(boolean) 13671 * @see #destroyDrawingCache() 13672 */ 13673 public Bitmap getDrawingCache(boolean autoScale) { 13674 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 13675 return null; 13676 } 13677 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 13678 buildDrawingCache(autoScale); 13679 } 13680 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 13681 } 13682 13683 /** 13684 * <p>Frees the resources used by the drawing cache. If you call 13685 * {@link #buildDrawingCache()} manually without calling 13686 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13687 * should cleanup the cache with this method afterwards.</p> 13688 * 13689 * @see #setDrawingCacheEnabled(boolean) 13690 * @see #buildDrawingCache() 13691 * @see #getDrawingCache() 13692 */ 13693 public void destroyDrawingCache() { 13694 if (mDrawingCache != null) { 13695 mDrawingCache.recycle(); 13696 mDrawingCache = null; 13697 } 13698 if (mUnscaledDrawingCache != null) { 13699 mUnscaledDrawingCache.recycle(); 13700 mUnscaledDrawingCache = null; 13701 } 13702 } 13703 13704 /** 13705 * Setting a solid background color for the drawing cache's bitmaps will improve 13706 * performance and memory usage. Note, though that this should only be used if this 13707 * view will always be drawn on top of a solid color. 13708 * 13709 * @param color The background color to use for the drawing cache's bitmap 13710 * 13711 * @see #setDrawingCacheEnabled(boolean) 13712 * @see #buildDrawingCache() 13713 * @see #getDrawingCache() 13714 */ 13715 public void setDrawingCacheBackgroundColor(int color) { 13716 if (color != mDrawingCacheBackgroundColor) { 13717 mDrawingCacheBackgroundColor = color; 13718 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13719 } 13720 } 13721 13722 /** 13723 * @see #setDrawingCacheBackgroundColor(int) 13724 * 13725 * @return The background color to used for the drawing cache's bitmap 13726 */ 13727 public int getDrawingCacheBackgroundColor() { 13728 return mDrawingCacheBackgroundColor; 13729 } 13730 13731 /** 13732 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 13733 * 13734 * @see #buildDrawingCache(boolean) 13735 */ 13736 public void buildDrawingCache() { 13737 buildDrawingCache(false); 13738 } 13739 13740 /** 13741 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 13742 * 13743 * <p>If you call {@link #buildDrawingCache()} manually without calling 13744 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 13745 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 13746 * 13747 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 13748 * this method will create a bitmap of the same size as this view. Because this bitmap 13749 * will be drawn scaled by the parent ViewGroup, the result on screen might show 13750 * scaling artifacts. To avoid such artifacts, you should call this method by setting 13751 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 13752 * size than the view. This implies that your application must be able to handle this 13753 * size.</p> 13754 * 13755 * <p>You should avoid calling this method when hardware acceleration is enabled. If 13756 * you do not need the drawing cache bitmap, calling this method will increase memory 13757 * usage and cause the view to be rendered in software once, thus negatively impacting 13758 * performance.</p> 13759 * 13760 * @see #getDrawingCache() 13761 * @see #destroyDrawingCache() 13762 */ 13763 public void buildDrawingCache(boolean autoScale) { 13764 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 13765 mDrawingCache == null : mUnscaledDrawingCache == null)) { 13766 mCachingFailed = false; 13767 13768 int width = mRight - mLeft; 13769 int height = mBottom - mTop; 13770 13771 final AttachInfo attachInfo = mAttachInfo; 13772 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 13773 13774 if (autoScale && scalingRequired) { 13775 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 13776 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 13777 } 13778 13779 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 13780 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 13781 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 13782 13783 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 13784 final long drawingCacheSize = 13785 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 13786 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 13787 if (width > 0 && height > 0) { 13788 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 13789 + projectedBitmapSize + " bytes, only " 13790 + drawingCacheSize + " available"); 13791 } 13792 destroyDrawingCache(); 13793 mCachingFailed = true; 13794 return; 13795 } 13796 13797 boolean clear = true; 13798 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 13799 13800 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 13801 Bitmap.Config quality; 13802 if (!opaque) { 13803 // Never pick ARGB_4444 because it looks awful 13804 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 13805 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 13806 case DRAWING_CACHE_QUALITY_AUTO: 13807 case DRAWING_CACHE_QUALITY_LOW: 13808 case DRAWING_CACHE_QUALITY_HIGH: 13809 default: 13810 quality = Bitmap.Config.ARGB_8888; 13811 break; 13812 } 13813 } else { 13814 // Optimization for translucent windows 13815 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 13816 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 13817 } 13818 13819 // Try to cleanup memory 13820 if (bitmap != null) bitmap.recycle(); 13821 13822 try { 13823 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13824 width, height, quality); 13825 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 13826 if (autoScale) { 13827 mDrawingCache = bitmap; 13828 } else { 13829 mUnscaledDrawingCache = bitmap; 13830 } 13831 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 13832 } catch (OutOfMemoryError e) { 13833 // If there is not enough memory to create the bitmap cache, just 13834 // ignore the issue as bitmap caches are not required to draw the 13835 // view hierarchy 13836 if (autoScale) { 13837 mDrawingCache = null; 13838 } else { 13839 mUnscaledDrawingCache = null; 13840 } 13841 mCachingFailed = true; 13842 return; 13843 } 13844 13845 clear = drawingCacheBackgroundColor != 0; 13846 } 13847 13848 Canvas canvas; 13849 if (attachInfo != null) { 13850 canvas = attachInfo.mCanvas; 13851 if (canvas == null) { 13852 canvas = new Canvas(); 13853 } 13854 canvas.setBitmap(bitmap); 13855 // Temporarily clobber the cached Canvas in case one of our children 13856 // is also using a drawing cache. Without this, the children would 13857 // steal the canvas by attaching their own bitmap to it and bad, bad 13858 // thing would happen (invisible views, corrupted drawings, etc.) 13859 attachInfo.mCanvas = null; 13860 } else { 13861 // This case should hopefully never or seldom happen 13862 canvas = new Canvas(bitmap); 13863 } 13864 13865 if (clear) { 13866 bitmap.eraseColor(drawingCacheBackgroundColor); 13867 } 13868 13869 computeScroll(); 13870 final int restoreCount = canvas.save(); 13871 13872 if (autoScale && scalingRequired) { 13873 final float scale = attachInfo.mApplicationScale; 13874 canvas.scale(scale, scale); 13875 } 13876 13877 canvas.translate(-mScrollX, -mScrollY); 13878 13879 mPrivateFlags |= PFLAG_DRAWN; 13880 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 13881 mLayerType != LAYER_TYPE_NONE) { 13882 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 13883 } 13884 13885 // Fast path for layouts with no backgrounds 13886 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13887 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13888 dispatchDraw(canvas); 13889 if (mOverlay != null && !mOverlay.isEmpty()) { 13890 mOverlay.getOverlayView().draw(canvas); 13891 } 13892 } else { 13893 draw(canvas); 13894 } 13895 13896 canvas.restoreToCount(restoreCount); 13897 canvas.setBitmap(null); 13898 13899 if (attachInfo != null) { 13900 // Restore the cached Canvas for our siblings 13901 attachInfo.mCanvas = canvas; 13902 } 13903 } 13904 } 13905 13906 /** 13907 * Create a snapshot of the view into a bitmap. We should probably make 13908 * some form of this public, but should think about the API. 13909 */ 13910 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 13911 int width = mRight - mLeft; 13912 int height = mBottom - mTop; 13913 13914 final AttachInfo attachInfo = mAttachInfo; 13915 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 13916 width = (int) ((width * scale) + 0.5f); 13917 height = (int) ((height * scale) + 0.5f); 13918 13919 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 13920 width > 0 ? width : 1, height > 0 ? height : 1, quality); 13921 if (bitmap == null) { 13922 throw new OutOfMemoryError(); 13923 } 13924 13925 Resources resources = getResources(); 13926 if (resources != null) { 13927 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 13928 } 13929 13930 Canvas canvas; 13931 if (attachInfo != null) { 13932 canvas = attachInfo.mCanvas; 13933 if (canvas == null) { 13934 canvas = new Canvas(); 13935 } 13936 canvas.setBitmap(bitmap); 13937 // Temporarily clobber the cached Canvas in case one of our children 13938 // is also using a drawing cache. Without this, the children would 13939 // steal the canvas by attaching their own bitmap to it and bad, bad 13940 // things would happen (invisible views, corrupted drawings, etc.) 13941 attachInfo.mCanvas = null; 13942 } else { 13943 // This case should hopefully never or seldom happen 13944 canvas = new Canvas(bitmap); 13945 } 13946 13947 if ((backgroundColor & 0xff000000) != 0) { 13948 bitmap.eraseColor(backgroundColor); 13949 } 13950 13951 computeScroll(); 13952 final int restoreCount = canvas.save(); 13953 canvas.scale(scale, scale); 13954 canvas.translate(-mScrollX, -mScrollY); 13955 13956 // Temporarily remove the dirty mask 13957 int flags = mPrivateFlags; 13958 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 13959 13960 // Fast path for layouts with no backgrounds 13961 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 13962 dispatchDraw(canvas); 13963 if (mOverlay != null && !mOverlay.isEmpty()) { 13964 mOverlay.getOverlayView().draw(canvas); 13965 } 13966 } else { 13967 draw(canvas); 13968 } 13969 13970 mPrivateFlags = flags; 13971 13972 canvas.restoreToCount(restoreCount); 13973 canvas.setBitmap(null); 13974 13975 if (attachInfo != null) { 13976 // Restore the cached Canvas for our siblings 13977 attachInfo.mCanvas = canvas; 13978 } 13979 13980 return bitmap; 13981 } 13982 13983 /** 13984 * Indicates whether this View is currently in edit mode. A View is usually 13985 * in edit mode when displayed within a developer tool. For instance, if 13986 * this View is being drawn by a visual user interface builder, this method 13987 * should return true. 13988 * 13989 * Subclasses should check the return value of this method to provide 13990 * different behaviors if their normal behavior might interfere with the 13991 * host environment. For instance: the class spawns a thread in its 13992 * constructor, the drawing code relies on device-specific features, etc. 13993 * 13994 * This method is usually checked in the drawing code of custom widgets. 13995 * 13996 * @return True if this View is in edit mode, false otherwise. 13997 */ 13998 public boolean isInEditMode() { 13999 return false; 14000 } 14001 14002 /** 14003 * If the View draws content inside its padding and enables fading edges, 14004 * it needs to support padding offsets. Padding offsets are added to the 14005 * fading edges to extend the length of the fade so that it covers pixels 14006 * drawn inside the padding. 14007 * 14008 * Subclasses of this class should override this method if they need 14009 * to draw content inside the padding. 14010 * 14011 * @return True if padding offset must be applied, false otherwise. 14012 * 14013 * @see #getLeftPaddingOffset() 14014 * @see #getRightPaddingOffset() 14015 * @see #getTopPaddingOffset() 14016 * @see #getBottomPaddingOffset() 14017 * 14018 * @since CURRENT 14019 */ 14020 protected boolean isPaddingOffsetRequired() { 14021 return false; 14022 } 14023 14024 /** 14025 * Amount by which to extend the left fading region. Called only when 14026 * {@link #isPaddingOffsetRequired()} returns true. 14027 * 14028 * @return The left padding offset in pixels. 14029 * 14030 * @see #isPaddingOffsetRequired() 14031 * 14032 * @since CURRENT 14033 */ 14034 protected int getLeftPaddingOffset() { 14035 return 0; 14036 } 14037 14038 /** 14039 * Amount by which to extend the right fading region. Called only when 14040 * {@link #isPaddingOffsetRequired()} returns true. 14041 * 14042 * @return The right padding offset in pixels. 14043 * 14044 * @see #isPaddingOffsetRequired() 14045 * 14046 * @since CURRENT 14047 */ 14048 protected int getRightPaddingOffset() { 14049 return 0; 14050 } 14051 14052 /** 14053 * Amount by which to extend the top fading region. Called only when 14054 * {@link #isPaddingOffsetRequired()} returns true. 14055 * 14056 * @return The top padding offset in pixels. 14057 * 14058 * @see #isPaddingOffsetRequired() 14059 * 14060 * @since CURRENT 14061 */ 14062 protected int getTopPaddingOffset() { 14063 return 0; 14064 } 14065 14066 /** 14067 * Amount by which to extend the bottom fading region. Called only when 14068 * {@link #isPaddingOffsetRequired()} returns true. 14069 * 14070 * @return The bottom padding offset in pixels. 14071 * 14072 * @see #isPaddingOffsetRequired() 14073 * 14074 * @since CURRENT 14075 */ 14076 protected int getBottomPaddingOffset() { 14077 return 0; 14078 } 14079 14080 /** 14081 * @hide 14082 * @param offsetRequired 14083 */ 14084 protected int getFadeTop(boolean offsetRequired) { 14085 int top = mPaddingTop; 14086 if (offsetRequired) top += getTopPaddingOffset(); 14087 return top; 14088 } 14089 14090 /** 14091 * @hide 14092 * @param offsetRequired 14093 */ 14094 protected int getFadeHeight(boolean offsetRequired) { 14095 int padding = mPaddingTop; 14096 if (offsetRequired) padding += getTopPaddingOffset(); 14097 return mBottom - mTop - mPaddingBottom - padding; 14098 } 14099 14100 /** 14101 * <p>Indicates whether this view is attached to a hardware accelerated 14102 * window or not.</p> 14103 * 14104 * <p>Even if this method returns true, it does not mean that every call 14105 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14106 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14107 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14108 * window is hardware accelerated, 14109 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14110 * return false, and this method will return true.</p> 14111 * 14112 * @return True if the view is attached to a window and the window is 14113 * hardware accelerated; false in any other case. 14114 */ 14115 public boolean isHardwareAccelerated() { 14116 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14117 } 14118 14119 /** 14120 * Sets a rectangular area on this view to which the view will be clipped 14121 * when it is drawn. Setting the value to null will remove the clip bounds 14122 * and the view will draw normally, using its full bounds. 14123 * 14124 * @param clipBounds The rectangular area, in the local coordinates of 14125 * this view, to which future drawing operations will be clipped. 14126 */ 14127 public void setClipBounds(Rect clipBounds) { 14128 if (clipBounds != null) { 14129 if (clipBounds.equals(mClipBounds)) { 14130 return; 14131 } 14132 if (mClipBounds == null) { 14133 invalidate(); 14134 mClipBounds = new Rect(clipBounds); 14135 } else { 14136 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14137 Math.min(mClipBounds.top, clipBounds.top), 14138 Math.max(mClipBounds.right, clipBounds.right), 14139 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14140 mClipBounds.set(clipBounds); 14141 } 14142 } else { 14143 if (mClipBounds != null) { 14144 invalidate(); 14145 mClipBounds = null; 14146 } 14147 } 14148 } 14149 14150 /** 14151 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14152 * 14153 * @return A copy of the current clip bounds if clip bounds are set, 14154 * otherwise null. 14155 */ 14156 public Rect getClipBounds() { 14157 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14158 } 14159 14160 /** 14161 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14162 * case of an active Animation being run on the view. 14163 */ 14164 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14165 Animation a, boolean scalingRequired) { 14166 Transformation invalidationTransform; 14167 final int flags = parent.mGroupFlags; 14168 final boolean initialized = a.isInitialized(); 14169 if (!initialized) { 14170 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14171 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14172 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14173 onAnimationStart(); 14174 } 14175 14176 final Transformation t = parent.getChildTransformation(); 14177 boolean more = a.getTransformation(drawingTime, t, 1f); 14178 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14179 if (parent.mInvalidationTransformation == null) { 14180 parent.mInvalidationTransformation = new Transformation(); 14181 } 14182 invalidationTransform = parent.mInvalidationTransformation; 14183 a.getTransformation(drawingTime, invalidationTransform, 1f); 14184 } else { 14185 invalidationTransform = t; 14186 } 14187 14188 if (more) { 14189 if (!a.willChangeBounds()) { 14190 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14191 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14192 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14193 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14194 // The child need to draw an animation, potentially offscreen, so 14195 // make sure we do not cancel invalidate requests 14196 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14197 parent.invalidate(mLeft, mTop, mRight, mBottom); 14198 } 14199 } else { 14200 if (parent.mInvalidateRegion == null) { 14201 parent.mInvalidateRegion = new RectF(); 14202 } 14203 final RectF region = parent.mInvalidateRegion; 14204 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14205 invalidationTransform); 14206 14207 // The child need to draw an animation, potentially offscreen, so 14208 // make sure we do not cancel invalidate requests 14209 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14210 14211 final int left = mLeft + (int) region.left; 14212 final int top = mTop + (int) region.top; 14213 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14214 top + (int) (region.height() + .5f)); 14215 } 14216 } 14217 return more; 14218 } 14219 14220 /** 14221 * This method is called by getDisplayList() when a display list is recorded for a View. 14222 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14223 */ 14224 void setDisplayListProperties(RenderNode renderNode) { 14225 if (renderNode != null) { 14226 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14227 if (mParent instanceof ViewGroup) { 14228 renderNode.setClipToBounds( 14229 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14230 } 14231 float alpha = 1; 14232 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14233 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14234 ViewGroup parentVG = (ViewGroup) mParent; 14235 final Transformation t = parentVG.getChildTransformation(); 14236 if (parentVG.getChildStaticTransformation(this, t)) { 14237 final int transformType = t.getTransformationType(); 14238 if (transformType != Transformation.TYPE_IDENTITY) { 14239 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14240 alpha = t.getAlpha(); 14241 } 14242 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14243 renderNode.setStaticMatrix(t.getMatrix()); 14244 } 14245 } 14246 } 14247 } 14248 if (mTransformationInfo != null) { 14249 alpha *= getFinalAlpha(); 14250 if (alpha < 1) { 14251 final int multipliedAlpha = (int) (255 * alpha); 14252 if (onSetAlpha(multipliedAlpha)) { 14253 alpha = 1; 14254 } 14255 } 14256 renderNode.setAlpha(alpha); 14257 } else if (alpha < 1) { 14258 renderNode.setAlpha(alpha); 14259 } 14260 } 14261 } 14262 14263 /** 14264 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14265 * This draw() method is an implementation detail and is not intended to be overridden or 14266 * to be called from anywhere else other than ViewGroup.drawChild(). 14267 */ 14268 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14269 boolean useDisplayListProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14270 boolean more = false; 14271 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14272 final int flags = parent.mGroupFlags; 14273 14274 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14275 parent.getChildTransformation().clear(); 14276 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14277 } 14278 14279 Transformation transformToApply = null; 14280 boolean concatMatrix = false; 14281 14282 boolean scalingRequired = false; 14283 boolean caching; 14284 int layerType = getLayerType(); 14285 14286 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14287 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14288 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14289 caching = true; 14290 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14291 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14292 } else { 14293 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14294 } 14295 14296 final Animation a = getAnimation(); 14297 if (a != null) { 14298 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14299 concatMatrix = a.willChangeTransformationMatrix(); 14300 if (concatMatrix) { 14301 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14302 } 14303 transformToApply = parent.getChildTransformation(); 14304 } else { 14305 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14306 // No longer animating: clear out old animation matrix 14307 mRenderNode.setAnimationMatrix(null); 14308 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14309 } 14310 if (!useDisplayListProperties && 14311 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14312 final Transformation t = parent.getChildTransformation(); 14313 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14314 if (hasTransform) { 14315 final int transformType = t.getTransformationType(); 14316 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14317 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14318 } 14319 } 14320 } 14321 14322 concatMatrix |= !childHasIdentityMatrix; 14323 14324 // Sets the flag as early as possible to allow draw() implementations 14325 // to call invalidate() successfully when doing animations 14326 mPrivateFlags |= PFLAG_DRAWN; 14327 14328 if (!concatMatrix && 14329 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14330 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14331 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14332 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14333 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14334 return more; 14335 } 14336 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14337 14338 if (hardwareAccelerated) { 14339 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14340 // retain the flag's value temporarily in the mRecreateDisplayList flag 14341 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14342 mPrivateFlags &= ~PFLAG_INVALIDATED; 14343 } 14344 14345 RenderNode displayList = null; 14346 Bitmap cache = null; 14347 boolean hasDisplayList = false; 14348 if (caching) { 14349 if (!hardwareAccelerated) { 14350 if (layerType != LAYER_TYPE_NONE) { 14351 layerType = LAYER_TYPE_SOFTWARE; 14352 buildDrawingCache(true); 14353 } 14354 cache = getDrawingCache(true); 14355 } else { 14356 switch (layerType) { 14357 case LAYER_TYPE_SOFTWARE: 14358 if (useDisplayListProperties) { 14359 hasDisplayList = canHaveDisplayList(); 14360 } else { 14361 buildDrawingCache(true); 14362 cache = getDrawingCache(true); 14363 } 14364 break; 14365 case LAYER_TYPE_HARDWARE: 14366 if (useDisplayListProperties) { 14367 hasDisplayList = canHaveDisplayList(); 14368 } 14369 break; 14370 case LAYER_TYPE_NONE: 14371 // Delay getting the display list until animation-driven alpha values are 14372 // set up and possibly passed on to the view 14373 hasDisplayList = canHaveDisplayList(); 14374 break; 14375 } 14376 } 14377 } 14378 useDisplayListProperties &= hasDisplayList; 14379 if (useDisplayListProperties) { 14380 displayList = getDisplayList(); 14381 if (!displayList.isValid()) { 14382 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14383 // to getDisplayList(), the display list will be marked invalid and we should not 14384 // try to use it again. 14385 displayList = null; 14386 hasDisplayList = false; 14387 useDisplayListProperties = false; 14388 } 14389 } 14390 14391 int sx = 0; 14392 int sy = 0; 14393 if (!hasDisplayList) { 14394 computeScroll(); 14395 sx = mScrollX; 14396 sy = mScrollY; 14397 } 14398 14399 final boolean hasNoCache = cache == null || hasDisplayList; 14400 final boolean offsetForScroll = cache == null && !hasDisplayList && 14401 layerType != LAYER_TYPE_HARDWARE; 14402 14403 int restoreTo = -1; 14404 if (!useDisplayListProperties || transformToApply != null) { 14405 restoreTo = canvas.save(); 14406 } 14407 if (offsetForScroll) { 14408 canvas.translate(mLeft - sx, mTop - sy); 14409 } else { 14410 if (!useDisplayListProperties) { 14411 canvas.translate(mLeft, mTop); 14412 } 14413 if (scalingRequired) { 14414 if (useDisplayListProperties) { 14415 // TODO: Might not need this if we put everything inside the DL 14416 restoreTo = canvas.save(); 14417 } 14418 // mAttachInfo cannot be null, otherwise scalingRequired == false 14419 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14420 canvas.scale(scale, scale); 14421 } 14422 } 14423 14424 float alpha = useDisplayListProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14425 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14426 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14427 if (transformToApply != null || !childHasIdentityMatrix) { 14428 int transX = 0; 14429 int transY = 0; 14430 14431 if (offsetForScroll) { 14432 transX = -sx; 14433 transY = -sy; 14434 } 14435 14436 if (transformToApply != null) { 14437 if (concatMatrix) { 14438 if (useDisplayListProperties) { 14439 displayList.setAnimationMatrix(transformToApply.getMatrix()); 14440 } else { 14441 // Undo the scroll translation, apply the transformation matrix, 14442 // then redo the scroll translate to get the correct result. 14443 canvas.translate(-transX, -transY); 14444 canvas.concat(transformToApply.getMatrix()); 14445 canvas.translate(transX, transY); 14446 } 14447 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14448 } 14449 14450 float transformAlpha = transformToApply.getAlpha(); 14451 if (transformAlpha < 1) { 14452 alpha *= transformAlpha; 14453 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14454 } 14455 } 14456 14457 if (!childHasIdentityMatrix && !useDisplayListProperties) { 14458 canvas.translate(-transX, -transY); 14459 canvas.concat(getMatrix()); 14460 canvas.translate(transX, transY); 14461 } 14462 } 14463 14464 // Deal with alpha if it is or used to be <1 14465 if (alpha < 1 || 14466 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14467 if (alpha < 1) { 14468 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14469 } else { 14470 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14471 } 14472 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14473 if (hasNoCache) { 14474 final int multipliedAlpha = (int) (255 * alpha); 14475 if (!onSetAlpha(multipliedAlpha)) { 14476 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14477 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14478 layerType != LAYER_TYPE_NONE) { 14479 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14480 } 14481 if (useDisplayListProperties) { 14482 displayList.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14483 } else if (layerType == LAYER_TYPE_NONE) { 14484 final int scrollX = hasDisplayList ? 0 : sx; 14485 final int scrollY = hasDisplayList ? 0 : sy; 14486 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + mRight - mLeft, 14487 scrollY + mBottom - mTop, multipliedAlpha, layerFlags); 14488 } 14489 } else { 14490 // Alpha is handled by the child directly, clobber the layer's alpha 14491 mPrivateFlags |= PFLAG_ALPHA_SET; 14492 } 14493 } 14494 } 14495 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14496 onSetAlpha(255); 14497 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14498 } 14499 14500 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && 14501 !useDisplayListProperties && cache == null) { 14502 if (offsetForScroll) { 14503 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14504 } else { 14505 if (!scalingRequired || cache == null) { 14506 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14507 } else { 14508 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14509 } 14510 } 14511 } 14512 14513 if (!useDisplayListProperties && hasDisplayList) { 14514 displayList = getDisplayList(); 14515 if (!displayList.isValid()) { 14516 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14517 // to getDisplayList(), the display list will be marked invalid and we should not 14518 // try to use it again. 14519 displayList = null; 14520 hasDisplayList = false; 14521 } 14522 } 14523 14524 if (hasNoCache) { 14525 boolean layerRendered = false; 14526 if (layerType == LAYER_TYPE_HARDWARE && !useDisplayListProperties) { 14527 final HardwareLayer layer = getHardwareLayer(); 14528 if (layer != null && layer.isValid()) { 14529 mLayerPaint.setAlpha((int) (alpha * 255)); 14530 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 14531 layerRendered = true; 14532 } else { 14533 final int scrollX = hasDisplayList ? 0 : sx; 14534 final int scrollY = hasDisplayList ? 0 : sy; 14535 canvas.saveLayer(scrollX, scrollY, 14536 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 14537 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 14538 } 14539 } 14540 14541 if (!layerRendered) { 14542 if (!hasDisplayList) { 14543 // Fast path for layouts with no backgrounds 14544 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14545 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14546 dispatchDraw(canvas); 14547 } else { 14548 draw(canvas); 14549 } 14550 } else { 14551 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14552 ((HardwareCanvas) canvas).drawDisplayList(displayList, null, flags); 14553 } 14554 } 14555 } else if (cache != null) { 14556 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14557 Paint cachePaint; 14558 14559 if (layerType == LAYER_TYPE_NONE) { 14560 cachePaint = parent.mCachePaint; 14561 if (cachePaint == null) { 14562 cachePaint = new Paint(); 14563 cachePaint.setDither(false); 14564 parent.mCachePaint = cachePaint; 14565 } 14566 if (alpha < 1) { 14567 cachePaint.setAlpha((int) (alpha * 255)); 14568 parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14569 } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { 14570 cachePaint.setAlpha(255); 14571 parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; 14572 } 14573 } else { 14574 cachePaint = mLayerPaint; 14575 cachePaint.setAlpha((int) (alpha * 255)); 14576 } 14577 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 14578 } 14579 14580 if (restoreTo >= 0) { 14581 canvas.restoreToCount(restoreTo); 14582 } 14583 14584 if (a != null && !more) { 14585 if (!hardwareAccelerated && !a.getFillAfter()) { 14586 onSetAlpha(255); 14587 } 14588 parent.finishAnimatingView(this, a); 14589 } 14590 14591 if (more && hardwareAccelerated) { 14592 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14593 // alpha animations should cause the child to recreate its display list 14594 invalidate(true); 14595 } 14596 } 14597 14598 mRecreateDisplayList = false; 14599 14600 return more; 14601 } 14602 14603 /** 14604 * Manually render this view (and all of its children) to the given Canvas. 14605 * The view must have already done a full layout before this function is 14606 * called. When implementing a view, implement 14607 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 14608 * If you do need to override this method, call the superclass version. 14609 * 14610 * @param canvas The Canvas to which the View is rendered. 14611 */ 14612 public void draw(Canvas canvas) { 14613 if (mClipBounds != null) { 14614 canvas.clipRect(mClipBounds); 14615 } 14616 final int privateFlags = mPrivateFlags; 14617 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 14618 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 14619 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 14620 14621 /* 14622 * Draw traversal performs several drawing steps which must be executed 14623 * in the appropriate order: 14624 * 14625 * 1. Draw the background 14626 * 2. If necessary, save the canvas' layers to prepare for fading 14627 * 3. Draw view's content 14628 * 4. Draw children 14629 * 5. If necessary, draw the fading edges and restore layers 14630 * 6. Draw decorations (scrollbars for instance) 14631 */ 14632 14633 // Step 1, draw the background, if needed 14634 int saveCount; 14635 14636 if (!dirtyOpaque) { 14637 drawBackground(canvas); 14638 } 14639 14640 // skip step 2 & 5 if possible (common case) 14641 final int viewFlags = mViewFlags; 14642 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 14643 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 14644 if (!verticalEdges && !horizontalEdges) { 14645 // Step 3, draw the content 14646 if (!dirtyOpaque) onDraw(canvas); 14647 14648 // Step 4, draw the children 14649 dispatchDraw(canvas); 14650 14651 // Step 6, draw decorations (scrollbars) 14652 onDrawScrollBars(canvas); 14653 14654 if (mOverlay != null && !mOverlay.isEmpty()) { 14655 mOverlay.getOverlayView().dispatchDraw(canvas); 14656 } 14657 14658 // we're done... 14659 return; 14660 } 14661 14662 /* 14663 * Here we do the full fledged routine... 14664 * (this is an uncommon case where speed matters less, 14665 * this is why we repeat some of the tests that have been 14666 * done above) 14667 */ 14668 14669 boolean drawTop = false; 14670 boolean drawBottom = false; 14671 boolean drawLeft = false; 14672 boolean drawRight = false; 14673 14674 float topFadeStrength = 0.0f; 14675 float bottomFadeStrength = 0.0f; 14676 float leftFadeStrength = 0.0f; 14677 float rightFadeStrength = 0.0f; 14678 14679 // Step 2, save the canvas' layers 14680 int paddingLeft = mPaddingLeft; 14681 14682 final boolean offsetRequired = isPaddingOffsetRequired(); 14683 if (offsetRequired) { 14684 paddingLeft += getLeftPaddingOffset(); 14685 } 14686 14687 int left = mScrollX + paddingLeft; 14688 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 14689 int top = mScrollY + getFadeTop(offsetRequired); 14690 int bottom = top + getFadeHeight(offsetRequired); 14691 14692 if (offsetRequired) { 14693 right += getRightPaddingOffset(); 14694 bottom += getBottomPaddingOffset(); 14695 } 14696 14697 final ScrollabilityCache scrollabilityCache = mScrollCache; 14698 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 14699 int length = (int) fadeHeight; 14700 14701 // clip the fade length if top and bottom fades overlap 14702 // overlapping fades produce odd-looking artifacts 14703 if (verticalEdges && (top + length > bottom - length)) { 14704 length = (bottom - top) / 2; 14705 } 14706 14707 // also clip horizontal fades if necessary 14708 if (horizontalEdges && (left + length > right - length)) { 14709 length = (right - left) / 2; 14710 } 14711 14712 if (verticalEdges) { 14713 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 14714 drawTop = topFadeStrength * fadeHeight > 1.0f; 14715 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 14716 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 14717 } 14718 14719 if (horizontalEdges) { 14720 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 14721 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 14722 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 14723 drawRight = rightFadeStrength * fadeHeight > 1.0f; 14724 } 14725 14726 saveCount = canvas.getSaveCount(); 14727 14728 int solidColor = getSolidColor(); 14729 if (solidColor == 0) { 14730 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14731 14732 if (drawTop) { 14733 canvas.saveLayer(left, top, right, top + length, null, flags); 14734 } 14735 14736 if (drawBottom) { 14737 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 14738 } 14739 14740 if (drawLeft) { 14741 canvas.saveLayer(left, top, left + length, bottom, null, flags); 14742 } 14743 14744 if (drawRight) { 14745 canvas.saveLayer(right - length, top, right, bottom, null, flags); 14746 } 14747 } else { 14748 scrollabilityCache.setFadeColor(solidColor); 14749 } 14750 14751 // Step 3, draw the content 14752 if (!dirtyOpaque) onDraw(canvas); 14753 14754 // Step 4, draw the children 14755 dispatchDraw(canvas); 14756 14757 // Step 5, draw the fade effect and restore layers 14758 final Paint p = scrollabilityCache.paint; 14759 final Matrix matrix = scrollabilityCache.matrix; 14760 final Shader fade = scrollabilityCache.shader; 14761 14762 if (drawTop) { 14763 matrix.setScale(1, fadeHeight * topFadeStrength); 14764 matrix.postTranslate(left, top); 14765 fade.setLocalMatrix(matrix); 14766 canvas.drawRect(left, top, right, top + length, p); 14767 } 14768 14769 if (drawBottom) { 14770 matrix.setScale(1, fadeHeight * bottomFadeStrength); 14771 matrix.postRotate(180); 14772 matrix.postTranslate(left, bottom); 14773 fade.setLocalMatrix(matrix); 14774 canvas.drawRect(left, bottom - length, right, bottom, p); 14775 } 14776 14777 if (drawLeft) { 14778 matrix.setScale(1, fadeHeight * leftFadeStrength); 14779 matrix.postRotate(-90); 14780 matrix.postTranslate(left, top); 14781 fade.setLocalMatrix(matrix); 14782 canvas.drawRect(left, top, left + length, bottom, p); 14783 } 14784 14785 if (drawRight) { 14786 matrix.setScale(1, fadeHeight * rightFadeStrength); 14787 matrix.postRotate(90); 14788 matrix.postTranslate(right, top); 14789 fade.setLocalMatrix(matrix); 14790 canvas.drawRect(right - length, top, right, bottom, p); 14791 } 14792 14793 canvas.restoreToCount(saveCount); 14794 14795 // Step 6, draw decorations (scrollbars) 14796 onDrawScrollBars(canvas); 14797 14798 if (mOverlay != null && !mOverlay.isEmpty()) { 14799 mOverlay.getOverlayView().dispatchDraw(canvas); 14800 } 14801 } 14802 14803 /** 14804 * Draws the background onto the specified canvas. 14805 * 14806 * @param canvas Canvas on which to draw the background 14807 */ 14808 private void drawBackground(Canvas canvas) { 14809 final Drawable background = mBackground; 14810 if (background == null) { 14811 return; 14812 } 14813 14814 if (mBackgroundSizeChanged) { 14815 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 14816 mBackgroundSizeChanged = false; 14817 queryOutlineFromBackgroundIfUndefined(); 14818 } 14819 14820 // Attempt to use a display list if requested. 14821 if (canvas.isHardwareAccelerated() && mAttachInfo != null 14822 && mAttachInfo.mHardwareRenderer != null) { 14823 mBackgroundDisplayList = getDrawableDisplayList(background, mBackgroundDisplayList); 14824 14825 final RenderNode displayList = mBackgroundDisplayList; 14826 if (displayList != null && displayList.isValid()) { 14827 setBackgroundDisplayListProperties(displayList); 14828 ((HardwareCanvas) canvas).drawDisplayList(displayList); 14829 return; 14830 } 14831 } 14832 14833 final int scrollX = mScrollX; 14834 final int scrollY = mScrollY; 14835 if ((scrollX | scrollY) == 0) { 14836 background.draw(canvas); 14837 } else { 14838 canvas.translate(scrollX, scrollY); 14839 background.draw(canvas); 14840 canvas.translate(-scrollX, -scrollY); 14841 } 14842 } 14843 14844 /** 14845 * Set up background drawable display list properties. 14846 * 14847 * @param displayList Valid display list for the background drawable 14848 */ 14849 private void setBackgroundDisplayListProperties(RenderNode displayList) { 14850 displayList.setTranslationX(mScrollX); 14851 displayList.setTranslationY(mScrollY); 14852 } 14853 14854 /** 14855 * Creates a new display list or updates the existing display list for the 14856 * specified Drawable. 14857 * 14858 * @param drawable Drawable for which to create a display list 14859 * @param displayList Existing display list, or {@code null} 14860 * @return A valid display list for the specified drawable 14861 */ 14862 private RenderNode getDrawableDisplayList(Drawable drawable, RenderNode displayList) { 14863 if (displayList == null) { 14864 displayList = RenderNode.create(drawable.getClass().getName()); 14865 } 14866 14867 final Rect bounds = drawable.getBounds(); 14868 final int width = bounds.width(); 14869 final int height = bounds.height(); 14870 final HardwareCanvas canvas = displayList.start(width, height); 14871 try { 14872 drawable.draw(canvas); 14873 } finally { 14874 displayList.end(canvas); 14875 } 14876 14877 // Set up drawable properties that are view-independent. 14878 displayList.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 14879 displayList.setProjectBackwards(drawable.isProjected()); 14880 displayList.setProjectionReceiver(true); 14881 displayList.setClipToBounds(false); 14882 return displayList; 14883 } 14884 14885 /** 14886 * Returns the overlay for this view, creating it if it does not yet exist. 14887 * Adding drawables to the overlay will cause them to be displayed whenever 14888 * the view itself is redrawn. Objects in the overlay should be actively 14889 * managed: remove them when they should not be displayed anymore. The 14890 * overlay will always have the same size as its host view. 14891 * 14892 * <p>Note: Overlays do not currently work correctly with {@link 14893 * SurfaceView} or {@link TextureView}; contents in overlays for these 14894 * types of views may not display correctly.</p> 14895 * 14896 * @return The ViewOverlay object for this view. 14897 * @see ViewOverlay 14898 */ 14899 public ViewOverlay getOverlay() { 14900 if (mOverlay == null) { 14901 mOverlay = new ViewOverlay(mContext, this); 14902 } 14903 return mOverlay; 14904 } 14905 14906 /** 14907 * Override this if your view is known to always be drawn on top of a solid color background, 14908 * and needs to draw fading edges. Returning a non-zero color enables the view system to 14909 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 14910 * should be set to 0xFF. 14911 * 14912 * @see #setVerticalFadingEdgeEnabled(boolean) 14913 * @see #setHorizontalFadingEdgeEnabled(boolean) 14914 * 14915 * @return The known solid color background for this view, or 0 if the color may vary 14916 */ 14917 @ViewDebug.ExportedProperty(category = "drawing") 14918 public int getSolidColor() { 14919 return 0; 14920 } 14921 14922 /** 14923 * Build a human readable string representation of the specified view flags. 14924 * 14925 * @param flags the view flags to convert to a string 14926 * @return a String representing the supplied flags 14927 */ 14928 private static String printFlags(int flags) { 14929 String output = ""; 14930 int numFlags = 0; 14931 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 14932 output += "TAKES_FOCUS"; 14933 numFlags++; 14934 } 14935 14936 switch (flags & VISIBILITY_MASK) { 14937 case INVISIBLE: 14938 if (numFlags > 0) { 14939 output += " "; 14940 } 14941 output += "INVISIBLE"; 14942 // USELESS HERE numFlags++; 14943 break; 14944 case GONE: 14945 if (numFlags > 0) { 14946 output += " "; 14947 } 14948 output += "GONE"; 14949 // USELESS HERE numFlags++; 14950 break; 14951 default: 14952 break; 14953 } 14954 return output; 14955 } 14956 14957 /** 14958 * Build a human readable string representation of the specified private 14959 * view flags. 14960 * 14961 * @param privateFlags the private view flags to convert to a string 14962 * @return a String representing the supplied flags 14963 */ 14964 private static String printPrivateFlags(int privateFlags) { 14965 String output = ""; 14966 int numFlags = 0; 14967 14968 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 14969 output += "WANTS_FOCUS"; 14970 numFlags++; 14971 } 14972 14973 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 14974 if (numFlags > 0) { 14975 output += " "; 14976 } 14977 output += "FOCUSED"; 14978 numFlags++; 14979 } 14980 14981 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 14982 if (numFlags > 0) { 14983 output += " "; 14984 } 14985 output += "SELECTED"; 14986 numFlags++; 14987 } 14988 14989 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 14990 if (numFlags > 0) { 14991 output += " "; 14992 } 14993 output += "IS_ROOT_NAMESPACE"; 14994 numFlags++; 14995 } 14996 14997 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 14998 if (numFlags > 0) { 14999 output += " "; 15000 } 15001 output += "HAS_BOUNDS"; 15002 numFlags++; 15003 } 15004 15005 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15006 if (numFlags > 0) { 15007 output += " "; 15008 } 15009 output += "DRAWN"; 15010 // USELESS HERE numFlags++; 15011 } 15012 return output; 15013 } 15014 15015 /** 15016 * <p>Indicates whether or not this view's layout will be requested during 15017 * the next hierarchy layout pass.</p> 15018 * 15019 * @return true if the layout will be forced during next layout pass 15020 */ 15021 public boolean isLayoutRequested() { 15022 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15023 } 15024 15025 /** 15026 * Return true if o is a ViewGroup that is laying out using optical bounds. 15027 * @hide 15028 */ 15029 public static boolean isLayoutModeOptical(Object o) { 15030 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15031 } 15032 15033 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15034 Insets parentInsets = mParent instanceof View ? 15035 ((View) mParent).getOpticalInsets() : Insets.NONE; 15036 Insets childInsets = getOpticalInsets(); 15037 return setFrame( 15038 left + parentInsets.left - childInsets.left, 15039 top + parentInsets.top - childInsets.top, 15040 right + parentInsets.left + childInsets.right, 15041 bottom + parentInsets.top + childInsets.bottom); 15042 } 15043 15044 /** 15045 * Assign a size and position to a view and all of its 15046 * descendants 15047 * 15048 * <p>This is the second phase of the layout mechanism. 15049 * (The first is measuring). In this phase, each parent calls 15050 * layout on all of its children to position them. 15051 * This is typically done using the child measurements 15052 * that were stored in the measure pass().</p> 15053 * 15054 * <p>Derived classes should not override this method. 15055 * Derived classes with children should override 15056 * onLayout. In that method, they should 15057 * call layout on each of their children.</p> 15058 * 15059 * @param l Left position, relative to parent 15060 * @param t Top position, relative to parent 15061 * @param r Right position, relative to parent 15062 * @param b Bottom position, relative to parent 15063 */ 15064 @SuppressWarnings({"unchecked"}) 15065 public void layout(int l, int t, int r, int b) { 15066 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15067 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15068 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15069 } 15070 15071 int oldL = mLeft; 15072 int oldT = mTop; 15073 int oldB = mBottom; 15074 int oldR = mRight; 15075 15076 boolean changed = isLayoutModeOptical(mParent) ? 15077 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15078 15079 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15080 onLayout(changed, l, t, r, b); 15081 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15082 15083 ListenerInfo li = mListenerInfo; 15084 if (li != null && li.mOnLayoutChangeListeners != null) { 15085 ArrayList<OnLayoutChangeListener> listenersCopy = 15086 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15087 int numListeners = listenersCopy.size(); 15088 for (int i = 0; i < numListeners; ++i) { 15089 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15090 } 15091 } 15092 } 15093 15094 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15095 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15096 } 15097 15098 /** 15099 * Called from layout when this view should 15100 * assign a size and position to each of its children. 15101 * 15102 * Derived classes with children should override 15103 * this method and call layout on each of 15104 * their children. 15105 * @param changed This is a new size or position for this view 15106 * @param left Left position, relative to parent 15107 * @param top Top position, relative to parent 15108 * @param right Right position, relative to parent 15109 * @param bottom Bottom position, relative to parent 15110 */ 15111 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15112 } 15113 15114 /** 15115 * Assign a size and position to this view. 15116 * 15117 * This is called from layout. 15118 * 15119 * @param left Left position, relative to parent 15120 * @param top Top position, relative to parent 15121 * @param right Right position, relative to parent 15122 * @param bottom Bottom position, relative to parent 15123 * @return true if the new size and position are different than the 15124 * previous ones 15125 * {@hide} 15126 */ 15127 protected boolean setFrame(int left, int top, int right, int bottom) { 15128 boolean changed = false; 15129 15130 if (DBG) { 15131 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15132 + right + "," + bottom + ")"); 15133 } 15134 15135 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15136 changed = true; 15137 15138 // Remember our drawn bit 15139 int drawn = mPrivateFlags & PFLAG_DRAWN; 15140 15141 int oldWidth = mRight - mLeft; 15142 int oldHeight = mBottom - mTop; 15143 int newWidth = right - left; 15144 int newHeight = bottom - top; 15145 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15146 15147 // Invalidate our old position 15148 invalidate(sizeChanged); 15149 15150 mLeft = left; 15151 mTop = top; 15152 mRight = right; 15153 mBottom = bottom; 15154 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15155 15156 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15157 15158 15159 if (sizeChanged) { 15160 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15161 } 15162 15163 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15164 // If we are visible, force the DRAWN bit to on so that 15165 // this invalidate will go through (at least to our parent). 15166 // This is because someone may have invalidated this view 15167 // before this call to setFrame came in, thereby clearing 15168 // the DRAWN bit. 15169 mPrivateFlags |= PFLAG_DRAWN; 15170 invalidate(sizeChanged); 15171 // parent display list may need to be recreated based on a change in the bounds 15172 // of any child 15173 invalidateParentCaches(); 15174 } 15175 15176 // Reset drawn bit to original value (invalidate turns it off) 15177 mPrivateFlags |= drawn; 15178 15179 mBackgroundSizeChanged = true; 15180 15181 notifySubtreeAccessibilityStateChangedIfNeeded(); 15182 } 15183 return changed; 15184 } 15185 15186 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15187 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15188 if (mOverlay != null) { 15189 mOverlay.getOverlayView().setRight(newWidth); 15190 mOverlay.getOverlayView().setBottom(newHeight); 15191 } 15192 } 15193 15194 /** 15195 * Finalize inflating a view from XML. This is called as the last phase 15196 * of inflation, after all child views have been added. 15197 * 15198 * <p>Even if the subclass overrides onFinishInflate, they should always be 15199 * sure to call the super method, so that we get called. 15200 */ 15201 protected void onFinishInflate() { 15202 } 15203 15204 /** 15205 * Returns the resources associated with this view. 15206 * 15207 * @return Resources object. 15208 */ 15209 public Resources getResources() { 15210 return mResources; 15211 } 15212 15213 /** 15214 * Invalidates the specified Drawable. 15215 * 15216 * @param drawable the drawable to invalidate 15217 */ 15218 @Override 15219 public void invalidateDrawable(@NonNull Drawable drawable) { 15220 if (verifyDrawable(drawable)) { 15221 final Rect dirty = drawable.getDirtyBounds(); 15222 final int scrollX = mScrollX; 15223 final int scrollY = mScrollY; 15224 15225 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15226 dirty.right + scrollX, dirty.bottom + scrollY); 15227 15228 if (drawable == mBackground) { 15229 queryOutlineFromBackgroundIfUndefined(); 15230 } 15231 } 15232 } 15233 15234 /** 15235 * Schedules an action on a drawable to occur at a specified time. 15236 * 15237 * @param who the recipient of the action 15238 * @param what the action to run on the drawable 15239 * @param when the time at which the action must occur. Uses the 15240 * {@link SystemClock#uptimeMillis} timebase. 15241 */ 15242 @Override 15243 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15244 if (verifyDrawable(who) && what != null) { 15245 final long delay = when - SystemClock.uptimeMillis(); 15246 if (mAttachInfo != null) { 15247 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15248 Choreographer.CALLBACK_ANIMATION, what, who, 15249 Choreographer.subtractFrameDelay(delay)); 15250 } else { 15251 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15252 } 15253 } 15254 } 15255 15256 /** 15257 * Cancels a scheduled action on a drawable. 15258 * 15259 * @param who the recipient of the action 15260 * @param what the action to cancel 15261 */ 15262 @Override 15263 public void unscheduleDrawable(Drawable who, Runnable what) { 15264 if (verifyDrawable(who) && what != null) { 15265 if (mAttachInfo != null) { 15266 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15267 Choreographer.CALLBACK_ANIMATION, what, who); 15268 } 15269 ViewRootImpl.getRunQueue().removeCallbacks(what); 15270 } 15271 } 15272 15273 /** 15274 * Unschedule any events associated with the given Drawable. This can be 15275 * used when selecting a new Drawable into a view, so that the previous 15276 * one is completely unscheduled. 15277 * 15278 * @param who The Drawable to unschedule. 15279 * 15280 * @see #drawableStateChanged 15281 */ 15282 public void unscheduleDrawable(Drawable who) { 15283 if (mAttachInfo != null && who != null) { 15284 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15285 Choreographer.CALLBACK_ANIMATION, null, who); 15286 } 15287 } 15288 15289 /** 15290 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15291 * that the View directionality can and will be resolved before its Drawables. 15292 * 15293 * Will call {@link View#onResolveDrawables} when resolution is done. 15294 * 15295 * @hide 15296 */ 15297 protected void resolveDrawables() { 15298 // Drawables resolution may need to happen before resolving the layout direction (which is 15299 // done only during the measure() call). 15300 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15301 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15302 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15303 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15304 // direction to be resolved as its resolved value will be the same as its raw value. 15305 if (!isLayoutDirectionResolved() && 15306 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15307 return; 15308 } 15309 15310 final int layoutDirection = isLayoutDirectionResolved() ? 15311 getLayoutDirection() : getRawLayoutDirection(); 15312 15313 if (mBackground != null) { 15314 mBackground.setLayoutDirection(layoutDirection); 15315 } 15316 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15317 onResolveDrawables(layoutDirection); 15318 } 15319 15320 /** 15321 * Called when layout direction has been resolved. 15322 * 15323 * The default implementation does nothing. 15324 * 15325 * @param layoutDirection The resolved layout direction. 15326 * 15327 * @see #LAYOUT_DIRECTION_LTR 15328 * @see #LAYOUT_DIRECTION_RTL 15329 * 15330 * @hide 15331 */ 15332 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15333 } 15334 15335 /** 15336 * @hide 15337 */ 15338 protected void resetResolvedDrawables() { 15339 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15340 } 15341 15342 private boolean isDrawablesResolved() { 15343 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15344 } 15345 15346 /** 15347 * If your view subclass is displaying its own Drawable objects, it should 15348 * override this function and return true for any Drawable it is 15349 * displaying. This allows animations for those drawables to be 15350 * scheduled. 15351 * 15352 * <p>Be sure to call through to the super class when overriding this 15353 * function. 15354 * 15355 * @param who The Drawable to verify. Return true if it is one you are 15356 * displaying, else return the result of calling through to the 15357 * super class. 15358 * 15359 * @return boolean If true than the Drawable is being displayed in the 15360 * view; else false and it is not allowed to animate. 15361 * 15362 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15363 * @see #drawableStateChanged() 15364 */ 15365 protected boolean verifyDrawable(Drawable who) { 15366 return who == mBackground; 15367 } 15368 15369 /** 15370 * This function is called whenever the state of the view changes in such 15371 * a way that it impacts the state of drawables being shown. 15372 * 15373 * <p>Be sure to call through to the superclass when overriding this 15374 * function. 15375 * 15376 * @see Drawable#setState(int[]) 15377 */ 15378 protected void drawableStateChanged() { 15379 final Drawable d = mBackground; 15380 if (d != null && d.isStateful()) { 15381 d.setState(getDrawableState()); 15382 } 15383 } 15384 15385 /** 15386 * Call this to force a view to update its drawable state. This will cause 15387 * drawableStateChanged to be called on this view. Views that are interested 15388 * in the new state should call getDrawableState. 15389 * 15390 * @see #drawableStateChanged 15391 * @see #getDrawableState 15392 */ 15393 public void refreshDrawableState() { 15394 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15395 drawableStateChanged(); 15396 15397 ViewParent parent = mParent; 15398 if (parent != null) { 15399 parent.childDrawableStateChanged(this); 15400 } 15401 } 15402 15403 /** 15404 * Return an array of resource IDs of the drawable states representing the 15405 * current state of the view. 15406 * 15407 * @return The current drawable state 15408 * 15409 * @see Drawable#setState(int[]) 15410 * @see #drawableStateChanged() 15411 * @see #onCreateDrawableState(int) 15412 */ 15413 public final int[] getDrawableState() { 15414 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15415 return mDrawableState; 15416 } else { 15417 mDrawableState = onCreateDrawableState(0); 15418 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15419 return mDrawableState; 15420 } 15421 } 15422 15423 /** 15424 * Generate the new {@link android.graphics.drawable.Drawable} state for 15425 * this view. This is called by the view 15426 * system when the cached Drawable state is determined to be invalid. To 15427 * retrieve the current state, you should use {@link #getDrawableState}. 15428 * 15429 * @param extraSpace if non-zero, this is the number of extra entries you 15430 * would like in the returned array in which you can place your own 15431 * states. 15432 * 15433 * @return Returns an array holding the current {@link Drawable} state of 15434 * the view. 15435 * 15436 * @see #mergeDrawableStates(int[], int[]) 15437 */ 15438 protected int[] onCreateDrawableState(int extraSpace) { 15439 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15440 mParent instanceof View) { 15441 return ((View) mParent).onCreateDrawableState(extraSpace); 15442 } 15443 15444 int[] drawableState; 15445 15446 int privateFlags = mPrivateFlags; 15447 15448 int viewStateIndex = 0; 15449 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15450 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15451 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15452 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15453 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15454 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15455 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15456 HardwareRenderer.isAvailable()) { 15457 // This is set if HW acceleration is requested, even if the current 15458 // process doesn't allow it. This is just to allow app preview 15459 // windows to better match their app. 15460 viewStateIndex |= VIEW_STATE_ACCELERATED; 15461 } 15462 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15463 15464 final int privateFlags2 = mPrivateFlags2; 15465 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 15466 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 15467 15468 drawableState = VIEW_STATE_SETS[viewStateIndex]; 15469 15470 //noinspection ConstantIfStatement 15471 if (false) { 15472 Log.i("View", "drawableStateIndex=" + viewStateIndex); 15473 Log.i("View", toString() 15474 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 15475 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 15476 + " fo=" + hasFocus() 15477 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 15478 + " wf=" + hasWindowFocus() 15479 + ": " + Arrays.toString(drawableState)); 15480 } 15481 15482 if (extraSpace == 0) { 15483 return drawableState; 15484 } 15485 15486 final int[] fullState; 15487 if (drawableState != null) { 15488 fullState = new int[drawableState.length + extraSpace]; 15489 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 15490 } else { 15491 fullState = new int[extraSpace]; 15492 } 15493 15494 return fullState; 15495 } 15496 15497 /** 15498 * Merge your own state values in <var>additionalState</var> into the base 15499 * state values <var>baseState</var> that were returned by 15500 * {@link #onCreateDrawableState(int)}. 15501 * 15502 * @param baseState The base state values returned by 15503 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 15504 * own additional state values. 15505 * 15506 * @param additionalState The additional state values you would like 15507 * added to <var>baseState</var>; this array is not modified. 15508 * 15509 * @return As a convenience, the <var>baseState</var> array you originally 15510 * passed into the function is returned. 15511 * 15512 * @see #onCreateDrawableState(int) 15513 */ 15514 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 15515 final int N = baseState.length; 15516 int i = N - 1; 15517 while (i >= 0 && baseState[i] == 0) { 15518 i--; 15519 } 15520 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 15521 return baseState; 15522 } 15523 15524 /** 15525 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 15526 * on all Drawable objects associated with this view. 15527 */ 15528 public void jumpDrawablesToCurrentState() { 15529 if (mBackground != null) { 15530 mBackground.jumpToCurrentState(); 15531 } 15532 } 15533 15534 /** 15535 * Sets the background color for this view. 15536 * @param color the color of the background 15537 */ 15538 @RemotableViewMethod 15539 public void setBackgroundColor(int color) { 15540 if (mBackground instanceof ColorDrawable) { 15541 ((ColorDrawable) mBackground.mutate()).setColor(color); 15542 computeOpaqueFlags(); 15543 mBackgroundResource = 0; 15544 } else { 15545 setBackground(new ColorDrawable(color)); 15546 } 15547 } 15548 15549 /** 15550 * Set the background to a given resource. The resource should refer to 15551 * a Drawable object or 0 to remove the background. 15552 * @param resid The identifier of the resource. 15553 * 15554 * @attr ref android.R.styleable#View_background 15555 */ 15556 @RemotableViewMethod 15557 public void setBackgroundResource(int resid) { 15558 if (resid != 0 && resid == mBackgroundResource) { 15559 return; 15560 } 15561 15562 Drawable d= null; 15563 if (resid != 0) { 15564 d = mContext.getDrawable(resid); 15565 } 15566 setBackground(d); 15567 15568 mBackgroundResource = resid; 15569 } 15570 15571 /** 15572 * Set the background to a given Drawable, or remove the background. If the 15573 * background has padding, this View's padding is set to the background's 15574 * padding. However, when a background is removed, this View's padding isn't 15575 * touched. If setting the padding is desired, please use 15576 * {@link #setPadding(int, int, int, int)}. 15577 * 15578 * @param background The Drawable to use as the background, or null to remove the 15579 * background 15580 */ 15581 public void setBackground(Drawable background) { 15582 //noinspection deprecation 15583 setBackgroundDrawable(background); 15584 } 15585 15586 /** 15587 * @deprecated use {@link #setBackground(Drawable)} instead 15588 */ 15589 @Deprecated 15590 public void setBackgroundDrawable(Drawable background) { 15591 computeOpaqueFlags(); 15592 15593 if (background == mBackground) { 15594 return; 15595 } 15596 15597 boolean requestLayout = false; 15598 15599 mBackgroundResource = 0; 15600 15601 /* 15602 * Regardless of whether we're setting a new background or not, we want 15603 * to clear the previous drawable. 15604 */ 15605 if (mBackground != null) { 15606 mBackground.setCallback(null); 15607 unscheduleDrawable(mBackground); 15608 } 15609 15610 if (background != null) { 15611 Rect padding = sThreadLocal.get(); 15612 if (padding == null) { 15613 padding = new Rect(); 15614 sThreadLocal.set(padding); 15615 } 15616 resetResolvedDrawables(); 15617 background.setLayoutDirection(getLayoutDirection()); 15618 if (background.getPadding(padding)) { 15619 resetResolvedPadding(); 15620 switch (background.getLayoutDirection()) { 15621 case LAYOUT_DIRECTION_RTL: 15622 mUserPaddingLeftInitial = padding.right; 15623 mUserPaddingRightInitial = padding.left; 15624 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 15625 break; 15626 case LAYOUT_DIRECTION_LTR: 15627 default: 15628 mUserPaddingLeftInitial = padding.left; 15629 mUserPaddingRightInitial = padding.right; 15630 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 15631 } 15632 mLeftPaddingDefined = false; 15633 mRightPaddingDefined = false; 15634 } 15635 15636 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 15637 // if it has a different minimum size, we should layout again 15638 if (mBackground == null || mBackground.getMinimumHeight() != background.getMinimumHeight() || 15639 mBackground.getMinimumWidth() != background.getMinimumWidth()) { 15640 requestLayout = true; 15641 } 15642 15643 background.setCallback(this); 15644 if (background.isStateful()) { 15645 background.setState(getDrawableState()); 15646 } 15647 background.setVisible(getVisibility() == VISIBLE, false); 15648 mBackground = background; 15649 15650 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 15651 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 15652 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 15653 requestLayout = true; 15654 } 15655 } else { 15656 /* Remove the background */ 15657 mBackground = null; 15658 15659 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 15660 /* 15661 * This view ONLY drew the background before and we're removing 15662 * the background, so now it won't draw anything 15663 * (hence we SKIP_DRAW) 15664 */ 15665 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 15666 mPrivateFlags |= PFLAG_SKIP_DRAW; 15667 } 15668 15669 /* 15670 * When the background is set, we try to apply its padding to this 15671 * View. When the background is removed, we don't touch this View's 15672 * padding. This is noted in the Javadocs. Hence, we don't need to 15673 * requestLayout(), the invalidate() below is sufficient. 15674 */ 15675 15676 // The old background's minimum size could have affected this 15677 // View's layout, so let's requestLayout 15678 requestLayout = true; 15679 } 15680 15681 computeOpaqueFlags(); 15682 15683 if (requestLayout) { 15684 requestLayout(); 15685 } 15686 15687 mBackgroundSizeChanged = true; 15688 invalidate(true); 15689 } 15690 15691 /** 15692 * Gets the background drawable 15693 * 15694 * @return The drawable used as the background for this view, if any. 15695 * 15696 * @see #setBackground(Drawable) 15697 * 15698 * @attr ref android.R.styleable#View_background 15699 */ 15700 public Drawable getBackground() { 15701 return mBackground; 15702 } 15703 15704 /** 15705 * Sets the padding. The view may add on the space required to display 15706 * the scrollbars, depending on the style and visibility of the scrollbars. 15707 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 15708 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 15709 * from the values set in this call. 15710 * 15711 * @attr ref android.R.styleable#View_padding 15712 * @attr ref android.R.styleable#View_paddingBottom 15713 * @attr ref android.R.styleable#View_paddingLeft 15714 * @attr ref android.R.styleable#View_paddingRight 15715 * @attr ref android.R.styleable#View_paddingTop 15716 * @param left the left padding in pixels 15717 * @param top the top padding in pixels 15718 * @param right the right padding in pixels 15719 * @param bottom the bottom padding in pixels 15720 */ 15721 public void setPadding(int left, int top, int right, int bottom) { 15722 resetResolvedPadding(); 15723 15724 mUserPaddingStart = UNDEFINED_PADDING; 15725 mUserPaddingEnd = UNDEFINED_PADDING; 15726 15727 mUserPaddingLeftInitial = left; 15728 mUserPaddingRightInitial = right; 15729 15730 mLeftPaddingDefined = true; 15731 mRightPaddingDefined = true; 15732 15733 internalSetPadding(left, top, right, bottom); 15734 } 15735 15736 /** 15737 * @hide 15738 */ 15739 protected void internalSetPadding(int left, int top, int right, int bottom) { 15740 mUserPaddingLeft = left; 15741 mUserPaddingRight = right; 15742 mUserPaddingBottom = bottom; 15743 15744 final int viewFlags = mViewFlags; 15745 boolean changed = false; 15746 15747 // Common case is there are no scroll bars. 15748 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 15749 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 15750 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 15751 ? 0 : getVerticalScrollbarWidth(); 15752 switch (mVerticalScrollbarPosition) { 15753 case SCROLLBAR_POSITION_DEFAULT: 15754 if (isLayoutRtl()) { 15755 left += offset; 15756 } else { 15757 right += offset; 15758 } 15759 break; 15760 case SCROLLBAR_POSITION_RIGHT: 15761 right += offset; 15762 break; 15763 case SCROLLBAR_POSITION_LEFT: 15764 left += offset; 15765 break; 15766 } 15767 } 15768 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 15769 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 15770 ? 0 : getHorizontalScrollbarHeight(); 15771 } 15772 } 15773 15774 if (mPaddingLeft != left) { 15775 changed = true; 15776 mPaddingLeft = left; 15777 } 15778 if (mPaddingTop != top) { 15779 changed = true; 15780 mPaddingTop = top; 15781 } 15782 if (mPaddingRight != right) { 15783 changed = true; 15784 mPaddingRight = right; 15785 } 15786 if (mPaddingBottom != bottom) { 15787 changed = true; 15788 mPaddingBottom = bottom; 15789 } 15790 15791 if (changed) { 15792 requestLayout(); 15793 } 15794 } 15795 15796 /** 15797 * Sets the relative padding. The view may add on the space required to display 15798 * the scrollbars, depending on the style and visibility of the scrollbars. 15799 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 15800 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 15801 * from the values set in this call. 15802 * 15803 * @attr ref android.R.styleable#View_padding 15804 * @attr ref android.R.styleable#View_paddingBottom 15805 * @attr ref android.R.styleable#View_paddingStart 15806 * @attr ref android.R.styleable#View_paddingEnd 15807 * @attr ref android.R.styleable#View_paddingTop 15808 * @param start the start padding in pixels 15809 * @param top the top padding in pixels 15810 * @param end the end padding in pixels 15811 * @param bottom the bottom padding in pixels 15812 */ 15813 public void setPaddingRelative(int start, int top, int end, int bottom) { 15814 resetResolvedPadding(); 15815 15816 mUserPaddingStart = start; 15817 mUserPaddingEnd = end; 15818 mLeftPaddingDefined = true; 15819 mRightPaddingDefined = true; 15820 15821 switch(getLayoutDirection()) { 15822 case LAYOUT_DIRECTION_RTL: 15823 mUserPaddingLeftInitial = end; 15824 mUserPaddingRightInitial = start; 15825 internalSetPadding(end, top, start, bottom); 15826 break; 15827 case LAYOUT_DIRECTION_LTR: 15828 default: 15829 mUserPaddingLeftInitial = start; 15830 mUserPaddingRightInitial = end; 15831 internalSetPadding(start, top, end, bottom); 15832 } 15833 } 15834 15835 /** 15836 * Returns the top padding of this view. 15837 * 15838 * @return the top padding in pixels 15839 */ 15840 public int getPaddingTop() { 15841 return mPaddingTop; 15842 } 15843 15844 /** 15845 * Returns the bottom padding of this view. If there are inset and enabled 15846 * scrollbars, this value may include the space required to display the 15847 * scrollbars as well. 15848 * 15849 * @return the bottom padding in pixels 15850 */ 15851 public int getPaddingBottom() { 15852 return mPaddingBottom; 15853 } 15854 15855 /** 15856 * Returns the left padding of this view. If there are inset and enabled 15857 * scrollbars, this value may include the space required to display the 15858 * scrollbars as well. 15859 * 15860 * @return the left padding in pixels 15861 */ 15862 public int getPaddingLeft() { 15863 if (!isPaddingResolved()) { 15864 resolvePadding(); 15865 } 15866 return mPaddingLeft; 15867 } 15868 15869 /** 15870 * Returns the start padding of this view depending on its resolved layout direction. 15871 * If there are inset and enabled scrollbars, this value may include the space 15872 * required to display the scrollbars as well. 15873 * 15874 * @return the start padding in pixels 15875 */ 15876 public int getPaddingStart() { 15877 if (!isPaddingResolved()) { 15878 resolvePadding(); 15879 } 15880 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15881 mPaddingRight : mPaddingLeft; 15882 } 15883 15884 /** 15885 * Returns the right padding of this view. If there are inset and enabled 15886 * scrollbars, this value may include the space required to display the 15887 * scrollbars as well. 15888 * 15889 * @return the right padding in pixels 15890 */ 15891 public int getPaddingRight() { 15892 if (!isPaddingResolved()) { 15893 resolvePadding(); 15894 } 15895 return mPaddingRight; 15896 } 15897 15898 /** 15899 * Returns the end padding of this view depending on its resolved layout direction. 15900 * If there are inset and enabled scrollbars, this value may include the space 15901 * required to display the scrollbars as well. 15902 * 15903 * @return the end padding in pixels 15904 */ 15905 public int getPaddingEnd() { 15906 if (!isPaddingResolved()) { 15907 resolvePadding(); 15908 } 15909 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 15910 mPaddingLeft : mPaddingRight; 15911 } 15912 15913 /** 15914 * Return if the padding as been set thru relative values 15915 * {@link #setPaddingRelative(int, int, int, int)} or thru 15916 * @attr ref android.R.styleable#View_paddingStart or 15917 * @attr ref android.R.styleable#View_paddingEnd 15918 * 15919 * @return true if the padding is relative or false if it is not. 15920 */ 15921 public boolean isPaddingRelative() { 15922 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 15923 } 15924 15925 Insets computeOpticalInsets() { 15926 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 15927 } 15928 15929 /** 15930 * @hide 15931 */ 15932 public void resetPaddingToInitialValues() { 15933 if (isRtlCompatibilityMode()) { 15934 mPaddingLeft = mUserPaddingLeftInitial; 15935 mPaddingRight = mUserPaddingRightInitial; 15936 return; 15937 } 15938 if (isLayoutRtl()) { 15939 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 15940 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 15941 } else { 15942 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 15943 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 15944 } 15945 } 15946 15947 /** 15948 * @hide 15949 */ 15950 public Insets getOpticalInsets() { 15951 if (mLayoutInsets == null) { 15952 mLayoutInsets = computeOpticalInsets(); 15953 } 15954 return mLayoutInsets; 15955 } 15956 15957 /** 15958 * Changes the selection state of this view. A view can be selected or not. 15959 * Note that selection is not the same as focus. Views are typically 15960 * selected in the context of an AdapterView like ListView or GridView; 15961 * the selected view is the view that is highlighted. 15962 * 15963 * @param selected true if the view must be selected, false otherwise 15964 */ 15965 public void setSelected(boolean selected) { 15966 //noinspection DoubleNegation 15967 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 15968 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 15969 if (!selected) resetPressedState(); 15970 invalidate(true); 15971 refreshDrawableState(); 15972 dispatchSetSelected(selected); 15973 notifyViewAccessibilityStateChangedIfNeeded( 15974 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 15975 } 15976 } 15977 15978 /** 15979 * Dispatch setSelected to all of this View's children. 15980 * 15981 * @see #setSelected(boolean) 15982 * 15983 * @param selected The new selected state 15984 */ 15985 protected void dispatchSetSelected(boolean selected) { 15986 } 15987 15988 /** 15989 * Indicates the selection state of this view. 15990 * 15991 * @return true if the view is selected, false otherwise 15992 */ 15993 @ViewDebug.ExportedProperty 15994 public boolean isSelected() { 15995 return (mPrivateFlags & PFLAG_SELECTED) != 0; 15996 } 15997 15998 /** 15999 * Changes the activated state of this view. A view can be activated or not. 16000 * Note that activation is not the same as selection. Selection is 16001 * a transient property, representing the view (hierarchy) the user is 16002 * currently interacting with. Activation is a longer-term state that the 16003 * user can move views in and out of. For example, in a list view with 16004 * single or multiple selection enabled, the views in the current selection 16005 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16006 * here.) The activated state is propagated down to children of the view it 16007 * is set on. 16008 * 16009 * @param activated true if the view must be activated, false otherwise 16010 */ 16011 public void setActivated(boolean activated) { 16012 //noinspection DoubleNegation 16013 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16014 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16015 invalidate(true); 16016 refreshDrawableState(); 16017 dispatchSetActivated(activated); 16018 } 16019 } 16020 16021 /** 16022 * Dispatch setActivated to all of this View's children. 16023 * 16024 * @see #setActivated(boolean) 16025 * 16026 * @param activated The new activated state 16027 */ 16028 protected void dispatchSetActivated(boolean activated) { 16029 } 16030 16031 /** 16032 * Indicates the activation state of this view. 16033 * 16034 * @return true if the view is activated, false otherwise 16035 */ 16036 @ViewDebug.ExportedProperty 16037 public boolean isActivated() { 16038 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16039 } 16040 16041 /** 16042 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16043 * observer can be used to get notifications when global events, like 16044 * layout, happen. 16045 * 16046 * The returned ViewTreeObserver observer is not guaranteed to remain 16047 * valid for the lifetime of this View. If the caller of this method keeps 16048 * a long-lived reference to ViewTreeObserver, it should always check for 16049 * the return value of {@link ViewTreeObserver#isAlive()}. 16050 * 16051 * @return The ViewTreeObserver for this view's hierarchy. 16052 */ 16053 public ViewTreeObserver getViewTreeObserver() { 16054 if (mAttachInfo != null) { 16055 return mAttachInfo.mTreeObserver; 16056 } 16057 if (mFloatingTreeObserver == null) { 16058 mFloatingTreeObserver = new ViewTreeObserver(); 16059 } 16060 return mFloatingTreeObserver; 16061 } 16062 16063 /** 16064 * <p>Finds the topmost view in the current view hierarchy.</p> 16065 * 16066 * @return the topmost view containing this view 16067 */ 16068 public View getRootView() { 16069 if (mAttachInfo != null) { 16070 final View v = mAttachInfo.mRootView; 16071 if (v != null) { 16072 return v; 16073 } 16074 } 16075 16076 View parent = this; 16077 16078 while (parent.mParent != null && parent.mParent instanceof View) { 16079 parent = (View) parent.mParent; 16080 } 16081 16082 return parent; 16083 } 16084 16085 /** 16086 * Transforms a motion event from view-local coordinates to on-screen 16087 * coordinates. 16088 * 16089 * @param ev the view-local motion event 16090 * @return false if the transformation could not be applied 16091 * @hide 16092 */ 16093 public boolean toGlobalMotionEvent(MotionEvent ev) { 16094 final AttachInfo info = mAttachInfo; 16095 if (info == null) { 16096 return false; 16097 } 16098 16099 final Matrix m = info.mTmpMatrix; 16100 m.set(Matrix.IDENTITY_MATRIX); 16101 transformMatrixToGlobal(m); 16102 ev.transform(m); 16103 return true; 16104 } 16105 16106 /** 16107 * Transforms a motion event from on-screen coordinates to view-local 16108 * coordinates. 16109 * 16110 * @param ev the on-screen motion event 16111 * @return false if the transformation could not be applied 16112 * @hide 16113 */ 16114 public boolean toLocalMotionEvent(MotionEvent ev) { 16115 final AttachInfo info = mAttachInfo; 16116 if (info == null) { 16117 return false; 16118 } 16119 16120 final Matrix m = info.mTmpMatrix; 16121 m.set(Matrix.IDENTITY_MATRIX); 16122 transformMatrixToLocal(m); 16123 ev.transform(m); 16124 return true; 16125 } 16126 16127 /** 16128 * Modifies the input matrix such that it maps view-local coordinates to 16129 * on-screen coordinates. 16130 * 16131 * @param m input matrix to modify 16132 */ 16133 void transformMatrixToGlobal(Matrix m) { 16134 final ViewParent parent = mParent; 16135 if (parent instanceof View) { 16136 final View vp = (View) parent; 16137 vp.transformMatrixToGlobal(m); 16138 m.postTranslate(-vp.mScrollX, -vp.mScrollY); 16139 } else if (parent instanceof ViewRootImpl) { 16140 final ViewRootImpl vr = (ViewRootImpl) parent; 16141 vr.transformMatrixToGlobal(m); 16142 m.postTranslate(0, -vr.mCurScrollY); 16143 } 16144 16145 m.postTranslate(mLeft, mTop); 16146 16147 if (!hasIdentityMatrix()) { 16148 m.postConcat(getMatrix()); 16149 } 16150 } 16151 16152 /** 16153 * Modifies the input matrix such that it maps on-screen coordinates to 16154 * view-local coordinates. 16155 * 16156 * @param m input matrix to modify 16157 */ 16158 void transformMatrixToLocal(Matrix m) { 16159 final ViewParent parent = mParent; 16160 if (parent instanceof View) { 16161 final View vp = (View) parent; 16162 vp.transformMatrixToLocal(m); 16163 m.preTranslate(vp.mScrollX, vp.mScrollY); 16164 } else if (parent instanceof ViewRootImpl) { 16165 final ViewRootImpl vr = (ViewRootImpl) parent; 16166 vr.transformMatrixToLocal(m); 16167 m.preTranslate(0, vr.mCurScrollY); 16168 } 16169 16170 m.preTranslate(-mLeft, -mTop); 16171 16172 if (!hasIdentityMatrix()) { 16173 m.preConcat(getInverseMatrix()); 16174 } 16175 } 16176 16177 /** 16178 * <p>Computes the coordinates of this view on the screen. The argument 16179 * must be an array of two integers. After the method returns, the array 16180 * contains the x and y location in that order.</p> 16181 * 16182 * @param location an array of two integers in which to hold the coordinates 16183 */ 16184 public void getLocationOnScreen(int[] location) { 16185 getLocationInWindow(location); 16186 16187 final AttachInfo info = mAttachInfo; 16188 if (info != null) { 16189 location[0] += info.mWindowLeft; 16190 location[1] += info.mWindowTop; 16191 } 16192 } 16193 16194 /** 16195 * <p>Computes the coordinates of this view in its window. The argument 16196 * must be an array of two integers. After the method returns, the array 16197 * contains the x and y location in that order.</p> 16198 * 16199 * @param location an array of two integers in which to hold the coordinates 16200 */ 16201 public void getLocationInWindow(int[] location) { 16202 if (location == null || location.length < 2) { 16203 throw new IllegalArgumentException("location must be an array of two integers"); 16204 } 16205 16206 if (mAttachInfo == null) { 16207 // When the view is not attached to a window, this method does not make sense 16208 location[0] = location[1] = 0; 16209 return; 16210 } 16211 16212 float[] position = mAttachInfo.mTmpTransformLocation; 16213 position[0] = position[1] = 0.0f; 16214 16215 if (!hasIdentityMatrix()) { 16216 getMatrix().mapPoints(position); 16217 } 16218 16219 position[0] += mLeft; 16220 position[1] += mTop; 16221 16222 ViewParent viewParent = mParent; 16223 while (viewParent instanceof View) { 16224 final View view = (View) viewParent; 16225 16226 position[0] -= view.mScrollX; 16227 position[1] -= view.mScrollY; 16228 16229 if (!view.hasIdentityMatrix()) { 16230 view.getMatrix().mapPoints(position); 16231 } 16232 16233 position[0] += view.mLeft; 16234 position[1] += view.mTop; 16235 16236 viewParent = view.mParent; 16237 } 16238 16239 if (viewParent instanceof ViewRootImpl) { 16240 // *cough* 16241 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16242 position[1] -= vr.mCurScrollY; 16243 } 16244 16245 location[0] = (int) (position[0] + 0.5f); 16246 location[1] = (int) (position[1] + 0.5f); 16247 } 16248 16249 /** 16250 * {@hide} 16251 * @param id the id of the view to be found 16252 * @return the view of the specified id, null if cannot be found 16253 */ 16254 protected View findViewTraversal(int id) { 16255 if (id == mID) { 16256 return this; 16257 } 16258 return null; 16259 } 16260 16261 /** 16262 * {@hide} 16263 * @param tag the tag of the view to be found 16264 * @return the view of specified tag, null if cannot be found 16265 */ 16266 protected View findViewWithTagTraversal(Object tag) { 16267 if (tag != null && tag.equals(mTag)) { 16268 return this; 16269 } 16270 return null; 16271 } 16272 16273 /** 16274 * {@hide} 16275 * @param predicate The predicate to evaluate. 16276 * @param childToSkip If not null, ignores this child during the recursive traversal. 16277 * @return The first view that matches the predicate or null. 16278 */ 16279 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16280 if (predicate.apply(this)) { 16281 return this; 16282 } 16283 return null; 16284 } 16285 16286 /** 16287 * Look for a child view with the given id. If this view has the given 16288 * id, return this view. 16289 * 16290 * @param id The id to search for. 16291 * @return The view that has the given id in the hierarchy or null 16292 */ 16293 public final View findViewById(int id) { 16294 if (id < 0) { 16295 return null; 16296 } 16297 return findViewTraversal(id); 16298 } 16299 16300 /** 16301 * Finds a view by its unuque and stable accessibility id. 16302 * 16303 * @param accessibilityId The searched accessibility id. 16304 * @return The found view. 16305 */ 16306 final View findViewByAccessibilityId(int accessibilityId) { 16307 if (accessibilityId < 0) { 16308 return null; 16309 } 16310 return findViewByAccessibilityIdTraversal(accessibilityId); 16311 } 16312 16313 /** 16314 * Performs the traversal to find a view by its unuque and stable accessibility id. 16315 * 16316 * <strong>Note:</strong>This method does not stop at the root namespace 16317 * boundary since the user can touch the screen at an arbitrary location 16318 * potentially crossing the root namespace bounday which will send an 16319 * accessibility event to accessibility services and they should be able 16320 * to obtain the event source. Also accessibility ids are guaranteed to be 16321 * unique in the window. 16322 * 16323 * @param accessibilityId The accessibility id. 16324 * @return The found view. 16325 * 16326 * @hide 16327 */ 16328 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16329 if (getAccessibilityViewId() == accessibilityId) { 16330 return this; 16331 } 16332 return null; 16333 } 16334 16335 /** 16336 * Look for a child view with the given tag. If this view has the given 16337 * tag, return this view. 16338 * 16339 * @param tag The tag to search for, using "tag.equals(getTag())". 16340 * @return The View that has the given tag in the hierarchy or null 16341 */ 16342 public final View findViewWithTag(Object tag) { 16343 if (tag == null) { 16344 return null; 16345 } 16346 return findViewWithTagTraversal(tag); 16347 } 16348 16349 /** 16350 * {@hide} 16351 * Look for a child view that matches the specified predicate. 16352 * If this view matches the predicate, return this view. 16353 * 16354 * @param predicate The predicate to evaluate. 16355 * @return The first view that matches the predicate or null. 16356 */ 16357 public final View findViewByPredicate(Predicate<View> predicate) { 16358 return findViewByPredicateTraversal(predicate, null); 16359 } 16360 16361 /** 16362 * {@hide} 16363 * Look for a child view that matches the specified predicate, 16364 * starting with the specified view and its descendents and then 16365 * recusively searching the ancestors and siblings of that view 16366 * until this view is reached. 16367 * 16368 * This method is useful in cases where the predicate does not match 16369 * a single unique view (perhaps multiple views use the same id) 16370 * and we are trying to find the view that is "closest" in scope to the 16371 * starting view. 16372 * 16373 * @param start The view to start from. 16374 * @param predicate The predicate to evaluate. 16375 * @return The first view that matches the predicate or null. 16376 */ 16377 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 16378 View childToSkip = null; 16379 for (;;) { 16380 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 16381 if (view != null || start == this) { 16382 return view; 16383 } 16384 16385 ViewParent parent = start.getParent(); 16386 if (parent == null || !(parent instanceof View)) { 16387 return null; 16388 } 16389 16390 childToSkip = start; 16391 start = (View) parent; 16392 } 16393 } 16394 16395 /** 16396 * Sets the identifier for this view. The identifier does not have to be 16397 * unique in this view's hierarchy. The identifier should be a positive 16398 * number. 16399 * 16400 * @see #NO_ID 16401 * @see #getId() 16402 * @see #findViewById(int) 16403 * 16404 * @param id a number used to identify the view 16405 * 16406 * @attr ref android.R.styleable#View_id 16407 */ 16408 public void setId(int id) { 16409 mID = id; 16410 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 16411 mID = generateViewId(); 16412 } 16413 } 16414 16415 /** 16416 * {@hide} 16417 * 16418 * @param isRoot true if the view belongs to the root namespace, false 16419 * otherwise 16420 */ 16421 public void setIsRootNamespace(boolean isRoot) { 16422 if (isRoot) { 16423 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 16424 } else { 16425 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 16426 } 16427 } 16428 16429 /** 16430 * {@hide} 16431 * 16432 * @return true if the view belongs to the root namespace, false otherwise 16433 */ 16434 public boolean isRootNamespace() { 16435 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 16436 } 16437 16438 /** 16439 * Returns this view's identifier. 16440 * 16441 * @return a positive integer used to identify the view or {@link #NO_ID} 16442 * if the view has no ID 16443 * 16444 * @see #setId(int) 16445 * @see #findViewById(int) 16446 * @attr ref android.R.styleable#View_id 16447 */ 16448 @ViewDebug.CapturedViewProperty 16449 public int getId() { 16450 return mID; 16451 } 16452 16453 /** 16454 * Returns this view's tag. 16455 * 16456 * @return the Object stored in this view as a tag, or {@code null} if not 16457 * set 16458 * 16459 * @see #setTag(Object) 16460 * @see #getTag(int) 16461 */ 16462 @ViewDebug.ExportedProperty 16463 public Object getTag() { 16464 return mTag; 16465 } 16466 16467 /** 16468 * Sets the tag associated with this view. A tag can be used to mark 16469 * a view in its hierarchy and does not have to be unique within the 16470 * hierarchy. Tags can also be used to store data within a view without 16471 * resorting to another data structure. 16472 * 16473 * @param tag an Object to tag the view with 16474 * 16475 * @see #getTag() 16476 * @see #setTag(int, Object) 16477 */ 16478 public void setTag(final Object tag) { 16479 mTag = tag; 16480 } 16481 16482 /** 16483 * Returns the tag associated with this view and the specified key. 16484 * 16485 * @param key The key identifying the tag 16486 * 16487 * @return the Object stored in this view as a tag, or {@code null} if not 16488 * set 16489 * 16490 * @see #setTag(int, Object) 16491 * @see #getTag() 16492 */ 16493 public Object getTag(int key) { 16494 if (mKeyedTags != null) return mKeyedTags.get(key); 16495 return null; 16496 } 16497 16498 /** 16499 * Sets a tag associated with this view and a key. A tag can be used 16500 * to mark a view in its hierarchy and does not have to be unique within 16501 * the hierarchy. Tags can also be used to store data within a view 16502 * without resorting to another data structure. 16503 * 16504 * The specified key should be an id declared in the resources of the 16505 * application to ensure it is unique (see the <a 16506 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 16507 * Keys identified as belonging to 16508 * the Android framework or not associated with any package will cause 16509 * an {@link IllegalArgumentException} to be thrown. 16510 * 16511 * @param key The key identifying the tag 16512 * @param tag An Object to tag the view with 16513 * 16514 * @throws IllegalArgumentException If they specified key is not valid 16515 * 16516 * @see #setTag(Object) 16517 * @see #getTag(int) 16518 */ 16519 public void setTag(int key, final Object tag) { 16520 // If the package id is 0x00 or 0x01, it's either an undefined package 16521 // or a framework id 16522 if ((key >>> 24) < 2) { 16523 throw new IllegalArgumentException("The key must be an application-specific " 16524 + "resource id."); 16525 } 16526 16527 setKeyedTag(key, tag); 16528 } 16529 16530 /** 16531 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 16532 * framework id. 16533 * 16534 * @hide 16535 */ 16536 public void setTagInternal(int key, Object tag) { 16537 if ((key >>> 24) != 0x1) { 16538 throw new IllegalArgumentException("The key must be a framework-specific " 16539 + "resource id."); 16540 } 16541 16542 setKeyedTag(key, tag); 16543 } 16544 16545 private void setKeyedTag(int key, Object tag) { 16546 if (mKeyedTags == null) { 16547 mKeyedTags = new SparseArray<Object>(2); 16548 } 16549 16550 mKeyedTags.put(key, tag); 16551 } 16552 16553 /** 16554 * Prints information about this view in the log output, with the tag 16555 * {@link #VIEW_LOG_TAG}. 16556 * 16557 * @hide 16558 */ 16559 public void debug() { 16560 debug(0); 16561 } 16562 16563 /** 16564 * Prints information about this view in the log output, with the tag 16565 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 16566 * indentation defined by the <code>depth</code>. 16567 * 16568 * @param depth the indentation level 16569 * 16570 * @hide 16571 */ 16572 protected void debug(int depth) { 16573 String output = debugIndent(depth - 1); 16574 16575 output += "+ " + this; 16576 int id = getId(); 16577 if (id != -1) { 16578 output += " (id=" + id + ")"; 16579 } 16580 Object tag = getTag(); 16581 if (tag != null) { 16582 output += " (tag=" + tag + ")"; 16583 } 16584 Log.d(VIEW_LOG_TAG, output); 16585 16586 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 16587 output = debugIndent(depth) + " FOCUSED"; 16588 Log.d(VIEW_LOG_TAG, output); 16589 } 16590 16591 output = debugIndent(depth); 16592 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 16593 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 16594 + "} "; 16595 Log.d(VIEW_LOG_TAG, output); 16596 16597 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 16598 || mPaddingBottom != 0) { 16599 output = debugIndent(depth); 16600 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 16601 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 16602 Log.d(VIEW_LOG_TAG, output); 16603 } 16604 16605 output = debugIndent(depth); 16606 output += "mMeasureWidth=" + mMeasuredWidth + 16607 " mMeasureHeight=" + mMeasuredHeight; 16608 Log.d(VIEW_LOG_TAG, output); 16609 16610 output = debugIndent(depth); 16611 if (mLayoutParams == null) { 16612 output += "BAD! no layout params"; 16613 } else { 16614 output = mLayoutParams.debug(output); 16615 } 16616 Log.d(VIEW_LOG_TAG, output); 16617 16618 output = debugIndent(depth); 16619 output += "flags={"; 16620 output += View.printFlags(mViewFlags); 16621 output += "}"; 16622 Log.d(VIEW_LOG_TAG, output); 16623 16624 output = debugIndent(depth); 16625 output += "privateFlags={"; 16626 output += View.printPrivateFlags(mPrivateFlags); 16627 output += "}"; 16628 Log.d(VIEW_LOG_TAG, output); 16629 } 16630 16631 /** 16632 * Creates a string of whitespaces used for indentation. 16633 * 16634 * @param depth the indentation level 16635 * @return a String containing (depth * 2 + 3) * 2 white spaces 16636 * 16637 * @hide 16638 */ 16639 protected static String debugIndent(int depth) { 16640 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 16641 for (int i = 0; i < (depth * 2) + 3; i++) { 16642 spaces.append(' ').append(' '); 16643 } 16644 return spaces.toString(); 16645 } 16646 16647 /** 16648 * <p>Return the offset of the widget's text baseline from the widget's top 16649 * boundary. If this widget does not support baseline alignment, this 16650 * method returns -1. </p> 16651 * 16652 * @return the offset of the baseline within the widget's bounds or -1 16653 * if baseline alignment is not supported 16654 */ 16655 @ViewDebug.ExportedProperty(category = "layout") 16656 public int getBaseline() { 16657 return -1; 16658 } 16659 16660 /** 16661 * Returns whether the view hierarchy is currently undergoing a layout pass. This 16662 * information is useful to avoid situations such as calling {@link #requestLayout()} during 16663 * a layout pass. 16664 * 16665 * @return whether the view hierarchy is currently undergoing a layout pass 16666 */ 16667 public boolean isInLayout() { 16668 ViewRootImpl viewRoot = getViewRootImpl(); 16669 return (viewRoot != null && viewRoot.isInLayout()); 16670 } 16671 16672 /** 16673 * Call this when something has changed which has invalidated the 16674 * layout of this view. This will schedule a layout pass of the view 16675 * tree. This should not be called while the view hierarchy is currently in a layout 16676 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 16677 * end of the current layout pass (and then layout will run again) or after the current 16678 * frame is drawn and the next layout occurs. 16679 * 16680 * <p>Subclasses which override this method should call the superclass method to 16681 * handle possible request-during-layout errors correctly.</p> 16682 */ 16683 public void requestLayout() { 16684 if (mMeasureCache != null) mMeasureCache.clear(); 16685 16686 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 16687 // Only trigger request-during-layout logic if this is the view requesting it, 16688 // not the views in its parent hierarchy 16689 ViewRootImpl viewRoot = getViewRootImpl(); 16690 if (viewRoot != null && viewRoot.isInLayout()) { 16691 if (!viewRoot.requestLayoutDuringLayout(this)) { 16692 return; 16693 } 16694 } 16695 mAttachInfo.mViewRequestingLayout = this; 16696 } 16697 16698 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16699 mPrivateFlags |= PFLAG_INVALIDATED; 16700 16701 if (mParent != null && !mParent.isLayoutRequested()) { 16702 mParent.requestLayout(); 16703 } 16704 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 16705 mAttachInfo.mViewRequestingLayout = null; 16706 } 16707 } 16708 16709 /** 16710 * Forces this view to be laid out during the next layout pass. 16711 * This method does not call requestLayout() or forceLayout() 16712 * on the parent. 16713 */ 16714 public void forceLayout() { 16715 if (mMeasureCache != null) mMeasureCache.clear(); 16716 16717 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 16718 mPrivateFlags |= PFLAG_INVALIDATED; 16719 } 16720 16721 /** 16722 * <p> 16723 * This is called to find out how big a view should be. The parent 16724 * supplies constraint information in the width and height parameters. 16725 * </p> 16726 * 16727 * <p> 16728 * The actual measurement work of a view is performed in 16729 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 16730 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 16731 * </p> 16732 * 16733 * 16734 * @param widthMeasureSpec Horizontal space requirements as imposed by the 16735 * parent 16736 * @param heightMeasureSpec Vertical space requirements as imposed by the 16737 * parent 16738 * 16739 * @see #onMeasure(int, int) 16740 */ 16741 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 16742 boolean optical = isLayoutModeOptical(this); 16743 if (optical != isLayoutModeOptical(mParent)) { 16744 Insets insets = getOpticalInsets(); 16745 int oWidth = insets.left + insets.right; 16746 int oHeight = insets.top + insets.bottom; 16747 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 16748 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 16749 } 16750 16751 // Suppress sign extension for the low bytes 16752 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 16753 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 16754 16755 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 16756 widthMeasureSpec != mOldWidthMeasureSpec || 16757 heightMeasureSpec != mOldHeightMeasureSpec) { 16758 16759 // first clears the measured dimension flag 16760 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 16761 16762 resolveRtlPropertiesIfNeeded(); 16763 16764 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 16765 mMeasureCache.indexOfKey(key); 16766 if (cacheIndex < 0 || sIgnoreMeasureCache) { 16767 // measure ourselves, this should set the measured dimension flag back 16768 onMeasure(widthMeasureSpec, heightMeasureSpec); 16769 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16770 } else { 16771 long value = mMeasureCache.valueAt(cacheIndex); 16772 // Casting a long to int drops the high 32 bits, no mask needed 16773 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 16774 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16775 } 16776 16777 // flag not set, setMeasuredDimension() was not invoked, we raise 16778 // an exception to warn the developer 16779 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 16780 throw new IllegalStateException("onMeasure() did not set the" 16781 + " measured dimension by calling" 16782 + " setMeasuredDimension()"); 16783 } 16784 16785 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 16786 } 16787 16788 mOldWidthMeasureSpec = widthMeasureSpec; 16789 mOldHeightMeasureSpec = heightMeasureSpec; 16790 16791 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 16792 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 16793 } 16794 16795 /** 16796 * <p> 16797 * Measure the view and its content to determine the measured width and the 16798 * measured height. This method is invoked by {@link #measure(int, int)} and 16799 * should be overriden by subclasses to provide accurate and efficient 16800 * measurement of their contents. 16801 * </p> 16802 * 16803 * <p> 16804 * <strong>CONTRACT:</strong> When overriding this method, you 16805 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 16806 * measured width and height of this view. Failure to do so will trigger an 16807 * <code>IllegalStateException</code>, thrown by 16808 * {@link #measure(int, int)}. Calling the superclass' 16809 * {@link #onMeasure(int, int)} is a valid use. 16810 * </p> 16811 * 16812 * <p> 16813 * The base class implementation of measure defaults to the background size, 16814 * unless a larger size is allowed by the MeasureSpec. Subclasses should 16815 * override {@link #onMeasure(int, int)} to provide better measurements of 16816 * their content. 16817 * </p> 16818 * 16819 * <p> 16820 * If this method is overridden, it is the subclass's responsibility to make 16821 * sure the measured height and width are at least the view's minimum height 16822 * and width ({@link #getSuggestedMinimumHeight()} and 16823 * {@link #getSuggestedMinimumWidth()}). 16824 * </p> 16825 * 16826 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 16827 * The requirements are encoded with 16828 * {@link android.view.View.MeasureSpec}. 16829 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 16830 * The requirements are encoded with 16831 * {@link android.view.View.MeasureSpec}. 16832 * 16833 * @see #getMeasuredWidth() 16834 * @see #getMeasuredHeight() 16835 * @see #setMeasuredDimension(int, int) 16836 * @see #getSuggestedMinimumHeight() 16837 * @see #getSuggestedMinimumWidth() 16838 * @see android.view.View.MeasureSpec#getMode(int) 16839 * @see android.view.View.MeasureSpec#getSize(int) 16840 */ 16841 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 16842 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 16843 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 16844 } 16845 16846 /** 16847 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 16848 * measured width and measured height. Failing to do so will trigger an 16849 * exception at measurement time.</p> 16850 * 16851 * @param measuredWidth The measured width of this view. May be a complex 16852 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16853 * {@link #MEASURED_STATE_TOO_SMALL}. 16854 * @param measuredHeight The measured height of this view. May be a complex 16855 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16856 * {@link #MEASURED_STATE_TOO_SMALL}. 16857 */ 16858 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 16859 boolean optical = isLayoutModeOptical(this); 16860 if (optical != isLayoutModeOptical(mParent)) { 16861 Insets insets = getOpticalInsets(); 16862 int opticalWidth = insets.left + insets.right; 16863 int opticalHeight = insets.top + insets.bottom; 16864 16865 measuredWidth += optical ? opticalWidth : -opticalWidth; 16866 measuredHeight += optical ? opticalHeight : -opticalHeight; 16867 } 16868 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 16869 } 16870 16871 /** 16872 * Sets the measured dimension without extra processing for things like optical bounds. 16873 * Useful for reapplying consistent values that have already been cooked with adjustments 16874 * for optical bounds, etc. such as those from the measurement cache. 16875 * 16876 * @param measuredWidth The measured width of this view. May be a complex 16877 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16878 * {@link #MEASURED_STATE_TOO_SMALL}. 16879 * @param measuredHeight The measured height of this view. May be a complex 16880 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 16881 * {@link #MEASURED_STATE_TOO_SMALL}. 16882 */ 16883 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 16884 mMeasuredWidth = measuredWidth; 16885 mMeasuredHeight = measuredHeight; 16886 16887 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 16888 } 16889 16890 /** 16891 * Merge two states as returned by {@link #getMeasuredState()}. 16892 * @param curState The current state as returned from a view or the result 16893 * of combining multiple views. 16894 * @param newState The new view state to combine. 16895 * @return Returns a new integer reflecting the combination of the two 16896 * states. 16897 */ 16898 public static int combineMeasuredStates(int curState, int newState) { 16899 return curState | newState; 16900 } 16901 16902 /** 16903 * Version of {@link #resolveSizeAndState(int, int, int)} 16904 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 16905 */ 16906 public static int resolveSize(int size, int measureSpec) { 16907 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 16908 } 16909 16910 /** 16911 * Utility to reconcile a desired size and state, with constraints imposed 16912 * by a MeasureSpec. Will take the desired size, unless a different size 16913 * is imposed by the constraints. The returned value is a compound integer, 16914 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 16915 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 16916 * size is smaller than the size the view wants to be. 16917 * 16918 * @param size How big the view wants to be 16919 * @param measureSpec Constraints imposed by the parent 16920 * @return Size information bit mask as defined by 16921 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 16922 */ 16923 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 16924 int result = size; 16925 int specMode = MeasureSpec.getMode(measureSpec); 16926 int specSize = MeasureSpec.getSize(measureSpec); 16927 switch (specMode) { 16928 case MeasureSpec.UNSPECIFIED: 16929 result = size; 16930 break; 16931 case MeasureSpec.AT_MOST: 16932 if (specSize < size) { 16933 result = specSize | MEASURED_STATE_TOO_SMALL; 16934 } else { 16935 result = size; 16936 } 16937 break; 16938 case MeasureSpec.EXACTLY: 16939 result = specSize; 16940 break; 16941 } 16942 return result | (childMeasuredState&MEASURED_STATE_MASK); 16943 } 16944 16945 /** 16946 * Utility to return a default size. Uses the supplied size if the 16947 * MeasureSpec imposed no constraints. Will get larger if allowed 16948 * by the MeasureSpec. 16949 * 16950 * @param size Default size for this view 16951 * @param measureSpec Constraints imposed by the parent 16952 * @return The size this view should be. 16953 */ 16954 public static int getDefaultSize(int size, int measureSpec) { 16955 int result = size; 16956 int specMode = MeasureSpec.getMode(measureSpec); 16957 int specSize = MeasureSpec.getSize(measureSpec); 16958 16959 switch (specMode) { 16960 case MeasureSpec.UNSPECIFIED: 16961 result = size; 16962 break; 16963 case MeasureSpec.AT_MOST: 16964 case MeasureSpec.EXACTLY: 16965 result = specSize; 16966 break; 16967 } 16968 return result; 16969 } 16970 16971 /** 16972 * Returns the suggested minimum height that the view should use. This 16973 * returns the maximum of the view's minimum height 16974 * and the background's minimum height 16975 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 16976 * <p> 16977 * When being used in {@link #onMeasure(int, int)}, the caller should still 16978 * ensure the returned height is within the requirements of the parent. 16979 * 16980 * @return The suggested minimum height of the view. 16981 */ 16982 protected int getSuggestedMinimumHeight() { 16983 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 16984 16985 } 16986 16987 /** 16988 * Returns the suggested minimum width that the view should use. This 16989 * returns the maximum of the view's minimum width) 16990 * and the background's minimum width 16991 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 16992 * <p> 16993 * When being used in {@link #onMeasure(int, int)}, the caller should still 16994 * ensure the returned width is within the requirements of the parent. 16995 * 16996 * @return The suggested minimum width of the view. 16997 */ 16998 protected int getSuggestedMinimumWidth() { 16999 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17000 } 17001 17002 /** 17003 * Returns the minimum height of the view. 17004 * 17005 * @return the minimum height the view will try to be. 17006 * 17007 * @see #setMinimumHeight(int) 17008 * 17009 * @attr ref android.R.styleable#View_minHeight 17010 */ 17011 public int getMinimumHeight() { 17012 return mMinHeight; 17013 } 17014 17015 /** 17016 * Sets the minimum height of the view. It is not guaranteed the view will 17017 * be able to achieve this minimum height (for example, if its parent layout 17018 * constrains it with less available height). 17019 * 17020 * @param minHeight The minimum height the view will try to be. 17021 * 17022 * @see #getMinimumHeight() 17023 * 17024 * @attr ref android.R.styleable#View_minHeight 17025 */ 17026 public void setMinimumHeight(int minHeight) { 17027 mMinHeight = minHeight; 17028 requestLayout(); 17029 } 17030 17031 /** 17032 * Returns the minimum width of the view. 17033 * 17034 * @return the minimum width the view will try to be. 17035 * 17036 * @see #setMinimumWidth(int) 17037 * 17038 * @attr ref android.R.styleable#View_minWidth 17039 */ 17040 public int getMinimumWidth() { 17041 return mMinWidth; 17042 } 17043 17044 /** 17045 * Sets the minimum width of the view. It is not guaranteed the view will 17046 * be able to achieve this minimum width (for example, if its parent layout 17047 * constrains it with less available width). 17048 * 17049 * @param minWidth The minimum width the view will try to be. 17050 * 17051 * @see #getMinimumWidth() 17052 * 17053 * @attr ref android.R.styleable#View_minWidth 17054 */ 17055 public void setMinimumWidth(int minWidth) { 17056 mMinWidth = minWidth; 17057 requestLayout(); 17058 17059 } 17060 17061 /** 17062 * Get the animation currently associated with this view. 17063 * 17064 * @return The animation that is currently playing or 17065 * scheduled to play for this view. 17066 */ 17067 public Animation getAnimation() { 17068 return mCurrentAnimation; 17069 } 17070 17071 /** 17072 * Start the specified animation now. 17073 * 17074 * @param animation the animation to start now 17075 */ 17076 public void startAnimation(Animation animation) { 17077 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17078 setAnimation(animation); 17079 invalidateParentCaches(); 17080 invalidate(true); 17081 } 17082 17083 /** 17084 * Cancels any animations for this view. 17085 */ 17086 public void clearAnimation() { 17087 if (mCurrentAnimation != null) { 17088 mCurrentAnimation.detach(); 17089 } 17090 mCurrentAnimation = null; 17091 invalidateParentIfNeeded(); 17092 } 17093 17094 /** 17095 * Sets the next animation to play for this view. 17096 * If you want the animation to play immediately, use 17097 * {@link #startAnimation(android.view.animation.Animation)} instead. 17098 * This method provides allows fine-grained 17099 * control over the start time and invalidation, but you 17100 * must make sure that 1) the animation has a start time set, and 17101 * 2) the view's parent (which controls animations on its children) 17102 * will be invalidated when the animation is supposed to 17103 * start. 17104 * 17105 * @param animation The next animation, or null. 17106 */ 17107 public void setAnimation(Animation animation) { 17108 mCurrentAnimation = animation; 17109 17110 if (animation != null) { 17111 // If the screen is off assume the animation start time is now instead of 17112 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17113 // would cause the animation to start when the screen turns back on 17114 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17115 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17116 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17117 } 17118 animation.reset(); 17119 } 17120 } 17121 17122 /** 17123 * Invoked by a parent ViewGroup to notify the start of the animation 17124 * currently associated with this view. If you override this method, 17125 * always call super.onAnimationStart(); 17126 * 17127 * @see #setAnimation(android.view.animation.Animation) 17128 * @see #getAnimation() 17129 */ 17130 protected void onAnimationStart() { 17131 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17132 } 17133 17134 /** 17135 * Invoked by a parent ViewGroup to notify the end of the animation 17136 * currently associated with this view. If you override this method, 17137 * always call super.onAnimationEnd(); 17138 * 17139 * @see #setAnimation(android.view.animation.Animation) 17140 * @see #getAnimation() 17141 */ 17142 protected void onAnimationEnd() { 17143 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17144 } 17145 17146 /** 17147 * Invoked if there is a Transform that involves alpha. Subclass that can 17148 * draw themselves with the specified alpha should return true, and then 17149 * respect that alpha when their onDraw() is called. If this returns false 17150 * then the view may be redirected to draw into an offscreen buffer to 17151 * fulfill the request, which will look fine, but may be slower than if the 17152 * subclass handles it internally. The default implementation returns false. 17153 * 17154 * @param alpha The alpha (0..255) to apply to the view's drawing 17155 * @return true if the view can draw with the specified alpha. 17156 */ 17157 protected boolean onSetAlpha(int alpha) { 17158 return false; 17159 } 17160 17161 /** 17162 * This is used by the RootView to perform an optimization when 17163 * the view hierarchy contains one or several SurfaceView. 17164 * SurfaceView is always considered transparent, but its children are not, 17165 * therefore all View objects remove themselves from the global transparent 17166 * region (passed as a parameter to this function). 17167 * 17168 * @param region The transparent region for this ViewAncestor (window). 17169 * 17170 * @return Returns true if the effective visibility of the view at this 17171 * point is opaque, regardless of the transparent region; returns false 17172 * if it is possible for underlying windows to be seen behind the view. 17173 * 17174 * {@hide} 17175 */ 17176 public boolean gatherTransparentRegion(Region region) { 17177 final AttachInfo attachInfo = mAttachInfo; 17178 if (region != null && attachInfo != null) { 17179 final int pflags = mPrivateFlags; 17180 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17181 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17182 // remove it from the transparent region. 17183 final int[] location = attachInfo.mTransparentLocation; 17184 getLocationInWindow(location); 17185 region.op(location[0], location[1], location[0] + mRight - mLeft, 17186 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17187 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null) { 17188 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17189 // exists, so we remove the background drawable's non-transparent 17190 // parts from this transparent region. 17191 applyDrawableToTransparentRegion(mBackground, region); 17192 } 17193 } 17194 return true; 17195 } 17196 17197 /** 17198 * Play a sound effect for this view. 17199 * 17200 * <p>The framework will play sound effects for some built in actions, such as 17201 * clicking, but you may wish to play these effects in your widget, 17202 * for instance, for internal navigation. 17203 * 17204 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17205 * {@link #isSoundEffectsEnabled()} is true. 17206 * 17207 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17208 */ 17209 public void playSoundEffect(int soundConstant) { 17210 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17211 return; 17212 } 17213 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17214 } 17215 17216 /** 17217 * BZZZTT!!1! 17218 * 17219 * <p>Provide haptic feedback to the user for this view. 17220 * 17221 * <p>The framework will provide haptic feedback for some built in actions, 17222 * such as long presses, but you may wish to provide feedback for your 17223 * own widget. 17224 * 17225 * <p>The feedback will only be performed if 17226 * {@link #isHapticFeedbackEnabled()} is true. 17227 * 17228 * @param feedbackConstant One of the constants defined in 17229 * {@link HapticFeedbackConstants} 17230 */ 17231 public boolean performHapticFeedback(int feedbackConstant) { 17232 return performHapticFeedback(feedbackConstant, 0); 17233 } 17234 17235 /** 17236 * BZZZTT!!1! 17237 * 17238 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17239 * 17240 * @param feedbackConstant One of the constants defined in 17241 * {@link HapticFeedbackConstants} 17242 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17243 */ 17244 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17245 if (mAttachInfo == null) { 17246 return false; 17247 } 17248 //noinspection SimplifiableIfStatement 17249 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17250 && !isHapticFeedbackEnabled()) { 17251 return false; 17252 } 17253 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17254 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17255 } 17256 17257 /** 17258 * Request that the visibility of the status bar or other screen/window 17259 * decorations be changed. 17260 * 17261 * <p>This method is used to put the over device UI into temporary modes 17262 * where the user's attention is focused more on the application content, 17263 * by dimming or hiding surrounding system affordances. This is typically 17264 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17265 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17266 * to be placed behind the action bar (and with these flags other system 17267 * affordances) so that smooth transitions between hiding and showing them 17268 * can be done. 17269 * 17270 * <p>Two representative examples of the use of system UI visibility is 17271 * implementing a content browsing application (like a magazine reader) 17272 * and a video playing application. 17273 * 17274 * <p>The first code shows a typical implementation of a View in a content 17275 * browsing application. In this implementation, the application goes 17276 * into a content-oriented mode by hiding the status bar and action bar, 17277 * and putting the navigation elements into lights out mode. The user can 17278 * then interact with content while in this mode. Such an application should 17279 * provide an easy way for the user to toggle out of the mode (such as to 17280 * check information in the status bar or access notifications). In the 17281 * implementation here, this is done simply by tapping on the content. 17282 * 17283 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17284 * content} 17285 * 17286 * <p>This second code sample shows a typical implementation of a View 17287 * in a video playing application. In this situation, while the video is 17288 * playing the application would like to go into a complete full-screen mode, 17289 * to use as much of the display as possible for the video. When in this state 17290 * the user can not interact with the application; the system intercepts 17291 * touching on the screen to pop the UI out of full screen mode. See 17292 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17293 * 17294 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17295 * content} 17296 * 17297 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17298 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17299 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17300 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17301 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17302 */ 17303 public void setSystemUiVisibility(int visibility) { 17304 if (visibility != mSystemUiVisibility) { 17305 mSystemUiVisibility = visibility; 17306 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17307 mParent.recomputeViewAttributes(this); 17308 } 17309 } 17310 } 17311 17312 /** 17313 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17314 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17315 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17316 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17317 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17318 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17319 */ 17320 public int getSystemUiVisibility() { 17321 return mSystemUiVisibility; 17322 } 17323 17324 /** 17325 * Returns the current system UI visibility that is currently set for 17326 * the entire window. This is the combination of the 17327 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17328 * views in the window. 17329 */ 17330 public int getWindowSystemUiVisibility() { 17331 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17332 } 17333 17334 /** 17335 * Override to find out when the window's requested system UI visibility 17336 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17337 * This is different from the callbacks received through 17338 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 17339 * in that this is only telling you about the local request of the window, 17340 * not the actual values applied by the system. 17341 */ 17342 public void onWindowSystemUiVisibilityChanged(int visible) { 17343 } 17344 17345 /** 17346 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 17347 * the view hierarchy. 17348 */ 17349 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 17350 onWindowSystemUiVisibilityChanged(visible); 17351 } 17352 17353 /** 17354 * Set a listener to receive callbacks when the visibility of the system bar changes. 17355 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 17356 */ 17357 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 17358 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 17359 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17360 mParent.recomputeViewAttributes(this); 17361 } 17362 } 17363 17364 /** 17365 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 17366 * the view hierarchy. 17367 */ 17368 public void dispatchSystemUiVisibilityChanged(int visibility) { 17369 ListenerInfo li = mListenerInfo; 17370 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 17371 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 17372 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 17373 } 17374 } 17375 17376 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 17377 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 17378 if (val != mSystemUiVisibility) { 17379 setSystemUiVisibility(val); 17380 return true; 17381 } 17382 return false; 17383 } 17384 17385 /** @hide */ 17386 public void setDisabledSystemUiVisibility(int flags) { 17387 if (mAttachInfo != null) { 17388 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 17389 mAttachInfo.mDisabledSystemUiVisibility = flags; 17390 if (mParent != null) { 17391 mParent.recomputeViewAttributes(this); 17392 } 17393 } 17394 } 17395 } 17396 17397 /** 17398 * Creates an image that the system displays during the drag and drop 17399 * operation. This is called a "drag shadow". The default implementation 17400 * for a DragShadowBuilder based on a View returns an image that has exactly the same 17401 * appearance as the given View. The default also positions the center of the drag shadow 17402 * directly under the touch point. If no View is provided (the constructor with no parameters 17403 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 17404 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 17405 * default is an invisible drag shadow. 17406 * <p> 17407 * You are not required to use the View you provide to the constructor as the basis of the 17408 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 17409 * anything you want as the drag shadow. 17410 * </p> 17411 * <p> 17412 * You pass a DragShadowBuilder object to the system when you start the drag. The system 17413 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 17414 * size and position of the drag shadow. It uses this data to construct a 17415 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 17416 * so that your application can draw the shadow image in the Canvas. 17417 * </p> 17418 * 17419 * <div class="special reference"> 17420 * <h3>Developer Guides</h3> 17421 * <p>For a guide to implementing drag and drop features, read the 17422 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 17423 * </div> 17424 */ 17425 public static class DragShadowBuilder { 17426 private final WeakReference<View> mView; 17427 17428 /** 17429 * Constructs a shadow image builder based on a View. By default, the resulting drag 17430 * shadow will have the same appearance and dimensions as the View, with the touch point 17431 * over the center of the View. 17432 * @param view A View. Any View in scope can be used. 17433 */ 17434 public DragShadowBuilder(View view) { 17435 mView = new WeakReference<View>(view); 17436 } 17437 17438 /** 17439 * Construct a shadow builder object with no associated View. This 17440 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 17441 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 17442 * to supply the drag shadow's dimensions and appearance without 17443 * reference to any View object. If they are not overridden, then the result is an 17444 * invisible drag shadow. 17445 */ 17446 public DragShadowBuilder() { 17447 mView = new WeakReference<View>(null); 17448 } 17449 17450 /** 17451 * Returns the View object that had been passed to the 17452 * {@link #View.DragShadowBuilder(View)} 17453 * constructor. If that View parameter was {@code null} or if the 17454 * {@link #View.DragShadowBuilder()} 17455 * constructor was used to instantiate the builder object, this method will return 17456 * null. 17457 * 17458 * @return The View object associate with this builder object. 17459 */ 17460 @SuppressWarnings({"JavadocReference"}) 17461 final public View getView() { 17462 return mView.get(); 17463 } 17464 17465 /** 17466 * Provides the metrics for the shadow image. These include the dimensions of 17467 * the shadow image, and the point within that shadow that should 17468 * be centered under the touch location while dragging. 17469 * <p> 17470 * The default implementation sets the dimensions of the shadow to be the 17471 * same as the dimensions of the View itself and centers the shadow under 17472 * the touch point. 17473 * </p> 17474 * 17475 * @param shadowSize A {@link android.graphics.Point} containing the width and height 17476 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 17477 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 17478 * image. 17479 * 17480 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 17481 * shadow image that should be underneath the touch point during the drag and drop 17482 * operation. Your application must set {@link android.graphics.Point#x} to the 17483 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 17484 */ 17485 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 17486 final View view = mView.get(); 17487 if (view != null) { 17488 shadowSize.set(view.getWidth(), view.getHeight()); 17489 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 17490 } else { 17491 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 17492 } 17493 } 17494 17495 /** 17496 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 17497 * based on the dimensions it received from the 17498 * {@link #onProvideShadowMetrics(Point, Point)} callback. 17499 * 17500 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 17501 */ 17502 public void onDrawShadow(Canvas canvas) { 17503 final View view = mView.get(); 17504 if (view != null) { 17505 view.draw(canvas); 17506 } else { 17507 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 17508 } 17509 } 17510 } 17511 17512 /** 17513 * Starts a drag and drop operation. When your application calls this method, it passes a 17514 * {@link android.view.View.DragShadowBuilder} object to the system. The 17515 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 17516 * to get metrics for the drag shadow, and then calls the object's 17517 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 17518 * <p> 17519 * Once the system has the drag shadow, it begins the drag and drop operation by sending 17520 * drag events to all the View objects in your application that are currently visible. It does 17521 * this either by calling the View object's drag listener (an implementation of 17522 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 17523 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 17524 * Both are passed a {@link android.view.DragEvent} object that has a 17525 * {@link android.view.DragEvent#getAction()} value of 17526 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 17527 * </p> 17528 * <p> 17529 * Your application can invoke startDrag() on any attached View object. The View object does not 17530 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 17531 * be related to the View the user selected for dragging. 17532 * </p> 17533 * @param data A {@link android.content.ClipData} object pointing to the data to be 17534 * transferred by the drag and drop operation. 17535 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 17536 * drag shadow. 17537 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 17538 * drop operation. This Object is put into every DragEvent object sent by the system during the 17539 * current drag. 17540 * <p> 17541 * myLocalState is a lightweight mechanism for the sending information from the dragged View 17542 * to the target Views. For example, it can contain flags that differentiate between a 17543 * a copy operation and a move operation. 17544 * </p> 17545 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 17546 * so the parameter should be set to 0. 17547 * @return {@code true} if the method completes successfully, or 17548 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 17549 * do a drag, and so no drag operation is in progress. 17550 */ 17551 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 17552 Object myLocalState, int flags) { 17553 if (ViewDebug.DEBUG_DRAG) { 17554 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 17555 } 17556 boolean okay = false; 17557 17558 Point shadowSize = new Point(); 17559 Point shadowTouchPoint = new Point(); 17560 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 17561 17562 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 17563 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 17564 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 17565 } 17566 17567 if (ViewDebug.DEBUG_DRAG) { 17568 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 17569 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 17570 } 17571 Surface surface = new Surface(); 17572 try { 17573 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 17574 flags, shadowSize.x, shadowSize.y, surface); 17575 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 17576 + " surface=" + surface); 17577 if (token != null) { 17578 Canvas canvas = surface.lockCanvas(null); 17579 try { 17580 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 17581 shadowBuilder.onDrawShadow(canvas); 17582 } finally { 17583 surface.unlockCanvasAndPost(canvas); 17584 } 17585 17586 final ViewRootImpl root = getViewRootImpl(); 17587 17588 // Cache the local state object for delivery with DragEvents 17589 root.setLocalDragState(myLocalState); 17590 17591 // repurpose 'shadowSize' for the last touch point 17592 root.getLastTouchPoint(shadowSize); 17593 17594 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 17595 shadowSize.x, shadowSize.y, 17596 shadowTouchPoint.x, shadowTouchPoint.y, data); 17597 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 17598 17599 // Off and running! Release our local surface instance; the drag 17600 // shadow surface is now managed by the system process. 17601 surface.release(); 17602 } 17603 } catch (Exception e) { 17604 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 17605 surface.destroy(); 17606 } 17607 17608 return okay; 17609 } 17610 17611 /** 17612 * Handles drag events sent by the system following a call to 17613 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 17614 *<p> 17615 * When the system calls this method, it passes a 17616 * {@link android.view.DragEvent} object. A call to 17617 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 17618 * in DragEvent. The method uses these to determine what is happening in the drag and drop 17619 * operation. 17620 * @param event The {@link android.view.DragEvent} sent by the system. 17621 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 17622 * in DragEvent, indicating the type of drag event represented by this object. 17623 * @return {@code true} if the method was successful, otherwise {@code false}. 17624 * <p> 17625 * The method should return {@code true} in response to an action type of 17626 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 17627 * operation. 17628 * </p> 17629 * <p> 17630 * The method should also return {@code true} in response to an action type of 17631 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 17632 * {@code false} if it didn't. 17633 * </p> 17634 */ 17635 public boolean onDragEvent(DragEvent event) { 17636 return false; 17637 } 17638 17639 /** 17640 * Detects if this View is enabled and has a drag event listener. 17641 * If both are true, then it calls the drag event listener with the 17642 * {@link android.view.DragEvent} it received. If the drag event listener returns 17643 * {@code true}, then dispatchDragEvent() returns {@code true}. 17644 * <p> 17645 * For all other cases, the method calls the 17646 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 17647 * method and returns its result. 17648 * </p> 17649 * <p> 17650 * This ensures that a drag event is always consumed, even if the View does not have a drag 17651 * event listener. However, if the View has a listener and the listener returns true, then 17652 * onDragEvent() is not called. 17653 * </p> 17654 */ 17655 public boolean dispatchDragEvent(DragEvent event) { 17656 ListenerInfo li = mListenerInfo; 17657 //noinspection SimplifiableIfStatement 17658 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 17659 && li.mOnDragListener.onDrag(this, event)) { 17660 return true; 17661 } 17662 return onDragEvent(event); 17663 } 17664 17665 boolean canAcceptDrag() { 17666 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 17667 } 17668 17669 /** 17670 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 17671 * it is ever exposed at all. 17672 * @hide 17673 */ 17674 public void onCloseSystemDialogs(String reason) { 17675 } 17676 17677 /** 17678 * Given a Drawable whose bounds have been set to draw into this view, 17679 * update a Region being computed for 17680 * {@link #gatherTransparentRegion(android.graphics.Region)} so 17681 * that any non-transparent parts of the Drawable are removed from the 17682 * given transparent region. 17683 * 17684 * @param dr The Drawable whose transparency is to be applied to the region. 17685 * @param region A Region holding the current transparency information, 17686 * where any parts of the region that are set are considered to be 17687 * transparent. On return, this region will be modified to have the 17688 * transparency information reduced by the corresponding parts of the 17689 * Drawable that are not transparent. 17690 * {@hide} 17691 */ 17692 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 17693 if (DBG) { 17694 Log.i("View", "Getting transparent region for: " + this); 17695 } 17696 final Region r = dr.getTransparentRegion(); 17697 final Rect db = dr.getBounds(); 17698 final AttachInfo attachInfo = mAttachInfo; 17699 if (r != null && attachInfo != null) { 17700 final int w = getRight()-getLeft(); 17701 final int h = getBottom()-getTop(); 17702 if (db.left > 0) { 17703 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 17704 r.op(0, 0, db.left, h, Region.Op.UNION); 17705 } 17706 if (db.right < w) { 17707 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 17708 r.op(db.right, 0, w, h, Region.Op.UNION); 17709 } 17710 if (db.top > 0) { 17711 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 17712 r.op(0, 0, w, db.top, Region.Op.UNION); 17713 } 17714 if (db.bottom < h) { 17715 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 17716 r.op(0, db.bottom, w, h, Region.Op.UNION); 17717 } 17718 final int[] location = attachInfo.mTransparentLocation; 17719 getLocationInWindow(location); 17720 r.translate(location[0], location[1]); 17721 region.op(r, Region.Op.INTERSECT); 17722 } else { 17723 region.op(db, Region.Op.DIFFERENCE); 17724 } 17725 } 17726 17727 private void checkForLongClick(int delayOffset) { 17728 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 17729 mHasPerformedLongPress = false; 17730 17731 if (mPendingCheckForLongPress == null) { 17732 mPendingCheckForLongPress = new CheckForLongPress(); 17733 } 17734 mPendingCheckForLongPress.rememberWindowAttachCount(); 17735 postDelayed(mPendingCheckForLongPress, 17736 ViewConfiguration.getLongPressTimeout() - delayOffset); 17737 } 17738 } 17739 17740 /** 17741 * Inflate a view from an XML resource. This convenience method wraps the {@link 17742 * LayoutInflater} class, which provides a full range of options for view inflation. 17743 * 17744 * @param context The Context object for your activity or application. 17745 * @param resource The resource ID to inflate 17746 * @param root A view group that will be the parent. Used to properly inflate the 17747 * layout_* parameters. 17748 * @see LayoutInflater 17749 */ 17750 public static View inflate(Context context, int resource, ViewGroup root) { 17751 LayoutInflater factory = LayoutInflater.from(context); 17752 return factory.inflate(resource, root); 17753 } 17754 17755 /** 17756 * Scroll the view with standard behavior for scrolling beyond the normal 17757 * content boundaries. Views that call this method should override 17758 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 17759 * results of an over-scroll operation. 17760 * 17761 * Views can use this method to handle any touch or fling-based scrolling. 17762 * 17763 * @param deltaX Change in X in pixels 17764 * @param deltaY Change in Y in pixels 17765 * @param scrollX Current X scroll value in pixels before applying deltaX 17766 * @param scrollY Current Y scroll value in pixels before applying deltaY 17767 * @param scrollRangeX Maximum content scroll range along the X axis 17768 * @param scrollRangeY Maximum content scroll range along the Y axis 17769 * @param maxOverScrollX Number of pixels to overscroll by in either direction 17770 * along the X axis. 17771 * @param maxOverScrollY Number of pixels to overscroll by in either direction 17772 * along the Y axis. 17773 * @param isTouchEvent true if this scroll operation is the result of a touch event. 17774 * @return true if scrolling was clamped to an over-scroll boundary along either 17775 * axis, false otherwise. 17776 */ 17777 @SuppressWarnings({"UnusedParameters"}) 17778 protected boolean overScrollBy(int deltaX, int deltaY, 17779 int scrollX, int scrollY, 17780 int scrollRangeX, int scrollRangeY, 17781 int maxOverScrollX, int maxOverScrollY, 17782 boolean isTouchEvent) { 17783 final int overScrollMode = mOverScrollMode; 17784 final boolean canScrollHorizontal = 17785 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 17786 final boolean canScrollVertical = 17787 computeVerticalScrollRange() > computeVerticalScrollExtent(); 17788 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 17789 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 17790 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 17791 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 17792 17793 int newScrollX = scrollX + deltaX; 17794 if (!overScrollHorizontal) { 17795 maxOverScrollX = 0; 17796 } 17797 17798 int newScrollY = scrollY + deltaY; 17799 if (!overScrollVertical) { 17800 maxOverScrollY = 0; 17801 } 17802 17803 // Clamp values if at the limits and record 17804 final int left = -maxOverScrollX; 17805 final int right = maxOverScrollX + scrollRangeX; 17806 final int top = -maxOverScrollY; 17807 final int bottom = maxOverScrollY + scrollRangeY; 17808 17809 boolean clampedX = false; 17810 if (newScrollX > right) { 17811 newScrollX = right; 17812 clampedX = true; 17813 } else if (newScrollX < left) { 17814 newScrollX = left; 17815 clampedX = true; 17816 } 17817 17818 boolean clampedY = false; 17819 if (newScrollY > bottom) { 17820 newScrollY = bottom; 17821 clampedY = true; 17822 } else if (newScrollY < top) { 17823 newScrollY = top; 17824 clampedY = true; 17825 } 17826 17827 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 17828 17829 return clampedX || clampedY; 17830 } 17831 17832 /** 17833 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 17834 * respond to the results of an over-scroll operation. 17835 * 17836 * @param scrollX New X scroll value in pixels 17837 * @param scrollY New Y scroll value in pixels 17838 * @param clampedX True if scrollX was clamped to an over-scroll boundary 17839 * @param clampedY True if scrollY was clamped to an over-scroll boundary 17840 */ 17841 protected void onOverScrolled(int scrollX, int scrollY, 17842 boolean clampedX, boolean clampedY) { 17843 // Intentionally empty. 17844 } 17845 17846 /** 17847 * Returns the over-scroll mode for this view. The result will be 17848 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17849 * (allow over-scrolling only if the view content is larger than the container), 17850 * or {@link #OVER_SCROLL_NEVER}. 17851 * 17852 * @return This view's over-scroll mode. 17853 */ 17854 public int getOverScrollMode() { 17855 return mOverScrollMode; 17856 } 17857 17858 /** 17859 * Set the over-scroll mode for this view. Valid over-scroll modes are 17860 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 17861 * (allow over-scrolling only if the view content is larger than the container), 17862 * or {@link #OVER_SCROLL_NEVER}. 17863 * 17864 * Setting the over-scroll mode of a view will have an effect only if the 17865 * view is capable of scrolling. 17866 * 17867 * @param overScrollMode The new over-scroll mode for this view. 17868 */ 17869 public void setOverScrollMode(int overScrollMode) { 17870 if (overScrollMode != OVER_SCROLL_ALWAYS && 17871 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 17872 overScrollMode != OVER_SCROLL_NEVER) { 17873 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 17874 } 17875 mOverScrollMode = overScrollMode; 17876 } 17877 17878 /** 17879 * Gets a scale factor that determines the distance the view should scroll 17880 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 17881 * @return The vertical scroll scale factor. 17882 * @hide 17883 */ 17884 protected float getVerticalScrollFactor() { 17885 if (mVerticalScrollFactor == 0) { 17886 TypedValue outValue = new TypedValue(); 17887 if (!mContext.getTheme().resolveAttribute( 17888 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 17889 throw new IllegalStateException( 17890 "Expected theme to define listPreferredItemHeight."); 17891 } 17892 mVerticalScrollFactor = outValue.getDimension( 17893 mContext.getResources().getDisplayMetrics()); 17894 } 17895 return mVerticalScrollFactor; 17896 } 17897 17898 /** 17899 * Gets a scale factor that determines the distance the view should scroll 17900 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 17901 * @return The horizontal scroll scale factor. 17902 * @hide 17903 */ 17904 protected float getHorizontalScrollFactor() { 17905 // TODO: Should use something else. 17906 return getVerticalScrollFactor(); 17907 } 17908 17909 /** 17910 * Return the value specifying the text direction or policy that was set with 17911 * {@link #setTextDirection(int)}. 17912 * 17913 * @return the defined text direction. It can be one of: 17914 * 17915 * {@link #TEXT_DIRECTION_INHERIT}, 17916 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17917 * {@link #TEXT_DIRECTION_ANY_RTL}, 17918 * {@link #TEXT_DIRECTION_LTR}, 17919 * {@link #TEXT_DIRECTION_RTL}, 17920 * {@link #TEXT_DIRECTION_LOCALE} 17921 * 17922 * @attr ref android.R.styleable#View_textDirection 17923 * 17924 * @hide 17925 */ 17926 @ViewDebug.ExportedProperty(category = "text", mapping = { 17927 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17928 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17929 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17930 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17931 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17932 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17933 }) 17934 public int getRawTextDirection() { 17935 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 17936 } 17937 17938 /** 17939 * Set the text direction. 17940 * 17941 * @param textDirection the direction to set. Should be one of: 17942 * 17943 * {@link #TEXT_DIRECTION_INHERIT}, 17944 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17945 * {@link #TEXT_DIRECTION_ANY_RTL}, 17946 * {@link #TEXT_DIRECTION_LTR}, 17947 * {@link #TEXT_DIRECTION_RTL}, 17948 * {@link #TEXT_DIRECTION_LOCALE} 17949 * 17950 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 17951 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 17952 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 17953 * 17954 * @attr ref android.R.styleable#View_textDirection 17955 */ 17956 public void setTextDirection(int textDirection) { 17957 if (getRawTextDirection() != textDirection) { 17958 // Reset the current text direction and the resolved one 17959 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 17960 resetResolvedTextDirection(); 17961 // Set the new text direction 17962 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 17963 // Do resolution 17964 resolveTextDirection(); 17965 // Notify change 17966 onRtlPropertiesChanged(getLayoutDirection()); 17967 // Refresh 17968 requestLayout(); 17969 invalidate(true); 17970 } 17971 } 17972 17973 /** 17974 * Return the resolved text direction. 17975 * 17976 * @return the resolved text direction. Returns one of: 17977 * 17978 * {@link #TEXT_DIRECTION_FIRST_STRONG} 17979 * {@link #TEXT_DIRECTION_ANY_RTL}, 17980 * {@link #TEXT_DIRECTION_LTR}, 17981 * {@link #TEXT_DIRECTION_RTL}, 17982 * {@link #TEXT_DIRECTION_LOCALE} 17983 * 17984 * @attr ref android.R.styleable#View_textDirection 17985 */ 17986 @ViewDebug.ExportedProperty(category = "text", mapping = { 17987 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 17988 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 17989 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 17990 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 17991 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 17992 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 17993 }) 17994 public int getTextDirection() { 17995 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 17996 } 17997 17998 /** 17999 * Resolve the text direction. 18000 * 18001 * @return true if resolution has been done, false otherwise. 18002 * 18003 * @hide 18004 */ 18005 public boolean resolveTextDirection() { 18006 // Reset any previous text direction resolution 18007 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18008 18009 if (hasRtlSupport()) { 18010 // Set resolved text direction flag depending on text direction flag 18011 final int textDirection = getRawTextDirection(); 18012 switch(textDirection) { 18013 case TEXT_DIRECTION_INHERIT: 18014 if (!canResolveTextDirection()) { 18015 // We cannot do the resolution if there is no parent, so use the default one 18016 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18017 // Resolution will need to happen again later 18018 return false; 18019 } 18020 18021 // Parent has not yet resolved, so we still return the default 18022 try { 18023 if (!mParent.isTextDirectionResolved()) { 18024 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18025 // Resolution will need to happen again later 18026 return false; 18027 } 18028 } catch (AbstractMethodError e) { 18029 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18030 " does not fully implement ViewParent", e); 18031 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18032 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18033 return true; 18034 } 18035 18036 // Set current resolved direction to the same value as the parent's one 18037 int parentResolvedDirection; 18038 try { 18039 parentResolvedDirection = mParent.getTextDirection(); 18040 } catch (AbstractMethodError e) { 18041 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18042 " does not fully implement ViewParent", e); 18043 parentResolvedDirection = TEXT_DIRECTION_LTR; 18044 } 18045 switch (parentResolvedDirection) { 18046 case TEXT_DIRECTION_FIRST_STRONG: 18047 case TEXT_DIRECTION_ANY_RTL: 18048 case TEXT_DIRECTION_LTR: 18049 case TEXT_DIRECTION_RTL: 18050 case TEXT_DIRECTION_LOCALE: 18051 mPrivateFlags2 |= 18052 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18053 break; 18054 default: 18055 // Default resolved direction is "first strong" heuristic 18056 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18057 } 18058 break; 18059 case TEXT_DIRECTION_FIRST_STRONG: 18060 case TEXT_DIRECTION_ANY_RTL: 18061 case TEXT_DIRECTION_LTR: 18062 case TEXT_DIRECTION_RTL: 18063 case TEXT_DIRECTION_LOCALE: 18064 // Resolved direction is the same as text direction 18065 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 18066 break; 18067 default: 18068 // Default resolved direction is "first strong" heuristic 18069 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18070 } 18071 } else { 18072 // Default resolved direction is "first strong" heuristic 18073 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18074 } 18075 18076 // Set to resolved 18077 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 18078 return true; 18079 } 18080 18081 /** 18082 * Check if text direction resolution can be done. 18083 * 18084 * @return true if text direction resolution can be done otherwise return false. 18085 */ 18086 public boolean canResolveTextDirection() { 18087 switch (getRawTextDirection()) { 18088 case TEXT_DIRECTION_INHERIT: 18089 if (mParent != null) { 18090 try { 18091 return mParent.canResolveTextDirection(); 18092 } catch (AbstractMethodError e) { 18093 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18094 " does not fully implement ViewParent", e); 18095 } 18096 } 18097 return false; 18098 18099 default: 18100 return true; 18101 } 18102 } 18103 18104 /** 18105 * Reset resolved text direction. Text direction will be resolved during a call to 18106 * {@link #onMeasure(int, int)}. 18107 * 18108 * @hide 18109 */ 18110 public void resetResolvedTextDirection() { 18111 // Reset any previous text direction resolution 18112 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18113 // Set to default value 18114 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18115 } 18116 18117 /** 18118 * @return true if text direction is inherited. 18119 * 18120 * @hide 18121 */ 18122 public boolean isTextDirectionInherited() { 18123 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 18124 } 18125 18126 /** 18127 * @return true if text direction is resolved. 18128 */ 18129 public boolean isTextDirectionResolved() { 18130 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 18131 } 18132 18133 /** 18134 * Return the value specifying the text alignment or policy that was set with 18135 * {@link #setTextAlignment(int)}. 18136 * 18137 * @return the defined text alignment. It can be one of: 18138 * 18139 * {@link #TEXT_ALIGNMENT_INHERIT}, 18140 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18141 * {@link #TEXT_ALIGNMENT_CENTER}, 18142 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18143 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18144 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18145 * {@link #TEXT_ALIGNMENT_VIEW_END} 18146 * 18147 * @attr ref android.R.styleable#View_textAlignment 18148 * 18149 * @hide 18150 */ 18151 @ViewDebug.ExportedProperty(category = "text", mapping = { 18152 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18153 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18154 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18155 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18156 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18157 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18158 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18159 }) 18160 @TextAlignment 18161 public int getRawTextAlignment() { 18162 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 18163 } 18164 18165 /** 18166 * Set the text alignment. 18167 * 18168 * @param textAlignment The text alignment to set. Should be one of 18169 * 18170 * {@link #TEXT_ALIGNMENT_INHERIT}, 18171 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18172 * {@link #TEXT_ALIGNMENT_CENTER}, 18173 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18174 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18175 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18176 * {@link #TEXT_ALIGNMENT_VIEW_END} 18177 * 18178 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 18179 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 18180 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 18181 * 18182 * @attr ref android.R.styleable#View_textAlignment 18183 */ 18184 public void setTextAlignment(@TextAlignment int textAlignment) { 18185 if (textAlignment != getRawTextAlignment()) { 18186 // Reset the current and resolved text alignment 18187 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 18188 resetResolvedTextAlignment(); 18189 // Set the new text alignment 18190 mPrivateFlags2 |= 18191 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 18192 // Do resolution 18193 resolveTextAlignment(); 18194 // Notify change 18195 onRtlPropertiesChanged(getLayoutDirection()); 18196 // Refresh 18197 requestLayout(); 18198 invalidate(true); 18199 } 18200 } 18201 18202 /** 18203 * Return the resolved text alignment. 18204 * 18205 * @return the resolved text alignment. Returns one of: 18206 * 18207 * {@link #TEXT_ALIGNMENT_GRAVITY}, 18208 * {@link #TEXT_ALIGNMENT_CENTER}, 18209 * {@link #TEXT_ALIGNMENT_TEXT_START}, 18210 * {@link #TEXT_ALIGNMENT_TEXT_END}, 18211 * {@link #TEXT_ALIGNMENT_VIEW_START}, 18212 * {@link #TEXT_ALIGNMENT_VIEW_END} 18213 * 18214 * @attr ref android.R.styleable#View_textAlignment 18215 */ 18216 @ViewDebug.ExportedProperty(category = "text", mapping = { 18217 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 18218 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 18219 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 18220 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 18221 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 18222 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 18223 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 18224 }) 18225 @TextAlignment 18226 public int getTextAlignment() { 18227 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 18228 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 18229 } 18230 18231 /** 18232 * Resolve the text alignment. 18233 * 18234 * @return true if resolution has been done, false otherwise. 18235 * 18236 * @hide 18237 */ 18238 public boolean resolveTextAlignment() { 18239 // Reset any previous text alignment resolution 18240 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18241 18242 if (hasRtlSupport()) { 18243 // Set resolved text alignment flag depending on text alignment flag 18244 final int textAlignment = getRawTextAlignment(); 18245 switch (textAlignment) { 18246 case TEXT_ALIGNMENT_INHERIT: 18247 // Check if we can resolve the text alignment 18248 if (!canResolveTextAlignment()) { 18249 // We cannot do the resolution if there is no parent so use the default 18250 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18251 // Resolution will need to happen again later 18252 return false; 18253 } 18254 18255 // Parent has not yet resolved, so we still return the default 18256 try { 18257 if (!mParent.isTextAlignmentResolved()) { 18258 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18259 // Resolution will need to happen again later 18260 return false; 18261 } 18262 } catch (AbstractMethodError e) { 18263 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18264 " does not fully implement ViewParent", e); 18265 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 18266 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18267 return true; 18268 } 18269 18270 int parentResolvedTextAlignment; 18271 try { 18272 parentResolvedTextAlignment = mParent.getTextAlignment(); 18273 } catch (AbstractMethodError e) { 18274 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18275 " does not fully implement ViewParent", e); 18276 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 18277 } 18278 switch (parentResolvedTextAlignment) { 18279 case TEXT_ALIGNMENT_GRAVITY: 18280 case TEXT_ALIGNMENT_TEXT_START: 18281 case TEXT_ALIGNMENT_TEXT_END: 18282 case TEXT_ALIGNMENT_CENTER: 18283 case TEXT_ALIGNMENT_VIEW_START: 18284 case TEXT_ALIGNMENT_VIEW_END: 18285 // Resolved text alignment is the same as the parent resolved 18286 // text alignment 18287 mPrivateFlags2 |= 18288 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18289 break; 18290 default: 18291 // Use default resolved text alignment 18292 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18293 } 18294 break; 18295 case TEXT_ALIGNMENT_GRAVITY: 18296 case TEXT_ALIGNMENT_TEXT_START: 18297 case TEXT_ALIGNMENT_TEXT_END: 18298 case TEXT_ALIGNMENT_CENTER: 18299 case TEXT_ALIGNMENT_VIEW_START: 18300 case TEXT_ALIGNMENT_VIEW_END: 18301 // Resolved text alignment is the same as text alignment 18302 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 18303 break; 18304 default: 18305 // Use default resolved text alignment 18306 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18307 } 18308 } else { 18309 // Use default resolved text alignment 18310 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18311 } 18312 18313 // Set the resolved 18314 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18315 return true; 18316 } 18317 18318 /** 18319 * Check if text alignment resolution can be done. 18320 * 18321 * @return true if text alignment resolution can be done otherwise return false. 18322 */ 18323 public boolean canResolveTextAlignment() { 18324 switch (getRawTextAlignment()) { 18325 case TEXT_DIRECTION_INHERIT: 18326 if (mParent != null) { 18327 try { 18328 return mParent.canResolveTextAlignment(); 18329 } catch (AbstractMethodError e) { 18330 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18331 " does not fully implement ViewParent", e); 18332 } 18333 } 18334 return false; 18335 18336 default: 18337 return true; 18338 } 18339 } 18340 18341 /** 18342 * Reset resolved text alignment. Text alignment will be resolved during a call to 18343 * {@link #onMeasure(int, int)}. 18344 * 18345 * @hide 18346 */ 18347 public void resetResolvedTextAlignment() { 18348 // Reset any previous text alignment resolution 18349 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 18350 // Set to default 18351 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 18352 } 18353 18354 /** 18355 * @return true if text alignment is inherited. 18356 * 18357 * @hide 18358 */ 18359 public boolean isTextAlignmentInherited() { 18360 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 18361 } 18362 18363 /** 18364 * @return true if text alignment is resolved. 18365 */ 18366 public boolean isTextAlignmentResolved() { 18367 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 18368 } 18369 18370 /** 18371 * Generate a value suitable for use in {@link #setId(int)}. 18372 * This value will not collide with ID values generated at build time by aapt for R.id. 18373 * 18374 * @return a generated ID value 18375 */ 18376 public static int generateViewId() { 18377 for (;;) { 18378 final int result = sNextGeneratedId.get(); 18379 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 18380 int newValue = result + 1; 18381 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 18382 if (sNextGeneratedId.compareAndSet(result, newValue)) { 18383 return result; 18384 } 18385 } 18386 } 18387 18388 /** 18389 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 18390 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 18391 * a normal View or a ViewGroup with 18392 * {@link android.view.ViewGroup#isTransitionGroup()} true. 18393 * @hide 18394 */ 18395 public void captureTransitioningViews(List<View> transitioningViews) { 18396 if (getVisibility() == View.VISIBLE) { 18397 transitioningViews.add(this); 18398 } 18399 } 18400 18401 /** 18402 * Adds all Views that have {@link #getSharedElementName()} non-null to sharedElements. 18403 * @param sharedElements Will contain all Views in the hierarchy having a shared element name. 18404 * @hide 18405 */ 18406 public void findSharedElements(Map<String, View> sharedElements) { 18407 if (getVisibility() == VISIBLE) { 18408 String sharedElementName = getSharedElementName(); 18409 if (sharedElementName != null) { 18410 sharedElements.put(sharedElementName, this); 18411 } 18412 } 18413 } 18414 18415 // 18416 // Properties 18417 // 18418 /** 18419 * A Property wrapper around the <code>alpha</code> functionality handled by the 18420 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 18421 */ 18422 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 18423 @Override 18424 public void setValue(View object, float value) { 18425 object.setAlpha(value); 18426 } 18427 18428 @Override 18429 public Float get(View object) { 18430 return object.getAlpha(); 18431 } 18432 }; 18433 18434 /** 18435 * A Property wrapper around the <code>translationX</code> functionality handled by the 18436 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 18437 */ 18438 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 18439 @Override 18440 public void setValue(View object, float value) { 18441 object.setTranslationX(value); 18442 } 18443 18444 @Override 18445 public Float get(View object) { 18446 return object.getTranslationX(); 18447 } 18448 }; 18449 18450 /** 18451 * A Property wrapper around the <code>translationY</code> functionality handled by the 18452 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 18453 */ 18454 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 18455 @Override 18456 public void setValue(View object, float value) { 18457 object.setTranslationY(value); 18458 } 18459 18460 @Override 18461 public Float get(View object) { 18462 return object.getTranslationY(); 18463 } 18464 }; 18465 18466 /** 18467 * A Property wrapper around the <code>translationZ</code> functionality handled by the 18468 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 18469 */ 18470 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 18471 @Override 18472 public void setValue(View object, float value) { 18473 object.setTranslationZ(value); 18474 } 18475 18476 @Override 18477 public Float get(View object) { 18478 return object.getTranslationZ(); 18479 } 18480 }; 18481 18482 /** 18483 * A Property wrapper around the <code>x</code> functionality handled by the 18484 * {@link View#setX(float)} and {@link View#getX()} methods. 18485 */ 18486 public static final Property<View, Float> X = new FloatProperty<View>("x") { 18487 @Override 18488 public void setValue(View object, float value) { 18489 object.setX(value); 18490 } 18491 18492 @Override 18493 public Float get(View object) { 18494 return object.getX(); 18495 } 18496 }; 18497 18498 /** 18499 * A Property wrapper around the <code>y</code> functionality handled by the 18500 * {@link View#setY(float)} and {@link View#getY()} methods. 18501 */ 18502 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 18503 @Override 18504 public void setValue(View object, float value) { 18505 object.setY(value); 18506 } 18507 18508 @Override 18509 public Float get(View object) { 18510 return object.getY(); 18511 } 18512 }; 18513 18514 /** 18515 * A Property wrapper around the <code>rotation</code> functionality handled by the 18516 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 18517 */ 18518 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 18519 @Override 18520 public void setValue(View object, float value) { 18521 object.setRotation(value); 18522 } 18523 18524 @Override 18525 public Float get(View object) { 18526 return object.getRotation(); 18527 } 18528 }; 18529 18530 /** 18531 * A Property wrapper around the <code>rotationX</code> functionality handled by the 18532 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 18533 */ 18534 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 18535 @Override 18536 public void setValue(View object, float value) { 18537 object.setRotationX(value); 18538 } 18539 18540 @Override 18541 public Float get(View object) { 18542 return object.getRotationX(); 18543 } 18544 }; 18545 18546 /** 18547 * A Property wrapper around the <code>rotationY</code> functionality handled by the 18548 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 18549 */ 18550 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 18551 @Override 18552 public void setValue(View object, float value) { 18553 object.setRotationY(value); 18554 } 18555 18556 @Override 18557 public Float get(View object) { 18558 return object.getRotationY(); 18559 } 18560 }; 18561 18562 /** 18563 * A Property wrapper around the <code>scaleX</code> functionality handled by the 18564 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 18565 */ 18566 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 18567 @Override 18568 public void setValue(View object, float value) { 18569 object.setScaleX(value); 18570 } 18571 18572 @Override 18573 public Float get(View object) { 18574 return object.getScaleX(); 18575 } 18576 }; 18577 18578 /** 18579 * A Property wrapper around the <code>scaleY</code> functionality handled by the 18580 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 18581 */ 18582 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 18583 @Override 18584 public void setValue(View object, float value) { 18585 object.setScaleY(value); 18586 } 18587 18588 @Override 18589 public Float get(View object) { 18590 return object.getScaleY(); 18591 } 18592 }; 18593 18594 /** 18595 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 18596 * Each MeasureSpec represents a requirement for either the width or the height. 18597 * A MeasureSpec is comprised of a size and a mode. There are three possible 18598 * modes: 18599 * <dl> 18600 * <dt>UNSPECIFIED</dt> 18601 * <dd> 18602 * The parent has not imposed any constraint on the child. It can be whatever size 18603 * it wants. 18604 * </dd> 18605 * 18606 * <dt>EXACTLY</dt> 18607 * <dd> 18608 * The parent has determined an exact size for the child. The child is going to be 18609 * given those bounds regardless of how big it wants to be. 18610 * </dd> 18611 * 18612 * <dt>AT_MOST</dt> 18613 * <dd> 18614 * The child can be as large as it wants up to the specified size. 18615 * </dd> 18616 * </dl> 18617 * 18618 * MeasureSpecs are implemented as ints to reduce object allocation. This class 18619 * is provided to pack and unpack the <size, mode> tuple into the int. 18620 */ 18621 public static class MeasureSpec { 18622 private static final int MODE_SHIFT = 30; 18623 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 18624 18625 /** 18626 * Measure specification mode: The parent has not imposed any constraint 18627 * on the child. It can be whatever size it wants. 18628 */ 18629 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 18630 18631 /** 18632 * Measure specification mode: The parent has determined an exact size 18633 * for the child. The child is going to be given those bounds regardless 18634 * of how big it wants to be. 18635 */ 18636 public static final int EXACTLY = 1 << MODE_SHIFT; 18637 18638 /** 18639 * Measure specification mode: The child can be as large as it wants up 18640 * to the specified size. 18641 */ 18642 public static final int AT_MOST = 2 << MODE_SHIFT; 18643 18644 /** 18645 * Creates a measure specification based on the supplied size and mode. 18646 * 18647 * The mode must always be one of the following: 18648 * <ul> 18649 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 18650 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 18651 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 18652 * </ul> 18653 * 18654 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 18655 * implementation was such that the order of arguments did not matter 18656 * and overflow in either value could impact the resulting MeasureSpec. 18657 * {@link android.widget.RelativeLayout} was affected by this bug. 18658 * Apps targeting API levels greater than 17 will get the fixed, more strict 18659 * behavior.</p> 18660 * 18661 * @param size the size of the measure specification 18662 * @param mode the mode of the measure specification 18663 * @return the measure specification based on size and mode 18664 */ 18665 public static int makeMeasureSpec(int size, int mode) { 18666 if (sUseBrokenMakeMeasureSpec) { 18667 return size + mode; 18668 } else { 18669 return (size & ~MODE_MASK) | (mode & MODE_MASK); 18670 } 18671 } 18672 18673 /** 18674 * Extracts the mode from the supplied measure specification. 18675 * 18676 * @param measureSpec the measure specification to extract the mode from 18677 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 18678 * {@link android.view.View.MeasureSpec#AT_MOST} or 18679 * {@link android.view.View.MeasureSpec#EXACTLY} 18680 */ 18681 public static int getMode(int measureSpec) { 18682 return (measureSpec & MODE_MASK); 18683 } 18684 18685 /** 18686 * Extracts the size from the supplied measure specification. 18687 * 18688 * @param measureSpec the measure specification to extract the size from 18689 * @return the size in pixels defined in the supplied measure specification 18690 */ 18691 public static int getSize(int measureSpec) { 18692 return (measureSpec & ~MODE_MASK); 18693 } 18694 18695 static int adjust(int measureSpec, int delta) { 18696 final int mode = getMode(measureSpec); 18697 if (mode == UNSPECIFIED) { 18698 // No need to adjust size for UNSPECIFIED mode. 18699 return makeMeasureSpec(0, UNSPECIFIED); 18700 } 18701 int size = getSize(measureSpec) + delta; 18702 if (size < 0) { 18703 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 18704 ") spec: " + toString(measureSpec) + " delta: " + delta); 18705 size = 0; 18706 } 18707 return makeMeasureSpec(size, mode); 18708 } 18709 18710 /** 18711 * Returns a String representation of the specified measure 18712 * specification. 18713 * 18714 * @param measureSpec the measure specification to convert to a String 18715 * @return a String with the following format: "MeasureSpec: MODE SIZE" 18716 */ 18717 public static String toString(int measureSpec) { 18718 int mode = getMode(measureSpec); 18719 int size = getSize(measureSpec); 18720 18721 StringBuilder sb = new StringBuilder("MeasureSpec: "); 18722 18723 if (mode == UNSPECIFIED) 18724 sb.append("UNSPECIFIED "); 18725 else if (mode == EXACTLY) 18726 sb.append("EXACTLY "); 18727 else if (mode == AT_MOST) 18728 sb.append("AT_MOST "); 18729 else 18730 sb.append(mode).append(" "); 18731 18732 sb.append(size); 18733 return sb.toString(); 18734 } 18735 } 18736 18737 private final class CheckForLongPress implements Runnable { 18738 private int mOriginalWindowAttachCount; 18739 18740 @Override 18741 public void run() { 18742 if (isPressed() && (mParent != null) 18743 && mOriginalWindowAttachCount == mWindowAttachCount) { 18744 if (performLongClick()) { 18745 mHasPerformedLongPress = true; 18746 } 18747 } 18748 } 18749 18750 public void rememberWindowAttachCount() { 18751 mOriginalWindowAttachCount = mWindowAttachCount; 18752 } 18753 } 18754 18755 private final class CheckForTap implements Runnable { 18756 public float x; 18757 public float y; 18758 18759 @Override 18760 public void run() { 18761 mPrivateFlags &= ~PFLAG_PREPRESSED; 18762 setHotspot(R.attr.state_pressed, x, y); 18763 setPressed(true); 18764 checkForLongClick(ViewConfiguration.getTapTimeout()); 18765 } 18766 } 18767 18768 private final class PerformClick implements Runnable { 18769 @Override 18770 public void run() { 18771 performClick(); 18772 } 18773 } 18774 18775 /** @hide */ 18776 public void hackTurnOffWindowResizeAnim(boolean off) { 18777 mAttachInfo.mTurnOffWindowResizeAnim = off; 18778 } 18779 18780 /** 18781 * This method returns a ViewPropertyAnimator object, which can be used to animate 18782 * specific properties on this View. 18783 * 18784 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 18785 */ 18786 public ViewPropertyAnimator animate() { 18787 if (mAnimator == null) { 18788 mAnimator = new ViewPropertyAnimator(this); 18789 } 18790 return mAnimator; 18791 } 18792 18793 /** 18794 * Specifies that the shared name of the View to be shared with another Activity. 18795 * When transitioning between Activities, the name links a UI element in the starting 18796 * Activity to UI element in the called Activity. Names should be unique in the 18797 * View hierarchy. 18798 * 18799 * @param sharedElementName The cross-Activity View identifier. The called Activity will use 18800 * the name to match the location with a View in its layout. 18801 * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.os.Bundle) 18802 */ 18803 public void setSharedElementName(String sharedElementName) { 18804 setTagInternal(com.android.internal.R.id.shared_element_name, sharedElementName); 18805 } 18806 18807 /** 18808 * Returns the shared name of the View to be shared with another Activity. 18809 * When transitioning between Activities, the name links a UI element in the starting 18810 * Activity to UI element in the called Activity. Names should be unique in the 18811 * View hierarchy. 18812 * 18813 * <p>This returns null if the View is not a shared element or the name if it is.</p> 18814 * 18815 * @return The name used for this View for cross-Activity transitions or null if 18816 * this View has not been identified as shared. 18817 */ 18818 public String getSharedElementName() { 18819 return (String) getTag(com.android.internal.R.id.shared_element_name); 18820 } 18821 18822 /** 18823 * Interface definition for a callback to be invoked when a hardware key event is 18824 * dispatched to this view. The callback will be invoked before the key event is 18825 * given to the view. This is only useful for hardware keyboards; a software input 18826 * method has no obligation to trigger this listener. 18827 */ 18828 public interface OnKeyListener { 18829 /** 18830 * Called when a hardware key is dispatched to a view. This allows listeners to 18831 * get a chance to respond before the target view. 18832 * <p>Key presses in software keyboards will generally NOT trigger this method, 18833 * although some may elect to do so in some situations. Do not assume a 18834 * software input method has to be key-based; even if it is, it may use key presses 18835 * in a different way than you expect, so there is no way to reliably catch soft 18836 * input key presses. 18837 * 18838 * @param v The view the key has been dispatched to. 18839 * @param keyCode The code for the physical key that was pressed 18840 * @param event The KeyEvent object containing full information about 18841 * the event. 18842 * @return True if the listener has consumed the event, false otherwise. 18843 */ 18844 boolean onKey(View v, int keyCode, KeyEvent event); 18845 } 18846 18847 /** 18848 * Interface definition for a callback to be invoked when a touch event is 18849 * dispatched to this view. The callback will be invoked before the touch 18850 * event is given to the view. 18851 */ 18852 public interface OnTouchListener { 18853 /** 18854 * Called when a touch event is dispatched to a view. This allows listeners to 18855 * get a chance to respond before the target view. 18856 * 18857 * @param v The view the touch event has been dispatched to. 18858 * @param event The MotionEvent object containing full information about 18859 * the event. 18860 * @return True if the listener has consumed the event, false otherwise. 18861 */ 18862 boolean onTouch(View v, MotionEvent event); 18863 } 18864 18865 /** 18866 * Interface definition for a callback to be invoked when a hover event is 18867 * dispatched to this view. The callback will be invoked before the hover 18868 * event is given to the view. 18869 */ 18870 public interface OnHoverListener { 18871 /** 18872 * Called when a hover event is dispatched to a view. This allows listeners to 18873 * get a chance to respond before the target view. 18874 * 18875 * @param v The view the hover event has been dispatched to. 18876 * @param event The MotionEvent object containing full information about 18877 * the event. 18878 * @return True if the listener has consumed the event, false otherwise. 18879 */ 18880 boolean onHover(View v, MotionEvent event); 18881 } 18882 18883 /** 18884 * Interface definition for a callback to be invoked when a generic motion event is 18885 * dispatched to this view. The callback will be invoked before the generic motion 18886 * event is given to the view. 18887 */ 18888 public interface OnGenericMotionListener { 18889 /** 18890 * Called when a generic motion event is dispatched to a view. This allows listeners to 18891 * get a chance to respond before the target view. 18892 * 18893 * @param v The view the generic motion event has been dispatched to. 18894 * @param event The MotionEvent object containing full information about 18895 * the event. 18896 * @return True if the listener has consumed the event, false otherwise. 18897 */ 18898 boolean onGenericMotion(View v, MotionEvent event); 18899 } 18900 18901 /** 18902 * Interface definition for a callback to be invoked when a view has been clicked and held. 18903 */ 18904 public interface OnLongClickListener { 18905 /** 18906 * Called when a view has been clicked and held. 18907 * 18908 * @param v The view that was clicked and held. 18909 * 18910 * @return true if the callback consumed the long click, false otherwise. 18911 */ 18912 boolean onLongClick(View v); 18913 } 18914 18915 /** 18916 * Interface definition for a callback to be invoked when a drag is being dispatched 18917 * to this view. The callback will be invoked before the hosting view's own 18918 * onDrag(event) method. If the listener wants to fall back to the hosting view's 18919 * onDrag(event) behavior, it should return 'false' from this callback. 18920 * 18921 * <div class="special reference"> 18922 * <h3>Developer Guides</h3> 18923 * <p>For a guide to implementing drag and drop features, read the 18924 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18925 * </div> 18926 */ 18927 public interface OnDragListener { 18928 /** 18929 * Called when a drag event is dispatched to a view. This allows listeners 18930 * to get a chance to override base View behavior. 18931 * 18932 * @param v The View that received the drag event. 18933 * @param event The {@link android.view.DragEvent} object for the drag event. 18934 * @return {@code true} if the drag event was handled successfully, or {@code false} 18935 * if the drag event was not handled. Note that {@code false} will trigger the View 18936 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 18937 */ 18938 boolean onDrag(View v, DragEvent event); 18939 } 18940 18941 /** 18942 * Interface definition for a callback to be invoked when the focus state of 18943 * a view changed. 18944 */ 18945 public interface OnFocusChangeListener { 18946 /** 18947 * Called when the focus state of a view has changed. 18948 * 18949 * @param v The view whose state has changed. 18950 * @param hasFocus The new focus state of v. 18951 */ 18952 void onFocusChange(View v, boolean hasFocus); 18953 } 18954 18955 /** 18956 * Interface definition for a callback to be invoked when a view is clicked. 18957 */ 18958 public interface OnClickListener { 18959 /** 18960 * Called when a view has been clicked. 18961 * 18962 * @param v The view that was clicked. 18963 */ 18964 void onClick(View v); 18965 } 18966 18967 /** 18968 * Interface definition for a callback to be invoked when the context menu 18969 * for this view is being built. 18970 */ 18971 public interface OnCreateContextMenuListener { 18972 /** 18973 * Called when the context menu for this view is being built. It is not 18974 * safe to hold onto the menu after this method returns. 18975 * 18976 * @param menu The context menu that is being built 18977 * @param v The view for which the context menu is being built 18978 * @param menuInfo Extra information about the item for which the 18979 * context menu should be shown. This information will vary 18980 * depending on the class of v. 18981 */ 18982 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 18983 } 18984 18985 /** 18986 * Interface definition for a callback to be invoked when the status bar changes 18987 * visibility. This reports <strong>global</strong> changes to the system UI 18988 * state, not what the application is requesting. 18989 * 18990 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 18991 */ 18992 public interface OnSystemUiVisibilityChangeListener { 18993 /** 18994 * Called when the status bar changes visibility because of a call to 18995 * {@link View#setSystemUiVisibility(int)}. 18996 * 18997 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18998 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 18999 * This tells you the <strong>global</strong> state of these UI visibility 19000 * flags, not what your app is currently applying. 19001 */ 19002 public void onSystemUiVisibilityChange(int visibility); 19003 } 19004 19005 /** 19006 * Interface definition for a callback to be invoked when this view is attached 19007 * or detached from its window. 19008 */ 19009 public interface OnAttachStateChangeListener { 19010 /** 19011 * Called when the view is attached to a window. 19012 * @param v The view that was attached 19013 */ 19014 public void onViewAttachedToWindow(View v); 19015 /** 19016 * Called when the view is detached from a window. 19017 * @param v The view that was detached 19018 */ 19019 public void onViewDetachedFromWindow(View v); 19020 } 19021 19022 /** 19023 * Listener for applying window insets on a view in a custom way. 19024 * 19025 * <p>Apps may choose to implement this interface if they want to apply custom policy 19026 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19027 * is set, its 19028 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 19029 * method will be called instead of the View's own 19030 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 19031 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 19032 * the View's normal behavior as part of its own.</p> 19033 */ 19034 public interface OnApplyWindowInsetsListener { 19035 /** 19036 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 19037 * on a View, this listener method will be called instead of the view's own 19038 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 19039 * 19040 * @param v The view applying window insets 19041 * @param insets The insets to apply 19042 * @return The insets supplied, minus any insets that were consumed 19043 */ 19044 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 19045 } 19046 19047 private final class UnsetPressedState implements Runnable { 19048 @Override 19049 public void run() { 19050 clearHotspot(R.attr.state_pressed); 19051 setPressed(false); 19052 } 19053 } 19054 19055 /** 19056 * Base class for derived classes that want to save and restore their own 19057 * state in {@link android.view.View#onSaveInstanceState()}. 19058 */ 19059 public static class BaseSavedState extends AbsSavedState { 19060 /** 19061 * Constructor used when reading from a parcel. Reads the state of the superclass. 19062 * 19063 * @param source 19064 */ 19065 public BaseSavedState(Parcel source) { 19066 super(source); 19067 } 19068 19069 /** 19070 * Constructor called by derived classes when creating their SavedState objects 19071 * 19072 * @param superState The state of the superclass of this view 19073 */ 19074 public BaseSavedState(Parcelable superState) { 19075 super(superState); 19076 } 19077 19078 public static final Parcelable.Creator<BaseSavedState> CREATOR = 19079 new Parcelable.Creator<BaseSavedState>() { 19080 public BaseSavedState createFromParcel(Parcel in) { 19081 return new BaseSavedState(in); 19082 } 19083 19084 public BaseSavedState[] newArray(int size) { 19085 return new BaseSavedState[size]; 19086 } 19087 }; 19088 } 19089 19090 /** 19091 * A set of information given to a view when it is attached to its parent 19092 * window. 19093 */ 19094 final static class AttachInfo { 19095 interface Callbacks { 19096 void playSoundEffect(int effectId); 19097 boolean performHapticFeedback(int effectId, boolean always); 19098 } 19099 19100 /** 19101 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 19102 * to a Handler. This class contains the target (View) to invalidate and 19103 * the coordinates of the dirty rectangle. 19104 * 19105 * For performance purposes, this class also implements a pool of up to 19106 * POOL_LIMIT objects that get reused. This reduces memory allocations 19107 * whenever possible. 19108 */ 19109 static class InvalidateInfo { 19110 private static final int POOL_LIMIT = 10; 19111 19112 private static final SynchronizedPool<InvalidateInfo> sPool = 19113 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 19114 19115 View target; 19116 19117 int left; 19118 int top; 19119 int right; 19120 int bottom; 19121 19122 public static InvalidateInfo obtain() { 19123 InvalidateInfo instance = sPool.acquire(); 19124 return (instance != null) ? instance : new InvalidateInfo(); 19125 } 19126 19127 public void recycle() { 19128 target = null; 19129 sPool.release(this); 19130 } 19131 } 19132 19133 final IWindowSession mSession; 19134 19135 final IWindow mWindow; 19136 19137 final IBinder mWindowToken; 19138 19139 final Display mDisplay; 19140 19141 final Callbacks mRootCallbacks; 19142 19143 IWindowId mIWindowId; 19144 WindowId mWindowId; 19145 19146 /** 19147 * The top view of the hierarchy. 19148 */ 19149 View mRootView; 19150 19151 IBinder mPanelParentWindowToken; 19152 19153 boolean mHardwareAccelerated; 19154 boolean mHardwareAccelerationRequested; 19155 HardwareRenderer mHardwareRenderer; 19156 19157 /** 19158 * The state of the display to which the window is attached, as reported 19159 * by {@link Display#getState()}. Note that the display state constants 19160 * declared by {@link Display} do not exactly line up with the screen state 19161 * constants declared by {@link View} (there are more display states than 19162 * screen states). 19163 */ 19164 int mDisplayState = Display.STATE_UNKNOWN; 19165 19166 /** 19167 * Scale factor used by the compatibility mode 19168 */ 19169 float mApplicationScale; 19170 19171 /** 19172 * Indicates whether the application is in compatibility mode 19173 */ 19174 boolean mScalingRequired; 19175 19176 /** 19177 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 19178 */ 19179 boolean mTurnOffWindowResizeAnim; 19180 19181 /** 19182 * Left position of this view's window 19183 */ 19184 int mWindowLeft; 19185 19186 /** 19187 * Top position of this view's window 19188 */ 19189 int mWindowTop; 19190 19191 /** 19192 * Indicates whether views need to use 32-bit drawing caches 19193 */ 19194 boolean mUse32BitDrawingCache; 19195 19196 /** 19197 * For windows that are full-screen but using insets to layout inside 19198 * of the screen areas, these are the current insets to appear inside 19199 * the overscan area of the display. 19200 */ 19201 final Rect mOverscanInsets = new Rect(); 19202 19203 /** 19204 * For windows that are full-screen but using insets to layout inside 19205 * of the screen decorations, these are the current insets for the 19206 * content of the window. 19207 */ 19208 final Rect mContentInsets = new Rect(); 19209 19210 /** 19211 * For windows that are full-screen but using insets to layout inside 19212 * of the screen decorations, these are the current insets for the 19213 * actual visible parts of the window. 19214 */ 19215 final Rect mVisibleInsets = new Rect(); 19216 19217 /** 19218 * The internal insets given by this window. This value is 19219 * supplied by the client (through 19220 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 19221 * be given to the window manager when changed to be used in laying 19222 * out windows behind it. 19223 */ 19224 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 19225 = new ViewTreeObserver.InternalInsetsInfo(); 19226 19227 /** 19228 * Set to true when mGivenInternalInsets is non-empty. 19229 */ 19230 boolean mHasNonEmptyGivenInternalInsets; 19231 19232 /** 19233 * All views in the window's hierarchy that serve as scroll containers, 19234 * used to determine if the window can be resized or must be panned 19235 * to adjust for a soft input area. 19236 */ 19237 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 19238 19239 final KeyEvent.DispatcherState mKeyDispatchState 19240 = new KeyEvent.DispatcherState(); 19241 19242 /** 19243 * Indicates whether the view's window currently has the focus. 19244 */ 19245 boolean mHasWindowFocus; 19246 19247 /** 19248 * The current visibility of the window. 19249 */ 19250 int mWindowVisibility; 19251 19252 /** 19253 * Indicates the time at which drawing started to occur. 19254 */ 19255 long mDrawingTime; 19256 19257 /** 19258 * Indicates whether or not ignoring the DIRTY_MASK flags. 19259 */ 19260 boolean mIgnoreDirtyState; 19261 19262 /** 19263 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 19264 * to avoid clearing that flag prematurely. 19265 */ 19266 boolean mSetIgnoreDirtyState = false; 19267 19268 /** 19269 * Indicates whether the view's window is currently in touch mode. 19270 */ 19271 boolean mInTouchMode; 19272 19273 /** 19274 * Indicates that ViewAncestor should trigger a global layout change 19275 * the next time it performs a traversal 19276 */ 19277 boolean mRecomputeGlobalAttributes; 19278 19279 /** 19280 * Always report new attributes at next traversal. 19281 */ 19282 boolean mForceReportNewAttributes; 19283 19284 /** 19285 * Set during a traveral if any views want to keep the screen on. 19286 */ 19287 boolean mKeepScreenOn; 19288 19289 /** 19290 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 19291 */ 19292 int mSystemUiVisibility; 19293 19294 /** 19295 * Hack to force certain system UI visibility flags to be cleared. 19296 */ 19297 int mDisabledSystemUiVisibility; 19298 19299 /** 19300 * Last global system UI visibility reported by the window manager. 19301 */ 19302 int mGlobalSystemUiVisibility; 19303 19304 /** 19305 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 19306 * attached. 19307 */ 19308 boolean mHasSystemUiListeners; 19309 19310 /** 19311 * Set if the window has requested to extend into the overscan region 19312 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 19313 */ 19314 boolean mOverscanRequested; 19315 19316 /** 19317 * Set if the visibility of any views has changed. 19318 */ 19319 boolean mViewVisibilityChanged; 19320 19321 /** 19322 * Set to true if a view has been scrolled. 19323 */ 19324 boolean mViewScrollChanged; 19325 19326 /** 19327 * Global to the view hierarchy used as a temporary for dealing with 19328 * x/y points in the transparent region computations. 19329 */ 19330 final int[] mTransparentLocation = new int[2]; 19331 19332 /** 19333 * Global to the view hierarchy used as a temporary for dealing with 19334 * x/y points in the ViewGroup.invalidateChild implementation. 19335 */ 19336 final int[] mInvalidateChildLocation = new int[2]; 19337 19338 19339 /** 19340 * Global to the view hierarchy used as a temporary for dealing with 19341 * x/y location when view is transformed. 19342 */ 19343 final float[] mTmpTransformLocation = new float[2]; 19344 19345 /** 19346 * The view tree observer used to dispatch global events like 19347 * layout, pre-draw, touch mode change, etc. 19348 */ 19349 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 19350 19351 /** 19352 * A Canvas used by the view hierarchy to perform bitmap caching. 19353 */ 19354 Canvas mCanvas; 19355 19356 /** 19357 * The view root impl. 19358 */ 19359 final ViewRootImpl mViewRootImpl; 19360 19361 /** 19362 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 19363 * handler can be used to pump events in the UI events queue. 19364 */ 19365 final Handler mHandler; 19366 19367 /** 19368 * Temporary for use in computing invalidate rectangles while 19369 * calling up the hierarchy. 19370 */ 19371 final Rect mTmpInvalRect = new Rect(); 19372 19373 /** 19374 * Temporary for use in computing hit areas with transformed views 19375 */ 19376 final RectF mTmpTransformRect = new RectF(); 19377 19378 /** 19379 * Temporary for use in transforming invalidation rect 19380 */ 19381 final Matrix mTmpMatrix = new Matrix(); 19382 19383 /** 19384 * Temporary for use in transforming invalidation rect 19385 */ 19386 final Transformation mTmpTransformation = new Transformation(); 19387 19388 /** 19389 * Temporary list for use in collecting focusable descendents of a view. 19390 */ 19391 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 19392 19393 /** 19394 * The id of the window for accessibility purposes. 19395 */ 19396 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 19397 19398 /** 19399 * Flags related to accessibility processing. 19400 * 19401 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 19402 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 19403 */ 19404 int mAccessibilityFetchFlags; 19405 19406 /** 19407 * The drawable for highlighting accessibility focus. 19408 */ 19409 Drawable mAccessibilityFocusDrawable; 19410 19411 /** 19412 * Show where the margins, bounds and layout bounds are for each view. 19413 */ 19414 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 19415 19416 /** 19417 * Point used to compute visible regions. 19418 */ 19419 final Point mPoint = new Point(); 19420 19421 /** 19422 * Used to track which View originated a requestLayout() call, used when 19423 * requestLayout() is called during layout. 19424 */ 19425 View mViewRequestingLayout; 19426 19427 /** 19428 * Creates a new set of attachment information with the specified 19429 * events handler and thread. 19430 * 19431 * @param handler the events handler the view must use 19432 */ 19433 AttachInfo(IWindowSession session, IWindow window, Display display, 19434 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 19435 mSession = session; 19436 mWindow = window; 19437 mWindowToken = window.asBinder(); 19438 mDisplay = display; 19439 mViewRootImpl = viewRootImpl; 19440 mHandler = handler; 19441 mRootCallbacks = effectPlayer; 19442 } 19443 } 19444 19445 /** 19446 * <p>ScrollabilityCache holds various fields used by a View when scrolling 19447 * is supported. This avoids keeping too many unused fields in most 19448 * instances of View.</p> 19449 */ 19450 private static class ScrollabilityCache implements Runnable { 19451 19452 /** 19453 * Scrollbars are not visible 19454 */ 19455 public static final int OFF = 0; 19456 19457 /** 19458 * Scrollbars are visible 19459 */ 19460 public static final int ON = 1; 19461 19462 /** 19463 * Scrollbars are fading away 19464 */ 19465 public static final int FADING = 2; 19466 19467 public boolean fadeScrollBars; 19468 19469 public int fadingEdgeLength; 19470 public int scrollBarDefaultDelayBeforeFade; 19471 public int scrollBarFadeDuration; 19472 19473 public int scrollBarSize; 19474 public ScrollBarDrawable scrollBar; 19475 public float[] interpolatorValues; 19476 public View host; 19477 19478 public final Paint paint; 19479 public final Matrix matrix; 19480 public Shader shader; 19481 19482 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 19483 19484 private static final float[] OPAQUE = { 255 }; 19485 private static final float[] TRANSPARENT = { 0.0f }; 19486 19487 /** 19488 * When fading should start. This time moves into the future every time 19489 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 19490 */ 19491 public long fadeStartTime; 19492 19493 19494 /** 19495 * The current state of the scrollbars: ON, OFF, or FADING 19496 */ 19497 public int state = OFF; 19498 19499 private int mLastColor; 19500 19501 public ScrollabilityCache(ViewConfiguration configuration, View host) { 19502 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 19503 scrollBarSize = configuration.getScaledScrollBarSize(); 19504 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 19505 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 19506 19507 paint = new Paint(); 19508 matrix = new Matrix(); 19509 // use use a height of 1, and then wack the matrix each time we 19510 // actually use it. 19511 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 19512 paint.setShader(shader); 19513 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 19514 19515 this.host = host; 19516 } 19517 19518 public void setFadeColor(int color) { 19519 if (color != mLastColor) { 19520 mLastColor = color; 19521 19522 if (color != 0) { 19523 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 19524 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 19525 paint.setShader(shader); 19526 // Restore the default transfer mode (src_over) 19527 paint.setXfermode(null); 19528 } else { 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 } 19534 } 19535 19536 public void run() { 19537 long now = AnimationUtils.currentAnimationTimeMillis(); 19538 if (now >= fadeStartTime) { 19539 19540 // the animation fades the scrollbars out by changing 19541 // the opacity (alpha) from fully opaque to fully 19542 // transparent 19543 int nextFrame = (int) now; 19544 int framesCount = 0; 19545 19546 Interpolator interpolator = scrollBarInterpolator; 19547 19548 // Start opaque 19549 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 19550 19551 // End transparent 19552 nextFrame += scrollBarFadeDuration; 19553 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 19554 19555 state = FADING; 19556 19557 // Kick off the fade animation 19558 host.invalidate(true); 19559 } 19560 } 19561 } 19562 19563 /** 19564 * Resuable callback for sending 19565 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 19566 */ 19567 private class SendViewScrolledAccessibilityEvent implements Runnable { 19568 public volatile boolean mIsPending; 19569 19570 public void run() { 19571 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 19572 mIsPending = false; 19573 } 19574 } 19575 19576 /** 19577 * <p> 19578 * This class represents a delegate that can be registered in a {@link View} 19579 * to enhance accessibility support via composition rather via inheritance. 19580 * It is specifically targeted to widget developers that extend basic View 19581 * classes i.e. classes in package android.view, that would like their 19582 * applications to be backwards compatible. 19583 * </p> 19584 * <div class="special reference"> 19585 * <h3>Developer Guides</h3> 19586 * <p>For more information about making applications accessible, read the 19587 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 19588 * developer guide.</p> 19589 * </div> 19590 * <p> 19591 * A scenario in which a developer would like to use an accessibility delegate 19592 * is overriding a method introduced in a later API version then the minimal API 19593 * version supported by the application. For example, the method 19594 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 19595 * in API version 4 when the accessibility APIs were first introduced. If a 19596 * developer would like his application to run on API version 4 devices (assuming 19597 * all other APIs used by the application are version 4 or lower) and take advantage 19598 * of this method, instead of overriding the method which would break the application's 19599 * backwards compatibility, he can override the corresponding method in this 19600 * delegate and register the delegate in the target View if the API version of 19601 * the system is high enough i.e. the API version is same or higher to the API 19602 * version that introduced 19603 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 19604 * </p> 19605 * <p> 19606 * Here is an example implementation: 19607 * </p> 19608 * <code><pre><p> 19609 * if (Build.VERSION.SDK_INT >= 14) { 19610 * // If the API version is equal of higher than the version in 19611 * // which onInitializeAccessibilityNodeInfo was introduced we 19612 * // register a delegate with a customized implementation. 19613 * View view = findViewById(R.id.view_id); 19614 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 19615 * public void onInitializeAccessibilityNodeInfo(View host, 19616 * AccessibilityNodeInfo info) { 19617 * // Let the default implementation populate the info. 19618 * super.onInitializeAccessibilityNodeInfo(host, info); 19619 * // Set some other information. 19620 * info.setEnabled(host.isEnabled()); 19621 * } 19622 * }); 19623 * } 19624 * </code></pre></p> 19625 * <p> 19626 * This delegate contains methods that correspond to the accessibility methods 19627 * in View. If a delegate has been specified the implementation in View hands 19628 * off handling to the corresponding method in this delegate. The default 19629 * implementation the delegate methods behaves exactly as the corresponding 19630 * method in View for the case of no accessibility delegate been set. Hence, 19631 * to customize the behavior of a View method, clients can override only the 19632 * corresponding delegate method without altering the behavior of the rest 19633 * accessibility related methods of the host view. 19634 * </p> 19635 */ 19636 public static class AccessibilityDelegate { 19637 19638 /** 19639 * Sends an accessibility event of the given type. If accessibility is not 19640 * enabled this method has no effect. 19641 * <p> 19642 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 19643 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 19644 * been set. 19645 * </p> 19646 * 19647 * @param host The View hosting the delegate. 19648 * @param eventType The type of the event to send. 19649 * 19650 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 19651 */ 19652 public void sendAccessibilityEvent(View host, int eventType) { 19653 host.sendAccessibilityEventInternal(eventType); 19654 } 19655 19656 /** 19657 * Performs the specified accessibility action on the view. For 19658 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 19659 * <p> 19660 * The default implementation behaves as 19661 * {@link View#performAccessibilityAction(int, Bundle) 19662 * View#performAccessibilityAction(int, Bundle)} for the case of 19663 * no accessibility delegate been set. 19664 * </p> 19665 * 19666 * @param action The action to perform. 19667 * @return Whether the action was performed. 19668 * 19669 * @see View#performAccessibilityAction(int, Bundle) 19670 * View#performAccessibilityAction(int, Bundle) 19671 */ 19672 public boolean performAccessibilityAction(View host, int action, Bundle args) { 19673 return host.performAccessibilityActionInternal(action, args); 19674 } 19675 19676 /** 19677 * Sends an accessibility event. This method behaves exactly as 19678 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 19679 * empty {@link AccessibilityEvent} and does not perform a check whether 19680 * accessibility is enabled. 19681 * <p> 19682 * The default implementation behaves as 19683 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19684 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 19685 * the case of no accessibility delegate been set. 19686 * </p> 19687 * 19688 * @param host The View hosting the delegate. 19689 * @param event The event to send. 19690 * 19691 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19692 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 19693 */ 19694 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 19695 host.sendAccessibilityEventUncheckedInternal(event); 19696 } 19697 19698 /** 19699 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 19700 * to its children for adding their text content to the event. 19701 * <p> 19702 * The default implementation behaves as 19703 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19704 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 19705 * the case of no accessibility delegate been set. 19706 * </p> 19707 * 19708 * @param host The View hosting the delegate. 19709 * @param event The event. 19710 * @return True if the event population was completed. 19711 * 19712 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19713 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 19714 */ 19715 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19716 return host.dispatchPopulateAccessibilityEventInternal(event); 19717 } 19718 19719 /** 19720 * Gives a chance to the host View to populate the accessibility event with its 19721 * text content. 19722 * <p> 19723 * The default implementation behaves as 19724 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 19725 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 19726 * the case of no accessibility delegate been set. 19727 * </p> 19728 * 19729 * @param host The View hosting the delegate. 19730 * @param event The accessibility event which to populate. 19731 * 19732 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 19733 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 19734 */ 19735 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 19736 host.onPopulateAccessibilityEventInternal(event); 19737 } 19738 19739 /** 19740 * Initializes an {@link AccessibilityEvent} with information about the 19741 * the host View which is the event source. 19742 * <p> 19743 * The default implementation behaves as 19744 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 19745 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 19746 * the case of no accessibility delegate been set. 19747 * </p> 19748 * 19749 * @param host The View hosting the delegate. 19750 * @param event The event to initialize. 19751 * 19752 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 19753 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 19754 */ 19755 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 19756 host.onInitializeAccessibilityEventInternal(event); 19757 } 19758 19759 /** 19760 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 19761 * <p> 19762 * The default implementation behaves as 19763 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19764 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 19765 * the case of no accessibility delegate been set. 19766 * </p> 19767 * 19768 * @param host The View hosting the delegate. 19769 * @param info The instance to initialize. 19770 * 19771 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19772 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 19773 */ 19774 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 19775 host.onInitializeAccessibilityNodeInfoInternal(info); 19776 } 19777 19778 /** 19779 * Called when a child of the host View has requested sending an 19780 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 19781 * to augment the event. 19782 * <p> 19783 * The default implementation behaves as 19784 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19785 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 19786 * the case of no accessibility delegate been set. 19787 * </p> 19788 * 19789 * @param host The View hosting the delegate. 19790 * @param child The child which requests sending the event. 19791 * @param event The event to be sent. 19792 * @return True if the event should be sent 19793 * 19794 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19795 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 19796 */ 19797 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 19798 AccessibilityEvent event) { 19799 return host.onRequestSendAccessibilityEventInternal(child, event); 19800 } 19801 19802 /** 19803 * Gets the provider for managing a virtual view hierarchy rooted at this View 19804 * and reported to {@link android.accessibilityservice.AccessibilityService}s 19805 * that explore the window content. 19806 * <p> 19807 * The default implementation behaves as 19808 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 19809 * the case of no accessibility delegate been set. 19810 * </p> 19811 * 19812 * @return The provider. 19813 * 19814 * @see AccessibilityNodeProvider 19815 */ 19816 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 19817 return null; 19818 } 19819 19820 /** 19821 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 19822 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 19823 * This method is responsible for obtaining an accessibility node info from a 19824 * pool of reusable instances and calling 19825 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 19826 * view to initialize the former. 19827 * <p> 19828 * <strong>Note:</strong> The client is responsible for recycling the obtained 19829 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 19830 * creation. 19831 * </p> 19832 * <p> 19833 * The default implementation behaves as 19834 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 19835 * the case of no accessibility delegate been set. 19836 * </p> 19837 * @return A populated {@link AccessibilityNodeInfo}. 19838 * 19839 * @see AccessibilityNodeInfo 19840 * 19841 * @hide 19842 */ 19843 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 19844 return host.createAccessibilityNodeInfoInternal(); 19845 } 19846 } 19847 19848 private class MatchIdPredicate implements Predicate<View> { 19849 public int mId; 19850 19851 @Override 19852 public boolean apply(View view) { 19853 return (view.mID == mId); 19854 } 19855 } 19856 19857 private class MatchLabelForPredicate implements Predicate<View> { 19858 private int mLabeledId; 19859 19860 @Override 19861 public boolean apply(View view) { 19862 return (view.mLabelForId == mLabeledId); 19863 } 19864 } 19865 19866 private class SendViewStateChangedAccessibilityEvent implements Runnable { 19867 private int mChangeTypes = 0; 19868 private boolean mPosted; 19869 private boolean mPostedWithDelay; 19870 private long mLastEventTimeMillis; 19871 19872 @Override 19873 public void run() { 19874 mPosted = false; 19875 mPostedWithDelay = false; 19876 mLastEventTimeMillis = SystemClock.uptimeMillis(); 19877 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 19878 final AccessibilityEvent event = AccessibilityEvent.obtain(); 19879 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 19880 event.setContentChangeTypes(mChangeTypes); 19881 sendAccessibilityEventUnchecked(event); 19882 } 19883 mChangeTypes = 0; 19884 } 19885 19886 public void runOrPost(int changeType) { 19887 mChangeTypes |= changeType; 19888 19889 // If this is a live region or the child of a live region, collect 19890 // all events from this frame and send them on the next frame. 19891 if (inLiveRegion()) { 19892 // If we're already posted with a delay, remove that. 19893 if (mPostedWithDelay) { 19894 removeCallbacks(this); 19895 mPostedWithDelay = false; 19896 } 19897 // Only post if we're not already posted. 19898 if (!mPosted) { 19899 post(this); 19900 mPosted = true; 19901 } 19902 return; 19903 } 19904 19905 if (mPosted) { 19906 return; 19907 } 19908 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 19909 final long minEventIntevalMillis = 19910 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 19911 if (timeSinceLastMillis >= minEventIntevalMillis) { 19912 removeCallbacks(this); 19913 run(); 19914 } else { 19915 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 19916 mPosted = true; 19917 mPostedWithDelay = true; 19918 } 19919 } 19920 } 19921 19922 private boolean inLiveRegion() { 19923 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19924 return true; 19925 } 19926 19927 ViewParent parent = getParent(); 19928 while (parent instanceof View) { 19929 if (((View) parent).getAccessibilityLiveRegion() 19930 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 19931 return true; 19932 } 19933 parent = parent.getParent(); 19934 } 19935 19936 return false; 19937 } 19938 19939 /** 19940 * Dump all private flags in readable format, useful for documentation and 19941 * sanity checking. 19942 */ 19943 private static void dumpFlags() { 19944 final HashMap<String, String> found = Maps.newHashMap(); 19945 try { 19946 for (Field field : View.class.getDeclaredFields()) { 19947 final int modifiers = field.getModifiers(); 19948 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 19949 if (field.getType().equals(int.class)) { 19950 final int value = field.getInt(null); 19951 dumpFlag(found, field.getName(), value); 19952 } else if (field.getType().equals(int[].class)) { 19953 final int[] values = (int[]) field.get(null); 19954 for (int i = 0; i < values.length; i++) { 19955 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 19956 } 19957 } 19958 } 19959 } 19960 } catch (IllegalAccessException e) { 19961 throw new RuntimeException(e); 19962 } 19963 19964 final ArrayList<String> keys = Lists.newArrayList(); 19965 keys.addAll(found.keySet()); 19966 Collections.sort(keys); 19967 for (String key : keys) { 19968 Log.d(VIEW_LOG_TAG, found.get(key)); 19969 } 19970 } 19971 19972 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 19973 // Sort flags by prefix, then by bits, always keeping unique keys 19974 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 19975 final int prefix = name.indexOf('_'); 19976 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 19977 final String output = bits + " " + name; 19978 found.put(key, output); 19979 } 19980} 19981