View.java revision a1c14fe945c00c55d4966aca943b2de8f4535a27
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.StateListAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.ColorStateList; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.content.res.TypedArray; 30import android.graphics.Bitmap; 31import android.graphics.Canvas; 32import android.graphics.Insets; 33import android.graphics.Interpolator; 34import android.graphics.LinearGradient; 35import android.graphics.Matrix; 36import android.graphics.Outline; 37import android.graphics.Paint; 38import android.graphics.Path; 39import android.graphics.PathMeasure; 40import android.graphics.PixelFormat; 41import android.graphics.Point; 42import android.graphics.PorterDuff; 43import android.graphics.PorterDuffXfermode; 44import android.graphics.Rect; 45import android.graphics.RectF; 46import android.graphics.Region; 47import android.graphics.Shader; 48import android.graphics.drawable.ColorDrawable; 49import android.graphics.drawable.Drawable; 50import android.hardware.display.DisplayManagerGlobal; 51import android.os.Bundle; 52import android.os.Handler; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.os.Trace; 60import android.text.TextUtils; 61import android.util.AttributeSet; 62import android.util.FloatProperty; 63import android.util.LayoutDirection; 64import android.util.Log; 65import android.util.LongSparseLongArray; 66import android.util.Pools.SynchronizedPool; 67import android.util.Property; 68import android.util.SparseArray; 69import android.util.StateSet; 70import android.util.SuperNotCalledException; 71import android.util.TypedValue; 72import android.view.ContextMenu.ContextMenuInfo; 73import android.view.AccessibilityIterators.TextSegmentIterator; 74import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 75import android.view.AccessibilityIterators.WordTextSegmentIterator; 76import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 77import android.view.accessibility.AccessibilityEvent; 78import android.view.accessibility.AccessibilityEventSource; 79import android.view.accessibility.AccessibilityManager; 80import android.view.accessibility.AccessibilityNodeInfo; 81import android.view.accessibility.AccessibilityNodeProvider; 82import android.view.animation.Animation; 83import android.view.animation.AnimationUtils; 84import android.view.animation.Transformation; 85import android.view.inputmethod.EditorInfo; 86import android.view.inputmethod.InputConnection; 87import android.view.inputmethod.InputMethodManager; 88import android.widget.ScrollBarDrawable; 89 90import static android.os.Build.VERSION_CODES.*; 91import static java.lang.Math.max; 92 93import com.android.internal.R; 94import com.android.internal.util.Predicate; 95import com.android.internal.view.menu.MenuBuilder; 96import com.google.android.collect.Lists; 97import com.google.android.collect.Maps; 98 99import java.lang.annotation.Retention; 100import java.lang.annotation.RetentionPolicy; 101import java.lang.ref.WeakReference; 102import java.lang.reflect.Field; 103import java.lang.reflect.InvocationTargetException; 104import java.lang.reflect.Method; 105import java.lang.reflect.Modifier; 106import java.util.ArrayList; 107import java.util.Arrays; 108import java.util.Collections; 109import java.util.HashMap; 110import java.util.List; 111import java.util.Locale; 112import java.util.Map; 113import java.util.concurrent.CopyOnWriteArrayList; 114import java.util.concurrent.atomic.AtomicInteger; 115 116/** 117 * <p> 118 * This class represents the basic building block for user interface components. A View 119 * occupies a rectangular area on the screen and is responsible for drawing and 120 * event handling. View is the base class for <em>widgets</em>, which are 121 * used to create interactive UI components (buttons, text fields, etc.). The 122 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 123 * are invisible containers that hold other Views (or other ViewGroups) and define 124 * their layout properties. 125 * </p> 126 * 127 * <div class="special reference"> 128 * <h3>Developer Guides</h3> 129 * <p>For information about using this class to develop your application's user interface, 130 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 131 * </div> 132 * 133 * <a name="Using"></a> 134 * <h3>Using Views</h3> 135 * <p> 136 * All of the views in a window are arranged in a single tree. You can add views 137 * either from code or by specifying a tree of views in one or more XML layout 138 * files. There are many specialized subclasses of views that act as controls or 139 * are capable of displaying text, images, or other content. 140 * </p> 141 * <p> 142 * Once you have created a tree of views, there are typically a few types of 143 * common operations you may wish to perform: 144 * <ul> 145 * <li><strong>Set properties:</strong> for example setting the text of a 146 * {@link android.widget.TextView}. The available properties and the methods 147 * that set them will vary among the different subclasses of views. Note that 148 * properties that are known at build time can be set in the XML layout 149 * files.</li> 150 * <li><strong>Set focus:</strong> The framework will handled moving focus in 151 * response to user input. To force focus to a specific view, call 152 * {@link #requestFocus}.</li> 153 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 154 * that will be notified when something interesting happens to the view. For 155 * example, all views will let you set a listener to be notified when the view 156 * gains or loses focus. You can register such a listener using 157 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 158 * Other view subclasses offer more specialized listeners. For example, a Button 159 * exposes a listener to notify clients when the button is clicked.</li> 160 * <li><strong>Set visibility:</strong> You can hide or show views using 161 * {@link #setVisibility(int)}.</li> 162 * </ul> 163 * </p> 164 * <p><em> 165 * Note: The Android framework is responsible for measuring, laying out and 166 * drawing views. You should not call methods that perform these actions on 167 * views yourself unless you are actually implementing a 168 * {@link android.view.ViewGroup}. 169 * </em></p> 170 * 171 * <a name="Lifecycle"></a> 172 * <h3>Implementing a Custom View</h3> 173 * 174 * <p> 175 * To implement a custom view, you will usually begin by providing overrides for 176 * some of the standard methods that the framework calls on all views. You do 177 * not need to override all of these methods. In fact, you can start by just 178 * overriding {@link #onDraw(android.graphics.Canvas)}. 179 * <table border="2" width="85%" align="center" cellpadding="5"> 180 * <thead> 181 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 182 * </thead> 183 * 184 * <tbody> 185 * <tr> 186 * <td rowspan="2">Creation</td> 187 * <td>Constructors</td> 188 * <td>There is a form of the constructor that are called when the view 189 * is created from code and a form that is called when the view is 190 * inflated from a layout file. The second form should parse and apply 191 * any attributes defined in the layout file. 192 * </td> 193 * </tr> 194 * <tr> 195 * <td><code>{@link #onFinishInflate()}</code></td> 196 * <td>Called after a view and all of its children has been inflated 197 * from XML.</td> 198 * </tr> 199 * 200 * <tr> 201 * <td rowspan="3">Layout</td> 202 * <td><code>{@link #onMeasure(int, int)}</code></td> 203 * <td>Called to determine the size requirements for this view and all 204 * of its children. 205 * </td> 206 * </tr> 207 * <tr> 208 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 209 * <td>Called when this view should assign a size and position to all 210 * of its children. 211 * </td> 212 * </tr> 213 * <tr> 214 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 215 * <td>Called when the size of this view has changed. 216 * </td> 217 * </tr> 218 * 219 * <tr> 220 * <td>Drawing</td> 221 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 222 * <td>Called when the view should render its content. 223 * </td> 224 * </tr> 225 * 226 * <tr> 227 * <td rowspan="4">Event processing</td> 228 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 229 * <td>Called when a new hardware key event occurs. 230 * </td> 231 * </tr> 232 * <tr> 233 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 234 * <td>Called when a hardware key up event occurs. 235 * </td> 236 * </tr> 237 * <tr> 238 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 239 * <td>Called when a trackball motion event occurs. 240 * </td> 241 * </tr> 242 * <tr> 243 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 244 * <td>Called when a touch screen motion event occurs. 245 * </td> 246 * </tr> 247 * 248 * <tr> 249 * <td rowspan="2">Focus</td> 250 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 251 * <td>Called when the view gains or loses focus. 252 * </td> 253 * </tr> 254 * 255 * <tr> 256 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 257 * <td>Called when the window containing the view gains or loses focus. 258 * </td> 259 * </tr> 260 * 261 * <tr> 262 * <td rowspan="3">Attaching</td> 263 * <td><code>{@link #onAttachedToWindow()}</code></td> 264 * <td>Called when the view is attached to a window. 265 * </td> 266 * </tr> 267 * 268 * <tr> 269 * <td><code>{@link #onDetachedFromWindow}</code></td> 270 * <td>Called when the view is detached from its window. 271 * </td> 272 * </tr> 273 * 274 * <tr> 275 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 276 * <td>Called when the visibility of the window containing the view 277 * has changed. 278 * </td> 279 * </tr> 280 * </tbody> 281 * 282 * </table> 283 * </p> 284 * 285 * <a name="IDs"></a> 286 * <h3>IDs</h3> 287 * Views may have an integer id associated with them. These ids are typically 288 * assigned in the layout XML files, and are used to find specific views within 289 * the view tree. A common pattern is to: 290 * <ul> 291 * <li>Define a Button in the layout file and assign it a unique ID. 292 * <pre> 293 * <Button 294 * android:id="@+id/my_button" 295 * android:layout_width="wrap_content" 296 * android:layout_height="wrap_content" 297 * android:text="@string/my_button_text"/> 298 * </pre></li> 299 * <li>From the onCreate method of an Activity, find the Button 300 * <pre class="prettyprint"> 301 * Button myButton = (Button) findViewById(R.id.my_button); 302 * </pre></li> 303 * </ul> 304 * <p> 305 * View IDs need not be unique throughout the tree, but it is good practice to 306 * ensure that they are at least unique within the part of the tree you are 307 * searching. 308 * </p> 309 * 310 * <a name="Position"></a> 311 * <h3>Position</h3> 312 * <p> 313 * The geometry of a view is that of a rectangle. A view has a location, 314 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 315 * two dimensions, expressed as a width and a height. The unit for location 316 * and dimensions is the pixel. 317 * </p> 318 * 319 * <p> 320 * It is possible to retrieve the location of a view by invoking the methods 321 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 322 * coordinate of the rectangle representing the view. The latter returns the 323 * top, or Y, coordinate of the rectangle representing the view. These methods 324 * both return the location of the view relative to its parent. For instance, 325 * when getLeft() returns 20, that means the view is located 20 pixels to the 326 * right of the left edge of its direct parent. 327 * </p> 328 * 329 * <p> 330 * In addition, several convenience methods are offered to avoid unnecessary 331 * computations, namely {@link #getRight()} and {@link #getBottom()}. 332 * These methods return the coordinates of the right and bottom edges of the 333 * rectangle representing the view. For instance, calling {@link #getRight()} 334 * is similar to the following computation: <code>getLeft() + getWidth()</code> 335 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 336 * </p> 337 * 338 * <a name="SizePaddingMargins"></a> 339 * <h3>Size, padding and margins</h3> 340 * <p> 341 * The size of a view is expressed with a width and a height. A view actually 342 * possess two pairs of width and height values. 343 * </p> 344 * 345 * <p> 346 * The first pair is known as <em>measured width</em> and 347 * <em>measured height</em>. These dimensions define how big a view wants to be 348 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 349 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 350 * and {@link #getMeasuredHeight()}. 351 * </p> 352 * 353 * <p> 354 * The second pair is simply known as <em>width</em> and <em>height</em>, or 355 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 356 * dimensions define the actual size of the view on screen, at drawing time and 357 * after layout. These values may, but do not have to, be different from the 358 * measured width and height. The width and height can be obtained by calling 359 * {@link #getWidth()} and {@link #getHeight()}. 360 * </p> 361 * 362 * <p> 363 * To measure its dimensions, a view takes into account its padding. The padding 364 * is expressed in pixels for the left, top, right and bottom parts of the view. 365 * Padding can be used to offset the content of the view by a specific amount of 366 * pixels. For instance, a left padding of 2 will push the view's content by 367 * 2 pixels to the right of the left edge. Padding can be set using the 368 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 369 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 370 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 371 * {@link #getPaddingEnd()}. 372 * </p> 373 * 374 * <p> 375 * Even though a view can define a padding, it does not provide any support for 376 * margins. However, view groups provide such a support. Refer to 377 * {@link android.view.ViewGroup} and 378 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 379 * </p> 380 * 381 * <a name="Layout"></a> 382 * <h3>Layout</h3> 383 * <p> 384 * Layout is a two pass process: a measure pass and a layout pass. The measuring 385 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 386 * of the view tree. Each view pushes dimension specifications down the tree 387 * during the recursion. At the end of the measure pass, every view has stored 388 * its measurements. The second pass happens in 389 * {@link #layout(int,int,int,int)} and is also top-down. During 390 * this pass each parent is responsible for positioning all of its children 391 * using the sizes computed in the measure pass. 392 * </p> 393 * 394 * <p> 395 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 396 * {@link #getMeasuredHeight()} values must be set, along with those for all of 397 * that view's descendants. A view's measured width and measured height values 398 * must respect the constraints imposed by the view's parents. This guarantees 399 * that at the end of the measure pass, all parents accept all of their 400 * children's measurements. A parent view may call measure() more than once on 401 * its children. For example, the parent may measure each child once with 402 * unspecified dimensions to find out how big they want to be, then call 403 * measure() on them again with actual numbers if the sum of all the children's 404 * unconstrained sizes is too big or too small. 405 * </p> 406 * 407 * <p> 408 * The measure pass uses two classes to communicate dimensions. The 409 * {@link MeasureSpec} class is used by views to tell their parents how they 410 * want to be measured and positioned. The base LayoutParams class just 411 * describes how big the view wants to be for both width and height. For each 412 * dimension, it can specify one of: 413 * <ul> 414 * <li> an exact number 415 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 416 * (minus padding) 417 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 418 * enclose its content (plus padding). 419 * </ul> 420 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 421 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 422 * an X and Y value. 423 * </p> 424 * 425 * <p> 426 * MeasureSpecs are used to push requirements down the tree from parent to 427 * child. A MeasureSpec can be in one of three modes: 428 * <ul> 429 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 430 * of a child view. For example, a LinearLayout may call measure() on its child 431 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 432 * tall the child view wants to be given a width of 240 pixels. 433 * <li>EXACTLY: This is used by the parent to impose an exact size on the 434 * child. The child must use this size, and guarantee that all of its 435 * descendants will fit within this size. 436 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 437 * child. The child must guarantee that it and all of its descendants will fit 438 * within this size. 439 * </ul> 440 * </p> 441 * 442 * <p> 443 * To initiate a layout, call {@link #requestLayout}. This method is typically 444 * called by a view on itself when it believes that is can no longer fit within 445 * its current bounds. 446 * </p> 447 * 448 * <a name="Drawing"></a> 449 * <h3>Drawing</h3> 450 * <p> 451 * Drawing is handled by walking the tree and recording the drawing commands of 452 * any View that needs to update. After this, the drawing commands of the 453 * entire tree are issued to screen, clipped to the newly damaged area. 454 * </p> 455 * 456 * <p> 457 * The tree is largely recorded and drawn in order, with parents drawn before 458 * (i.e., behind) their children, with siblings drawn in the order they appear 459 * in the tree. If you set a background drawable for a View, then the View will 460 * draw it before calling back to its <code>onDraw()</code> method. The child 461 * drawing order can be overridden with 462 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 463 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 464 * </p> 465 * 466 * <p> 467 * To force a view to draw, call {@link #invalidate()}. 468 * </p> 469 * 470 * <a name="EventHandlingThreading"></a> 471 * <h3>Event Handling and Threading</h3> 472 * <p> 473 * The basic cycle of a view is as follows: 474 * <ol> 475 * <li>An event comes in and is dispatched to the appropriate view. The view 476 * handles the event and notifies any listeners.</li> 477 * <li>If in the course of processing the event, the view's bounds may need 478 * to be changed, the view will call {@link #requestLayout()}.</li> 479 * <li>Similarly, if in the course of processing the event the view's appearance 480 * may need to be changed, the view will call {@link #invalidate()}.</li> 481 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 482 * the framework will take care of measuring, laying out, and drawing the tree 483 * as appropriate.</li> 484 * </ol> 485 * </p> 486 * 487 * <p><em>Note: The entire view tree is single threaded. You must always be on 488 * the UI thread when calling any method on any view.</em> 489 * If you are doing work on other threads and want to update the state of a view 490 * from that thread, you should use a {@link Handler}. 491 * </p> 492 * 493 * <a name="FocusHandling"></a> 494 * <h3>Focus Handling</h3> 495 * <p> 496 * The framework will handle routine focus movement in response to user input. 497 * This includes changing the focus as views are removed or hidden, or as new 498 * views become available. Views indicate their willingness to take focus 499 * through the {@link #isFocusable} method. To change whether a view can take 500 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 501 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 502 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 503 * </p> 504 * <p> 505 * Focus movement is based on an algorithm which finds the nearest neighbor in a 506 * given direction. In rare cases, the default algorithm may not match the 507 * intended behavior of the developer. In these situations, you can provide 508 * explicit overrides by using these XML attributes in the layout file: 509 * <pre> 510 * nextFocusDown 511 * nextFocusLeft 512 * nextFocusRight 513 * nextFocusUp 514 * </pre> 515 * </p> 516 * 517 * 518 * <p> 519 * To get a particular view to take focus, call {@link #requestFocus()}. 520 * </p> 521 * 522 * <a name="TouchMode"></a> 523 * <h3>Touch Mode</h3> 524 * <p> 525 * When a user is navigating a user interface via directional keys such as a D-pad, it is 526 * necessary to give focus to actionable items such as buttons so the user can see 527 * what will take input. If the device has touch capabilities, however, and the user 528 * begins interacting with the interface by touching it, it is no longer necessary to 529 * always highlight, or give focus to, a particular view. This motivates a mode 530 * for interaction named 'touch mode'. 531 * </p> 532 * <p> 533 * For a touch capable device, once the user touches the screen, the device 534 * will enter touch mode. From this point onward, only views for which 535 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 536 * Other views that are touchable, like buttons, will not take focus when touched; they will 537 * only fire the on click listeners. 538 * </p> 539 * <p> 540 * Any time a user hits a directional key, such as a D-pad direction, the view device will 541 * exit touch mode, and find a view to take focus, so that the user may resume interacting 542 * with the user interface without touching the screen again. 543 * </p> 544 * <p> 545 * The touch mode state is maintained across {@link android.app.Activity}s. Call 546 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 547 * </p> 548 * 549 * <a name="Scrolling"></a> 550 * <h3>Scrolling</h3> 551 * <p> 552 * The framework provides basic support for views that wish to internally 553 * scroll their content. This includes keeping track of the X and Y scroll 554 * offset as well as mechanisms for drawing scrollbars. See 555 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 556 * {@link #awakenScrollBars()} for more details. 557 * </p> 558 * 559 * <a name="Tags"></a> 560 * <h3>Tags</h3> 561 * <p> 562 * Unlike IDs, tags are not used to identify views. Tags are essentially an 563 * extra piece of information that can be associated with a view. They are most 564 * often used as a convenience to store data related to views in the views 565 * themselves rather than by putting them in a separate structure. 566 * </p> 567 * 568 * <a name="Properties"></a> 569 * <h3>Properties</h3> 570 * <p> 571 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 572 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 573 * available both in the {@link Property} form as well as in similarly-named setter/getter 574 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 575 * be used to set persistent state associated with these rendering-related properties on the view. 576 * The properties and methods can also be used in conjunction with 577 * {@link android.animation.Animator Animator}-based animations, described more in the 578 * <a href="#Animation">Animation</a> section. 579 * </p> 580 * 581 * <a name="Animation"></a> 582 * <h3>Animation</h3> 583 * <p> 584 * Starting with Android 3.0, the preferred way of animating views is to use the 585 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 586 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 587 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 588 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 589 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 590 * makes animating these View properties particularly easy and efficient. 591 * </p> 592 * <p> 593 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 594 * You can attach an {@link Animation} object to a view using 595 * {@link #setAnimation(Animation)} or 596 * {@link #startAnimation(Animation)}. The animation can alter the scale, 597 * rotation, translation and alpha of a view over time. If the animation is 598 * attached to a view that has children, the animation will affect the entire 599 * subtree rooted by that node. When an animation is started, the framework will 600 * take care of redrawing the appropriate views until the animation completes. 601 * </p> 602 * 603 * <a name="Security"></a> 604 * <h3>Security</h3> 605 * <p> 606 * Sometimes it is essential that an application be able to verify that an action 607 * is being performed with the full knowledge and consent of the user, such as 608 * granting a permission request, making a purchase or clicking on an advertisement. 609 * Unfortunately, a malicious application could try to spoof the user into 610 * performing these actions, unaware, by concealing the intended purpose of the view. 611 * As a remedy, the framework offers a touch filtering mechanism that can be used to 612 * improve the security of views that provide access to sensitive functionality. 613 * </p><p> 614 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 615 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 616 * will discard touches that are received whenever the view's window is obscured by 617 * another visible window. As a result, the view will not receive touches whenever a 618 * toast, dialog or other window appears above the view's window. 619 * </p><p> 620 * For more fine-grained control over security, consider overriding the 621 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 622 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 623 * </p> 624 * 625 * @attr ref android.R.styleable#View_alpha 626 * @attr ref android.R.styleable#View_background 627 * @attr ref android.R.styleable#View_clickable 628 * @attr ref android.R.styleable#View_contentDescription 629 * @attr ref android.R.styleable#View_drawingCacheQuality 630 * @attr ref android.R.styleable#View_duplicateParentState 631 * @attr ref android.R.styleable#View_id 632 * @attr ref android.R.styleable#View_requiresFadingEdge 633 * @attr ref android.R.styleable#View_fadeScrollbars 634 * @attr ref android.R.styleable#View_fadingEdgeLength 635 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 636 * @attr ref android.R.styleable#View_fitsSystemWindows 637 * @attr ref android.R.styleable#View_isScrollContainer 638 * @attr ref android.R.styleable#View_focusable 639 * @attr ref android.R.styleable#View_focusableInTouchMode 640 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 641 * @attr ref android.R.styleable#View_keepScreenOn 642 * @attr ref android.R.styleable#View_layerType 643 * @attr ref android.R.styleable#View_layoutDirection 644 * @attr ref android.R.styleable#View_longClickable 645 * @attr ref android.R.styleable#View_minHeight 646 * @attr ref android.R.styleable#View_minWidth 647 * @attr ref android.R.styleable#View_nextFocusDown 648 * @attr ref android.R.styleable#View_nextFocusLeft 649 * @attr ref android.R.styleable#View_nextFocusRight 650 * @attr ref android.R.styleable#View_nextFocusUp 651 * @attr ref android.R.styleable#View_onClick 652 * @attr ref android.R.styleable#View_padding 653 * @attr ref android.R.styleable#View_paddingBottom 654 * @attr ref android.R.styleable#View_paddingLeft 655 * @attr ref android.R.styleable#View_paddingRight 656 * @attr ref android.R.styleable#View_paddingTop 657 * @attr ref android.R.styleable#View_paddingStart 658 * @attr ref android.R.styleable#View_paddingEnd 659 * @attr ref android.R.styleable#View_saveEnabled 660 * @attr ref android.R.styleable#View_rotation 661 * @attr ref android.R.styleable#View_rotationX 662 * @attr ref android.R.styleable#View_rotationY 663 * @attr ref android.R.styleable#View_scaleX 664 * @attr ref android.R.styleable#View_scaleY 665 * @attr ref android.R.styleable#View_scrollX 666 * @attr ref android.R.styleable#View_scrollY 667 * @attr ref android.R.styleable#View_scrollbarSize 668 * @attr ref android.R.styleable#View_scrollbarStyle 669 * @attr ref android.R.styleable#View_scrollbars 670 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 671 * @attr ref android.R.styleable#View_scrollbarFadeDuration 672 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 673 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 674 * @attr ref android.R.styleable#View_scrollbarThumbVertical 675 * @attr ref android.R.styleable#View_scrollbarTrackVertical 676 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 677 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 678 * @attr ref android.R.styleable#View_stateListAnimator 679 * @attr ref android.R.styleable#View_transitionName 680 * @attr ref android.R.styleable#View_soundEffectsEnabled 681 * @attr ref android.R.styleable#View_tag 682 * @attr ref android.R.styleable#View_textAlignment 683 * @attr ref android.R.styleable#View_textDirection 684 * @attr ref android.R.styleable#View_transformPivotX 685 * @attr ref android.R.styleable#View_transformPivotY 686 * @attr ref android.R.styleable#View_translationX 687 * @attr ref android.R.styleable#View_translationY 688 * @attr ref android.R.styleable#View_translationZ 689 * @attr ref android.R.styleable#View_visibility 690 * 691 * @see android.view.ViewGroup 692 */ 693public class View implements Drawable.Callback, KeyEvent.Callback, 694 AccessibilityEventSource { 695 private static final boolean DBG = false; 696 697 /** 698 * The logging tag used by this class with android.util.Log. 699 */ 700 protected static final String VIEW_LOG_TAG = "View"; 701 702 /** 703 * When set to true, apps will draw debugging information about their layouts. 704 * 705 * @hide 706 */ 707 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 708 709 /** 710 * When set to true, this view will save its attribute data. 711 * 712 * @hide 713 */ 714 public static boolean mDebugViewAttributes = false; 715 716 /** 717 * Used to mark a View that has no ID. 718 */ 719 public static final int NO_ID = -1; 720 721 /** 722 * Signals that compatibility booleans have been initialized according to 723 * target SDK versions. 724 */ 725 private static boolean sCompatibilityDone = false; 726 727 /** 728 * Use the old (broken) way of building MeasureSpecs. 729 */ 730 private static boolean sUseBrokenMakeMeasureSpec = false; 731 732 /** 733 * Ignore any optimizations using the measure cache. 734 */ 735 private static boolean sIgnoreMeasureCache = false; 736 737 /** 738 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 739 * calling setFlags. 740 */ 741 private static final int NOT_FOCUSABLE = 0x00000000; 742 743 /** 744 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 745 * setFlags. 746 */ 747 private static final int FOCUSABLE = 0x00000001; 748 749 /** 750 * Mask for use with setFlags indicating bits used for focus. 751 */ 752 private static final int FOCUSABLE_MASK = 0x00000001; 753 754 /** 755 * This view will adjust its padding to fit sytem windows (e.g. status bar) 756 */ 757 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 758 759 /** @hide */ 760 @IntDef({VISIBLE, INVISIBLE, GONE}) 761 @Retention(RetentionPolicy.SOURCE) 762 public @interface Visibility {} 763 764 /** 765 * This view is visible. 766 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 767 * android:visibility}. 768 */ 769 public static final int VISIBLE = 0x00000000; 770 771 /** 772 * This view is invisible, but it still takes up space for layout purposes. 773 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 774 * android:visibility}. 775 */ 776 public static final int INVISIBLE = 0x00000004; 777 778 /** 779 * This view is invisible, and it doesn't take any space for layout 780 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 781 * android:visibility}. 782 */ 783 public static final int GONE = 0x00000008; 784 785 /** 786 * Mask for use with setFlags indicating bits used for visibility. 787 * {@hide} 788 */ 789 static final int VISIBILITY_MASK = 0x0000000C; 790 791 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 792 793 /** 794 * This view is enabled. Interpretation varies by subclass. 795 * Use with ENABLED_MASK when calling setFlags. 796 * {@hide} 797 */ 798 static final int ENABLED = 0x00000000; 799 800 /** 801 * This view is disabled. Interpretation varies by subclass. 802 * Use with ENABLED_MASK when calling setFlags. 803 * {@hide} 804 */ 805 static final int DISABLED = 0x00000020; 806 807 /** 808 * Mask for use with setFlags indicating bits used for indicating whether 809 * this view is enabled 810 * {@hide} 811 */ 812 static final int ENABLED_MASK = 0x00000020; 813 814 /** 815 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 816 * called and further optimizations will be performed. It is okay to have 817 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 818 * {@hide} 819 */ 820 static final int WILL_NOT_DRAW = 0x00000080; 821 822 /** 823 * Mask for use with setFlags indicating bits used for indicating whether 824 * this view is will draw 825 * {@hide} 826 */ 827 static final int DRAW_MASK = 0x00000080; 828 829 /** 830 * <p>This view doesn't show scrollbars.</p> 831 * {@hide} 832 */ 833 static final int SCROLLBARS_NONE = 0x00000000; 834 835 /** 836 * <p>This view shows horizontal scrollbars.</p> 837 * {@hide} 838 */ 839 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 840 841 /** 842 * <p>This view shows vertical scrollbars.</p> 843 * {@hide} 844 */ 845 static final int SCROLLBARS_VERTICAL = 0x00000200; 846 847 /** 848 * <p>Mask for use with setFlags indicating bits used for indicating which 849 * scrollbars are enabled.</p> 850 * {@hide} 851 */ 852 static final int SCROLLBARS_MASK = 0x00000300; 853 854 /** 855 * Indicates that the view should filter touches when its window is obscured. 856 * Refer to the class comments for more information about this security feature. 857 * {@hide} 858 */ 859 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 860 861 /** 862 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 863 * that they are optional and should be skipped if the window has 864 * requested system UI flags that ignore those insets for layout. 865 */ 866 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 867 868 /** 869 * <p>This view doesn't show fading edges.</p> 870 * {@hide} 871 */ 872 static final int FADING_EDGE_NONE = 0x00000000; 873 874 /** 875 * <p>This view shows horizontal fading edges.</p> 876 * {@hide} 877 */ 878 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 879 880 /** 881 * <p>This view shows vertical fading edges.</p> 882 * {@hide} 883 */ 884 static final int FADING_EDGE_VERTICAL = 0x00002000; 885 886 /** 887 * <p>Mask for use with setFlags indicating bits used for indicating which 888 * fading edges are enabled.</p> 889 * {@hide} 890 */ 891 static final int FADING_EDGE_MASK = 0x00003000; 892 893 /** 894 * <p>Indicates this view can be clicked. When clickable, a View reacts 895 * to clicks by notifying the OnClickListener.<p> 896 * {@hide} 897 */ 898 static final int CLICKABLE = 0x00004000; 899 900 /** 901 * <p>Indicates this view is caching its drawing into a bitmap.</p> 902 * {@hide} 903 */ 904 static final int DRAWING_CACHE_ENABLED = 0x00008000; 905 906 /** 907 * <p>Indicates that no icicle should be saved for this view.<p> 908 * {@hide} 909 */ 910 static final int SAVE_DISABLED = 0x000010000; 911 912 /** 913 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 914 * property.</p> 915 * {@hide} 916 */ 917 static final int SAVE_DISABLED_MASK = 0x000010000; 918 919 /** 920 * <p>Indicates that no drawing cache should ever be created for this view.<p> 921 * {@hide} 922 */ 923 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 924 925 /** 926 * <p>Indicates this view can take / keep focus when int touch mode.</p> 927 * {@hide} 928 */ 929 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 930 931 /** @hide */ 932 @Retention(RetentionPolicy.SOURCE) 933 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 934 public @interface DrawingCacheQuality {} 935 936 /** 937 * <p>Enables low quality mode for the drawing cache.</p> 938 */ 939 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 940 941 /** 942 * <p>Enables high quality mode for the drawing cache.</p> 943 */ 944 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 945 946 /** 947 * <p>Enables automatic quality mode for the drawing cache.</p> 948 */ 949 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 950 951 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 952 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 953 }; 954 955 /** 956 * <p>Mask for use with setFlags indicating bits used for the cache 957 * quality property.</p> 958 * {@hide} 959 */ 960 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 961 962 /** 963 * <p> 964 * Indicates this view can be long clicked. When long clickable, a View 965 * reacts to long clicks by notifying the OnLongClickListener or showing a 966 * context menu. 967 * </p> 968 * {@hide} 969 */ 970 static final int LONG_CLICKABLE = 0x00200000; 971 972 /** 973 * <p>Indicates that this view gets its drawable states from its direct parent 974 * and ignores its original internal states.</p> 975 * 976 * @hide 977 */ 978 static final int DUPLICATE_PARENT_STATE = 0x00400000; 979 980 /** @hide */ 981 @IntDef({ 982 SCROLLBARS_INSIDE_OVERLAY, 983 SCROLLBARS_INSIDE_INSET, 984 SCROLLBARS_OUTSIDE_OVERLAY, 985 SCROLLBARS_OUTSIDE_INSET 986 }) 987 @Retention(RetentionPolicy.SOURCE) 988 public @interface ScrollBarStyle {} 989 990 /** 991 * The scrollbar style to display the scrollbars inside the content area, 992 * without increasing the padding. The scrollbars will be overlaid with 993 * translucency on the view's content. 994 */ 995 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 996 997 /** 998 * The scrollbar style to display the scrollbars inside the padded area, 999 * increasing the padding of the view. The scrollbars will not overlap the 1000 * content area of the view. 1001 */ 1002 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1003 1004 /** 1005 * The scrollbar style to display the scrollbars at the edge of the view, 1006 * without increasing the padding. The scrollbars will be overlaid with 1007 * translucency. 1008 */ 1009 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1010 1011 /** 1012 * The scrollbar style to display the scrollbars at the edge of the view, 1013 * increasing the padding of the view. The scrollbars will only overlap the 1014 * background, if any. 1015 */ 1016 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1017 1018 /** 1019 * Mask to check if the scrollbar style is overlay or inset. 1020 * {@hide} 1021 */ 1022 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1023 1024 /** 1025 * Mask to check if the scrollbar style is inside or outside. 1026 * {@hide} 1027 */ 1028 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1029 1030 /** 1031 * Mask for scrollbar style. 1032 * {@hide} 1033 */ 1034 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1035 1036 /** 1037 * View flag indicating that the screen should remain on while the 1038 * window containing this view is visible to the user. This effectively 1039 * takes care of automatically setting the WindowManager's 1040 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1041 */ 1042 public static final int KEEP_SCREEN_ON = 0x04000000; 1043 1044 /** 1045 * View flag indicating whether this view should have sound effects enabled 1046 * for events such as clicking and touching. 1047 */ 1048 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1049 1050 /** 1051 * View flag indicating whether this view should have haptic feedback 1052 * enabled for events such as long presses. 1053 */ 1054 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1055 1056 /** 1057 * <p>Indicates that the view hierarchy should stop saving state when 1058 * it reaches this view. If state saving is initiated immediately at 1059 * the view, it will be allowed. 1060 * {@hide} 1061 */ 1062 static final int PARENT_SAVE_DISABLED = 0x20000000; 1063 1064 /** 1065 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1066 * {@hide} 1067 */ 1068 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1069 1070 /** @hide */ 1071 @IntDef(flag = true, 1072 value = { 1073 FOCUSABLES_ALL, 1074 FOCUSABLES_TOUCH_MODE 1075 }) 1076 @Retention(RetentionPolicy.SOURCE) 1077 public @interface FocusableMode {} 1078 1079 /** 1080 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1081 * should add all focusable Views regardless if they are focusable in touch mode. 1082 */ 1083 public static final int FOCUSABLES_ALL = 0x00000000; 1084 1085 /** 1086 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1087 * should add only Views focusable in touch mode. 1088 */ 1089 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1090 1091 /** @hide */ 1092 @IntDef({ 1093 FOCUS_BACKWARD, 1094 FOCUS_FORWARD, 1095 FOCUS_LEFT, 1096 FOCUS_UP, 1097 FOCUS_RIGHT, 1098 FOCUS_DOWN 1099 }) 1100 @Retention(RetentionPolicy.SOURCE) 1101 public @interface FocusDirection {} 1102 1103 /** @hide */ 1104 @IntDef({ 1105 FOCUS_LEFT, 1106 FOCUS_UP, 1107 FOCUS_RIGHT, 1108 FOCUS_DOWN 1109 }) 1110 @Retention(RetentionPolicy.SOURCE) 1111 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1112 1113 /** 1114 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1115 * item. 1116 */ 1117 public static final int FOCUS_BACKWARD = 0x00000001; 1118 1119 /** 1120 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1121 * item. 1122 */ 1123 public static final int FOCUS_FORWARD = 0x00000002; 1124 1125 /** 1126 * Use with {@link #focusSearch(int)}. Move focus to the left. 1127 */ 1128 public static final int FOCUS_LEFT = 0x00000011; 1129 1130 /** 1131 * Use with {@link #focusSearch(int)}. Move focus up. 1132 */ 1133 public static final int FOCUS_UP = 0x00000021; 1134 1135 /** 1136 * Use with {@link #focusSearch(int)}. Move focus to the right. 1137 */ 1138 public static final int FOCUS_RIGHT = 0x00000042; 1139 1140 /** 1141 * Use with {@link #focusSearch(int)}. Move focus down. 1142 */ 1143 public static final int FOCUS_DOWN = 0x00000082; 1144 1145 /** 1146 * Bits of {@link #getMeasuredWidthAndState()} and 1147 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1148 */ 1149 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1150 1151 /** 1152 * Bits of {@link #getMeasuredWidthAndState()} and 1153 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1154 */ 1155 public static final int MEASURED_STATE_MASK = 0xff000000; 1156 1157 /** 1158 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1159 * for functions that combine both width and height into a single int, 1160 * such as {@link #getMeasuredState()} and the childState argument of 1161 * {@link #resolveSizeAndState(int, int, int)}. 1162 */ 1163 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1164 1165 /** 1166 * Bit of {@link #getMeasuredWidthAndState()} and 1167 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1168 * is smaller that the space the view would like to have. 1169 */ 1170 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1171 1172 /** 1173 * Base View state sets 1174 */ 1175 // Singles 1176 /** 1177 * Indicates the view has no states set. States are used with 1178 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1179 * view depending on its state. 1180 * 1181 * @see android.graphics.drawable.Drawable 1182 * @see #getDrawableState() 1183 */ 1184 protected static final int[] EMPTY_STATE_SET; 1185 /** 1186 * Indicates the view is enabled. States are used with 1187 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1188 * view depending on its state. 1189 * 1190 * @see android.graphics.drawable.Drawable 1191 * @see #getDrawableState() 1192 */ 1193 protected static final int[] ENABLED_STATE_SET; 1194 /** 1195 * Indicates the view is focused. States are used with 1196 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1197 * view depending on its state. 1198 * 1199 * @see android.graphics.drawable.Drawable 1200 * @see #getDrawableState() 1201 */ 1202 protected static final int[] FOCUSED_STATE_SET; 1203 /** 1204 * Indicates the view is selected. States are used with 1205 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1206 * view depending on its state. 1207 * 1208 * @see android.graphics.drawable.Drawable 1209 * @see #getDrawableState() 1210 */ 1211 protected static final int[] SELECTED_STATE_SET; 1212 /** 1213 * Indicates the view is pressed. States are used with 1214 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1215 * view depending on its state. 1216 * 1217 * @see android.graphics.drawable.Drawable 1218 * @see #getDrawableState() 1219 */ 1220 protected static final int[] PRESSED_STATE_SET; 1221 /** 1222 * Indicates the view's window has focus. States are used with 1223 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1224 * view depending on its state. 1225 * 1226 * @see android.graphics.drawable.Drawable 1227 * @see #getDrawableState() 1228 */ 1229 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1230 // Doubles 1231 /** 1232 * Indicates the view is enabled and has the focus. 1233 * 1234 * @see #ENABLED_STATE_SET 1235 * @see #FOCUSED_STATE_SET 1236 */ 1237 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1238 /** 1239 * Indicates the view is enabled and selected. 1240 * 1241 * @see #ENABLED_STATE_SET 1242 * @see #SELECTED_STATE_SET 1243 */ 1244 protected static final int[] ENABLED_SELECTED_STATE_SET; 1245 /** 1246 * Indicates the view is enabled and that its window has focus. 1247 * 1248 * @see #ENABLED_STATE_SET 1249 * @see #WINDOW_FOCUSED_STATE_SET 1250 */ 1251 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1252 /** 1253 * Indicates the view is focused and selected. 1254 * 1255 * @see #FOCUSED_STATE_SET 1256 * @see #SELECTED_STATE_SET 1257 */ 1258 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1259 /** 1260 * Indicates the view has the focus and that its window has the focus. 1261 * 1262 * @see #FOCUSED_STATE_SET 1263 * @see #WINDOW_FOCUSED_STATE_SET 1264 */ 1265 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1266 /** 1267 * Indicates the view is selected and that its window has the focus. 1268 * 1269 * @see #SELECTED_STATE_SET 1270 * @see #WINDOW_FOCUSED_STATE_SET 1271 */ 1272 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1273 // Triples 1274 /** 1275 * Indicates the view is enabled, focused and selected. 1276 * 1277 * @see #ENABLED_STATE_SET 1278 * @see #FOCUSED_STATE_SET 1279 * @see #SELECTED_STATE_SET 1280 */ 1281 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1282 /** 1283 * Indicates the view is enabled, focused and its window has the focus. 1284 * 1285 * @see #ENABLED_STATE_SET 1286 * @see #FOCUSED_STATE_SET 1287 * @see #WINDOW_FOCUSED_STATE_SET 1288 */ 1289 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1290 /** 1291 * Indicates the view is enabled, selected and its window has the focus. 1292 * 1293 * @see #ENABLED_STATE_SET 1294 * @see #SELECTED_STATE_SET 1295 * @see #WINDOW_FOCUSED_STATE_SET 1296 */ 1297 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1298 /** 1299 * Indicates the view is focused, selected and its window has the focus. 1300 * 1301 * @see #FOCUSED_STATE_SET 1302 * @see #SELECTED_STATE_SET 1303 * @see #WINDOW_FOCUSED_STATE_SET 1304 */ 1305 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1306 /** 1307 * Indicates the view is enabled, focused, selected and its window 1308 * has the focus. 1309 * 1310 * @see #ENABLED_STATE_SET 1311 * @see #FOCUSED_STATE_SET 1312 * @see #SELECTED_STATE_SET 1313 * @see #WINDOW_FOCUSED_STATE_SET 1314 */ 1315 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1316 /** 1317 * Indicates the view is pressed and its window has the focus. 1318 * 1319 * @see #PRESSED_STATE_SET 1320 * @see #WINDOW_FOCUSED_STATE_SET 1321 */ 1322 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1323 /** 1324 * Indicates the view is pressed and selected. 1325 * 1326 * @see #PRESSED_STATE_SET 1327 * @see #SELECTED_STATE_SET 1328 */ 1329 protected static final int[] PRESSED_SELECTED_STATE_SET; 1330 /** 1331 * Indicates the view is pressed, selected and its window has the focus. 1332 * 1333 * @see #PRESSED_STATE_SET 1334 * @see #SELECTED_STATE_SET 1335 * @see #WINDOW_FOCUSED_STATE_SET 1336 */ 1337 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1338 /** 1339 * Indicates the view is pressed and focused. 1340 * 1341 * @see #PRESSED_STATE_SET 1342 * @see #FOCUSED_STATE_SET 1343 */ 1344 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1345 /** 1346 * Indicates the view is pressed, focused and its window has the focus. 1347 * 1348 * @see #PRESSED_STATE_SET 1349 * @see #FOCUSED_STATE_SET 1350 * @see #WINDOW_FOCUSED_STATE_SET 1351 */ 1352 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1353 /** 1354 * Indicates the view is pressed, focused and selected. 1355 * 1356 * @see #PRESSED_STATE_SET 1357 * @see #SELECTED_STATE_SET 1358 * @see #FOCUSED_STATE_SET 1359 */ 1360 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1361 /** 1362 * Indicates the view is pressed, focused, selected and its window has the focus. 1363 * 1364 * @see #PRESSED_STATE_SET 1365 * @see #FOCUSED_STATE_SET 1366 * @see #SELECTED_STATE_SET 1367 * @see #WINDOW_FOCUSED_STATE_SET 1368 */ 1369 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1370 /** 1371 * Indicates the view is pressed and enabled. 1372 * 1373 * @see #PRESSED_STATE_SET 1374 * @see #ENABLED_STATE_SET 1375 */ 1376 protected static final int[] PRESSED_ENABLED_STATE_SET; 1377 /** 1378 * Indicates the view is pressed, enabled and its window has the focus. 1379 * 1380 * @see #PRESSED_STATE_SET 1381 * @see #ENABLED_STATE_SET 1382 * @see #WINDOW_FOCUSED_STATE_SET 1383 */ 1384 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1385 /** 1386 * Indicates the view is pressed, enabled and selected. 1387 * 1388 * @see #PRESSED_STATE_SET 1389 * @see #ENABLED_STATE_SET 1390 * @see #SELECTED_STATE_SET 1391 */ 1392 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1393 /** 1394 * Indicates the view is pressed, enabled, selected and its window has the 1395 * focus. 1396 * 1397 * @see #PRESSED_STATE_SET 1398 * @see #ENABLED_STATE_SET 1399 * @see #SELECTED_STATE_SET 1400 * @see #WINDOW_FOCUSED_STATE_SET 1401 */ 1402 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1403 /** 1404 * Indicates the view is pressed, enabled and focused. 1405 * 1406 * @see #PRESSED_STATE_SET 1407 * @see #ENABLED_STATE_SET 1408 * @see #FOCUSED_STATE_SET 1409 */ 1410 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1411 /** 1412 * Indicates the view is pressed, enabled, focused and its window has the 1413 * focus. 1414 * 1415 * @see #PRESSED_STATE_SET 1416 * @see #ENABLED_STATE_SET 1417 * @see #FOCUSED_STATE_SET 1418 * @see #WINDOW_FOCUSED_STATE_SET 1419 */ 1420 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1421 /** 1422 * Indicates the view is pressed, enabled, focused and selected. 1423 * 1424 * @see #PRESSED_STATE_SET 1425 * @see #ENABLED_STATE_SET 1426 * @see #SELECTED_STATE_SET 1427 * @see #FOCUSED_STATE_SET 1428 */ 1429 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1430 /** 1431 * Indicates the view is pressed, enabled, focused, selected and its window 1432 * has the focus. 1433 * 1434 * @see #PRESSED_STATE_SET 1435 * @see #ENABLED_STATE_SET 1436 * @see #SELECTED_STATE_SET 1437 * @see #FOCUSED_STATE_SET 1438 * @see #WINDOW_FOCUSED_STATE_SET 1439 */ 1440 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1441 1442 static { 1443 EMPTY_STATE_SET = StateSet.get(0); 1444 1445 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1446 1447 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1448 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1449 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1450 1451 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1452 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1453 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1454 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1455 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1456 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1457 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1458 | StateSet.VIEW_STATE_FOCUSED); 1459 1460 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1461 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1462 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1463 ENABLED_SELECTED_STATE_SET = StateSet.get( 1464 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1465 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1466 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1467 | StateSet.VIEW_STATE_ENABLED); 1468 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1469 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1470 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1471 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1472 | StateSet.VIEW_STATE_ENABLED); 1473 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1474 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1475 | StateSet.VIEW_STATE_ENABLED); 1476 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1477 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1478 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1479 1480 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1481 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1482 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1483 PRESSED_SELECTED_STATE_SET = StateSet.get( 1484 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1485 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1486 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1487 | StateSet.VIEW_STATE_PRESSED); 1488 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1489 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1490 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1491 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1492 | StateSet.VIEW_STATE_PRESSED); 1493 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1494 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1495 | StateSet.VIEW_STATE_PRESSED); 1496 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1497 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1498 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1499 PRESSED_ENABLED_STATE_SET = StateSet.get( 1500 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1501 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1502 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1503 | StateSet.VIEW_STATE_PRESSED); 1504 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1505 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1506 | StateSet.VIEW_STATE_PRESSED); 1507 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1508 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1509 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1510 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1511 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1512 | StateSet.VIEW_STATE_PRESSED); 1513 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1514 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1515 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1516 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1517 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1518 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1519 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1520 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1521 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1522 | StateSet.VIEW_STATE_PRESSED); 1523 } 1524 1525 /** 1526 * Accessibility event types that are dispatched for text population. 1527 */ 1528 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1529 AccessibilityEvent.TYPE_VIEW_CLICKED 1530 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1531 | AccessibilityEvent.TYPE_VIEW_SELECTED 1532 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1533 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1534 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1535 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1536 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1537 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1538 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1539 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1540 1541 /** 1542 * Temporary Rect currently for use in setBackground(). This will probably 1543 * be extended in the future to hold our own class with more than just 1544 * a Rect. :) 1545 */ 1546 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1547 1548 /** 1549 * Map used to store views' tags. 1550 */ 1551 private SparseArray<Object> mKeyedTags; 1552 1553 /** 1554 * The next available accessibility id. 1555 */ 1556 private static int sNextAccessibilityViewId; 1557 1558 /** 1559 * The animation currently associated with this view. 1560 * @hide 1561 */ 1562 protected Animation mCurrentAnimation = null; 1563 1564 /** 1565 * Width as measured during measure pass. 1566 * {@hide} 1567 */ 1568 @ViewDebug.ExportedProperty(category = "measurement") 1569 int mMeasuredWidth; 1570 1571 /** 1572 * Height as measured during measure pass. 1573 * {@hide} 1574 */ 1575 @ViewDebug.ExportedProperty(category = "measurement") 1576 int mMeasuredHeight; 1577 1578 /** 1579 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1580 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1581 * its display list. This flag, used only when hw accelerated, allows us to clear the 1582 * flag while retaining this information until it's needed (at getDisplayList() time and 1583 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1584 * 1585 * {@hide} 1586 */ 1587 boolean mRecreateDisplayList = false; 1588 1589 /** 1590 * The view's identifier. 1591 * {@hide} 1592 * 1593 * @see #setId(int) 1594 * @see #getId() 1595 */ 1596 @ViewDebug.ExportedProperty(resolveId = true) 1597 int mID = NO_ID; 1598 1599 /** 1600 * The stable ID of this view for accessibility purposes. 1601 */ 1602 int mAccessibilityViewId = NO_ID; 1603 1604 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1605 1606 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1607 1608 /** 1609 * The view's tag. 1610 * {@hide} 1611 * 1612 * @see #setTag(Object) 1613 * @see #getTag() 1614 */ 1615 protected Object mTag = null; 1616 1617 // for mPrivateFlags: 1618 /** {@hide} */ 1619 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1620 /** {@hide} */ 1621 static final int PFLAG_FOCUSED = 0x00000002; 1622 /** {@hide} */ 1623 static final int PFLAG_SELECTED = 0x00000004; 1624 /** {@hide} */ 1625 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1626 /** {@hide} */ 1627 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1628 /** {@hide} */ 1629 static final int PFLAG_DRAWN = 0x00000020; 1630 /** 1631 * When this flag is set, this view is running an animation on behalf of its 1632 * children and should therefore not cancel invalidate requests, even if they 1633 * lie outside of this view's bounds. 1634 * 1635 * {@hide} 1636 */ 1637 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1638 /** {@hide} */ 1639 static final int PFLAG_SKIP_DRAW = 0x00000080; 1640 /** {@hide} */ 1641 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1642 /** {@hide} */ 1643 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1644 /** {@hide} */ 1645 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1646 /** {@hide} */ 1647 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1648 /** {@hide} */ 1649 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1650 /** {@hide} */ 1651 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1652 1653 private static final int PFLAG_PRESSED = 0x00004000; 1654 1655 /** {@hide} */ 1656 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1657 /** 1658 * Flag used to indicate that this view should be drawn once more (and only once 1659 * more) after its animation has completed. 1660 * {@hide} 1661 */ 1662 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1663 1664 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1665 1666 /** 1667 * Indicates that the View returned true when onSetAlpha() was called and that 1668 * the alpha must be restored. 1669 * {@hide} 1670 */ 1671 static final int PFLAG_ALPHA_SET = 0x00040000; 1672 1673 /** 1674 * Set by {@link #setScrollContainer(boolean)}. 1675 */ 1676 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1677 1678 /** 1679 * Set by {@link #setScrollContainer(boolean)}. 1680 */ 1681 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1682 1683 /** 1684 * View flag indicating whether this view was invalidated (fully or partially.) 1685 * 1686 * @hide 1687 */ 1688 static final int PFLAG_DIRTY = 0x00200000; 1689 1690 /** 1691 * View flag indicating whether this view was invalidated by an opaque 1692 * invalidate request. 1693 * 1694 * @hide 1695 */ 1696 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1697 1698 /** 1699 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1700 * 1701 * @hide 1702 */ 1703 static final int PFLAG_DIRTY_MASK = 0x00600000; 1704 1705 /** 1706 * Indicates whether the background is opaque. 1707 * 1708 * @hide 1709 */ 1710 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1711 1712 /** 1713 * Indicates whether the scrollbars are opaque. 1714 * 1715 * @hide 1716 */ 1717 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1718 1719 /** 1720 * Indicates whether the view is opaque. 1721 * 1722 * @hide 1723 */ 1724 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1725 1726 /** 1727 * Indicates a prepressed state; 1728 * the short time between ACTION_DOWN and recognizing 1729 * a 'real' press. Prepressed is used to recognize quick taps 1730 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1731 * 1732 * @hide 1733 */ 1734 private static final int PFLAG_PREPRESSED = 0x02000000; 1735 1736 /** 1737 * Indicates whether the view is temporarily detached. 1738 * 1739 * @hide 1740 */ 1741 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1742 1743 /** 1744 * Indicates that we should awaken scroll bars once attached 1745 * 1746 * @hide 1747 */ 1748 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1749 1750 /** 1751 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1752 * @hide 1753 */ 1754 private static final int PFLAG_HOVERED = 0x10000000; 1755 1756 /** 1757 * no longer needed, should be reused 1758 */ 1759 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1760 1761 /** {@hide} */ 1762 static final int PFLAG_ACTIVATED = 0x40000000; 1763 1764 /** 1765 * Indicates that this view was specifically invalidated, not just dirtied because some 1766 * child view was invalidated. The flag is used to determine when we need to recreate 1767 * a view's display list (as opposed to just returning a reference to its existing 1768 * display list). 1769 * 1770 * @hide 1771 */ 1772 static final int PFLAG_INVALIDATED = 0x80000000; 1773 1774 /** 1775 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1776 * 1777 * |-------|-------|-------|-------| 1778 * 1 PFLAG2_DRAG_CAN_ACCEPT 1779 * 1 PFLAG2_DRAG_HOVERED 1780 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1781 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1782 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1783 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1784 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1785 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1786 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1787 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1788 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1789 * 111 PFLAG2_TEXT_DIRECTION_MASK 1790 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1791 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1792 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1793 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1794 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1795 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1796 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1797 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1798 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1799 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1800 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1801 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1802 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1803 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1804 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1805 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1806 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1807 * 1 PFLAG2_VIEW_QUICK_REJECTED 1808 * 1 PFLAG2_PADDING_RESOLVED 1809 * 1 PFLAG2_DRAWABLE_RESOLVED 1810 * 1 PFLAG2_HAS_TRANSIENT_STATE 1811 * |-------|-------|-------|-------| 1812 */ 1813 1814 /** 1815 * Indicates that this view has reported that it can accept the current drag's content. 1816 * Cleared when the drag operation concludes. 1817 * @hide 1818 */ 1819 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1820 1821 /** 1822 * Indicates that this view is currently directly under the drag location in a 1823 * drag-and-drop operation involving content that it can accept. Cleared when 1824 * the drag exits the view, or when the drag operation concludes. 1825 * @hide 1826 */ 1827 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1828 1829 /** @hide */ 1830 @IntDef({ 1831 LAYOUT_DIRECTION_LTR, 1832 LAYOUT_DIRECTION_RTL, 1833 LAYOUT_DIRECTION_INHERIT, 1834 LAYOUT_DIRECTION_LOCALE 1835 }) 1836 @Retention(RetentionPolicy.SOURCE) 1837 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1838 public @interface LayoutDir {} 1839 1840 /** @hide */ 1841 @IntDef({ 1842 LAYOUT_DIRECTION_LTR, 1843 LAYOUT_DIRECTION_RTL 1844 }) 1845 @Retention(RetentionPolicy.SOURCE) 1846 public @interface ResolvedLayoutDir {} 1847 1848 /** 1849 * Horizontal layout direction of this view is from Left to Right. 1850 * Use with {@link #setLayoutDirection}. 1851 */ 1852 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1853 1854 /** 1855 * Horizontal layout direction of this view is from Right to Left. 1856 * Use with {@link #setLayoutDirection}. 1857 */ 1858 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1859 1860 /** 1861 * Horizontal layout direction of this view is inherited from its parent. 1862 * Use with {@link #setLayoutDirection}. 1863 */ 1864 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1865 1866 /** 1867 * Horizontal layout direction of this view is from deduced from the default language 1868 * script for the locale. Use with {@link #setLayoutDirection}. 1869 */ 1870 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1871 1872 /** 1873 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1874 * @hide 1875 */ 1876 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1877 1878 /** 1879 * Mask for use with private flags indicating bits used for horizontal layout direction. 1880 * @hide 1881 */ 1882 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1883 1884 /** 1885 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1886 * right-to-left direction. 1887 * @hide 1888 */ 1889 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1890 1891 /** 1892 * Indicates whether the view horizontal layout direction has been resolved. 1893 * @hide 1894 */ 1895 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1896 1897 /** 1898 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1899 * @hide 1900 */ 1901 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1902 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1903 1904 /* 1905 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1906 * flag value. 1907 * @hide 1908 */ 1909 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1910 LAYOUT_DIRECTION_LTR, 1911 LAYOUT_DIRECTION_RTL, 1912 LAYOUT_DIRECTION_INHERIT, 1913 LAYOUT_DIRECTION_LOCALE 1914 }; 1915 1916 /** 1917 * Default horizontal layout direction. 1918 */ 1919 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1920 1921 /** 1922 * Default horizontal layout direction. 1923 * @hide 1924 */ 1925 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1926 1927 /** 1928 * Text direction is inherited through {@link ViewGroup} 1929 */ 1930 public static final int TEXT_DIRECTION_INHERIT = 0; 1931 1932 /** 1933 * Text direction is using "first strong algorithm". The first strong directional character 1934 * determines the paragraph direction. If there is no strong directional character, the 1935 * paragraph direction is the view's resolved layout direction. 1936 */ 1937 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1938 1939 /** 1940 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1941 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1942 * If there are neither, the paragraph direction is the view's resolved layout direction. 1943 */ 1944 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1945 1946 /** 1947 * Text direction is forced to LTR. 1948 */ 1949 public static final int TEXT_DIRECTION_LTR = 3; 1950 1951 /** 1952 * Text direction is forced to RTL. 1953 */ 1954 public static final int TEXT_DIRECTION_RTL = 4; 1955 1956 /** 1957 * Text direction is coming from the system Locale. 1958 */ 1959 public static final int TEXT_DIRECTION_LOCALE = 5; 1960 1961 /** 1962 * Default text direction is inherited 1963 */ 1964 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 1965 1966 /** 1967 * Default resolved text direction 1968 * @hide 1969 */ 1970 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 1971 1972 /** 1973 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 1974 * @hide 1975 */ 1976 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 1977 1978 /** 1979 * Mask for use with private flags indicating bits used for text direction. 1980 * @hide 1981 */ 1982 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 1983 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 1984 1985 /** 1986 * Array of text direction flags for mapping attribute "textDirection" to correct 1987 * flag value. 1988 * @hide 1989 */ 1990 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 1991 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1992 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1993 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1994 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1995 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 1996 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 1997 }; 1998 1999 /** 2000 * Indicates whether the view text direction has been resolved. 2001 * @hide 2002 */ 2003 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2004 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2005 2006 /** 2007 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2008 * @hide 2009 */ 2010 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2011 2012 /** 2013 * Mask for use with private flags indicating bits used for resolved text direction. 2014 * @hide 2015 */ 2016 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2017 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2018 2019 /** 2020 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2021 * @hide 2022 */ 2023 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2024 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2025 2026 /** @hide */ 2027 @IntDef({ 2028 TEXT_ALIGNMENT_INHERIT, 2029 TEXT_ALIGNMENT_GRAVITY, 2030 TEXT_ALIGNMENT_CENTER, 2031 TEXT_ALIGNMENT_TEXT_START, 2032 TEXT_ALIGNMENT_TEXT_END, 2033 TEXT_ALIGNMENT_VIEW_START, 2034 TEXT_ALIGNMENT_VIEW_END 2035 }) 2036 @Retention(RetentionPolicy.SOURCE) 2037 public @interface TextAlignment {} 2038 2039 /** 2040 * Default text alignment. The text alignment of this View is inherited from its parent. 2041 * Use with {@link #setTextAlignment(int)} 2042 */ 2043 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2044 2045 /** 2046 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2047 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2048 * 2049 * Use with {@link #setTextAlignment(int)} 2050 */ 2051 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2052 2053 /** 2054 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2055 * 2056 * Use with {@link #setTextAlignment(int)} 2057 */ 2058 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2059 2060 /** 2061 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2062 * 2063 * Use with {@link #setTextAlignment(int)} 2064 */ 2065 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2066 2067 /** 2068 * Center the paragraph, e.g. ALIGN_CENTER. 2069 * 2070 * Use with {@link #setTextAlignment(int)} 2071 */ 2072 public static final int TEXT_ALIGNMENT_CENTER = 4; 2073 2074 /** 2075 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2076 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2077 * 2078 * Use with {@link #setTextAlignment(int)} 2079 */ 2080 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2081 2082 /** 2083 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2084 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2085 * 2086 * Use with {@link #setTextAlignment(int)} 2087 */ 2088 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2089 2090 /** 2091 * Default text alignment is inherited 2092 */ 2093 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2094 2095 /** 2096 * Default resolved text alignment 2097 * @hide 2098 */ 2099 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2100 2101 /** 2102 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2103 * @hide 2104 */ 2105 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2106 2107 /** 2108 * Mask for use with private flags indicating bits used for text alignment. 2109 * @hide 2110 */ 2111 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2112 2113 /** 2114 * Array of text direction flags for mapping attribute "textAlignment" to correct 2115 * flag value. 2116 * @hide 2117 */ 2118 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2119 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2120 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2121 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2122 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2123 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2124 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2125 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2126 }; 2127 2128 /** 2129 * Indicates whether the view text alignment has been resolved. 2130 * @hide 2131 */ 2132 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2133 2134 /** 2135 * Bit shift to get the resolved text alignment. 2136 * @hide 2137 */ 2138 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2139 2140 /** 2141 * Mask for use with private flags indicating bits used for text alignment. 2142 * @hide 2143 */ 2144 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2145 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2146 2147 /** 2148 * Indicates whether if the view text alignment has been resolved to gravity 2149 */ 2150 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2151 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2152 2153 // Accessiblity constants for mPrivateFlags2 2154 2155 /** 2156 * Shift for the bits in {@link #mPrivateFlags2} related to the 2157 * "importantForAccessibility" attribute. 2158 */ 2159 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2160 2161 /** 2162 * Automatically determine whether a view is important for accessibility. 2163 */ 2164 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2165 2166 /** 2167 * The view is important for accessibility. 2168 */ 2169 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2170 2171 /** 2172 * The view is not important for accessibility. 2173 */ 2174 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2175 2176 /** 2177 * The view is not important for accessibility, nor are any of its 2178 * descendant views. 2179 */ 2180 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2181 2182 /** 2183 * The default whether the view is important for accessibility. 2184 */ 2185 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2186 2187 /** 2188 * Mask for obtainig the bits which specify how to determine 2189 * whether a view is important for accessibility. 2190 */ 2191 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2192 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2193 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2194 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2195 2196 /** 2197 * Shift for the bits in {@link #mPrivateFlags2} related to the 2198 * "accessibilityLiveRegion" attribute. 2199 */ 2200 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2201 2202 /** 2203 * Live region mode specifying that accessibility services should not 2204 * automatically announce changes to this view. This is the default live 2205 * region mode for most views. 2206 * <p> 2207 * Use with {@link #setAccessibilityLiveRegion(int)}. 2208 */ 2209 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2210 2211 /** 2212 * Live region mode specifying that accessibility services should announce 2213 * changes to this view. 2214 * <p> 2215 * Use with {@link #setAccessibilityLiveRegion(int)}. 2216 */ 2217 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2218 2219 /** 2220 * Live region mode specifying that accessibility services should interrupt 2221 * ongoing speech to immediately announce changes to this view. 2222 * <p> 2223 * Use with {@link #setAccessibilityLiveRegion(int)}. 2224 */ 2225 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2226 2227 /** 2228 * The default whether the view is important for accessibility. 2229 */ 2230 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2231 2232 /** 2233 * Mask for obtaining the bits which specify a view's accessibility live 2234 * region mode. 2235 */ 2236 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2237 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2238 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2239 2240 /** 2241 * Flag indicating whether a view has accessibility focus. 2242 */ 2243 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2244 2245 /** 2246 * Flag whether the accessibility state of the subtree rooted at this view changed. 2247 */ 2248 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2249 2250 /** 2251 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2252 * is used to check whether later changes to the view's transform should invalidate the 2253 * view to force the quickReject test to run again. 2254 */ 2255 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2256 2257 /** 2258 * Flag indicating that start/end padding has been resolved into left/right padding 2259 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2260 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2261 * during measurement. In some special cases this is required such as when an adapter-based 2262 * view measures prospective children without attaching them to a window. 2263 */ 2264 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2265 2266 /** 2267 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2268 */ 2269 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2270 2271 /** 2272 * Indicates that the view is tracking some sort of transient state 2273 * that the app should not need to be aware of, but that the framework 2274 * should take special care to preserve. 2275 */ 2276 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2277 2278 /** 2279 * Group of bits indicating that RTL properties resolution is done. 2280 */ 2281 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2282 PFLAG2_TEXT_DIRECTION_RESOLVED | 2283 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2284 PFLAG2_PADDING_RESOLVED | 2285 PFLAG2_DRAWABLE_RESOLVED; 2286 2287 // There are a couple of flags left in mPrivateFlags2 2288 2289 /* End of masks for mPrivateFlags2 */ 2290 2291 /** 2292 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2293 * 2294 * |-------|-------|-------|-------| 2295 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2296 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2297 * 1 PFLAG3_IS_LAID_OUT 2298 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2299 * 1 PFLAG3_CALLED_SUPER 2300 * |-------|-------|-------|-------| 2301 */ 2302 2303 /** 2304 * Flag indicating that view has a transform animation set on it. This is used to track whether 2305 * an animation is cleared between successive frames, in order to tell the associated 2306 * DisplayList to clear its animation matrix. 2307 */ 2308 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2309 2310 /** 2311 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2312 * animation is cleared between successive frames, in order to tell the associated 2313 * DisplayList to restore its alpha value. 2314 */ 2315 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2316 2317 /** 2318 * Flag indicating that the view has been through at least one layout since it 2319 * was last attached to a window. 2320 */ 2321 static final int PFLAG3_IS_LAID_OUT = 0x4; 2322 2323 /** 2324 * Flag indicating that a call to measure() was skipped and should be done 2325 * instead when layout() is invoked. 2326 */ 2327 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2328 2329 /** 2330 * Flag indicating that an overridden method correctly called down to 2331 * the superclass implementation as required by the API spec. 2332 */ 2333 static final int PFLAG3_CALLED_SUPER = 0x10; 2334 2335 /** 2336 * Flag indicating that we're in the process of applying window insets. 2337 */ 2338 static final int PFLAG3_APPLYING_INSETS = 0x20; 2339 2340 /** 2341 * Flag indicating that we're in the process of fitting system windows using the old method. 2342 */ 2343 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2344 2345 /** 2346 * Flag indicating that nested scrolling is enabled for this view. 2347 * The view will optionally cooperate with views up its parent chain to allow for 2348 * integrated nested scrolling along the same axis. 2349 */ 2350 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2351 2352 /* End of masks for mPrivateFlags3 */ 2353 2354 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2355 2356 /** 2357 * Always allow a user to over-scroll this view, provided it is a 2358 * view that can scroll. 2359 * 2360 * @see #getOverScrollMode() 2361 * @see #setOverScrollMode(int) 2362 */ 2363 public static final int OVER_SCROLL_ALWAYS = 0; 2364 2365 /** 2366 * Allow a user to over-scroll this view only if the content is large 2367 * enough to meaningfully scroll, provided it is a view that can scroll. 2368 * 2369 * @see #getOverScrollMode() 2370 * @see #setOverScrollMode(int) 2371 */ 2372 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2373 2374 /** 2375 * Never allow a user to over-scroll this view. 2376 * 2377 * @see #getOverScrollMode() 2378 * @see #setOverScrollMode(int) 2379 */ 2380 public static final int OVER_SCROLL_NEVER = 2; 2381 2382 /** 2383 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2384 * requested the system UI (status bar) to be visible (the default). 2385 * 2386 * @see #setSystemUiVisibility(int) 2387 */ 2388 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2389 2390 /** 2391 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2392 * system UI to enter an unobtrusive "low profile" mode. 2393 * 2394 * <p>This is for use in games, book readers, video players, or any other 2395 * "immersive" application where the usual system chrome is deemed too distracting. 2396 * 2397 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2398 * 2399 * @see #setSystemUiVisibility(int) 2400 */ 2401 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2402 2403 /** 2404 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2405 * system navigation be temporarily hidden. 2406 * 2407 * <p>This is an even less obtrusive state than that called for by 2408 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2409 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2410 * those to disappear. This is useful (in conjunction with the 2411 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2412 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2413 * window flags) for displaying content using every last pixel on the display. 2414 * 2415 * <p>There is a limitation: because navigation controls are so important, the least user 2416 * interaction will cause them to reappear immediately. When this happens, both 2417 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2418 * so that both elements reappear at the same time. 2419 * 2420 * @see #setSystemUiVisibility(int) 2421 */ 2422 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2423 2424 /** 2425 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2426 * into the normal fullscreen mode so that its content can take over the screen 2427 * while still allowing the user to interact with the application. 2428 * 2429 * <p>This has the same visual effect as 2430 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2431 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2432 * meaning that non-critical screen decorations (such as the status bar) will be 2433 * hidden while the user is in the View's window, focusing the experience on 2434 * that content. Unlike the window flag, if you are using ActionBar in 2435 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2436 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2437 * hide the action bar. 2438 * 2439 * <p>This approach to going fullscreen is best used over the window flag when 2440 * it is a transient state -- that is, the application does this at certain 2441 * points in its user interaction where it wants to allow the user to focus 2442 * on content, but not as a continuous state. For situations where the application 2443 * would like to simply stay full screen the entire time (such as a game that 2444 * wants to take over the screen), the 2445 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2446 * is usually a better approach. The state set here will be removed by the system 2447 * in various situations (such as the user moving to another application) like 2448 * the other system UI states. 2449 * 2450 * <p>When using this flag, the application should provide some easy facility 2451 * for the user to go out of it. A common example would be in an e-book 2452 * reader, where tapping on the screen brings back whatever screen and UI 2453 * decorations that had been hidden while the user was immersed in reading 2454 * the book. 2455 * 2456 * @see #setSystemUiVisibility(int) 2457 */ 2458 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2459 2460 /** 2461 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2462 * flags, we would like a stable view of the content insets given to 2463 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2464 * will always represent the worst case that the application can expect 2465 * as a continuous state. In the stock Android UI this is the space for 2466 * the system bar, nav bar, and status bar, but not more transient elements 2467 * such as an input method. 2468 * 2469 * The stable layout your UI sees is based on the system UI modes you can 2470 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2471 * then you will get a stable layout for changes of the 2472 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2473 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2474 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2475 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2476 * with a stable layout. (Note that you should avoid using 2477 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2478 * 2479 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2480 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2481 * then a hidden status bar will be considered a "stable" state for purposes 2482 * here. This allows your UI to continually hide the status bar, while still 2483 * using the system UI flags to hide the action bar while still retaining 2484 * a stable layout. Note that changing the window fullscreen flag will never 2485 * provide a stable layout for a clean transition. 2486 * 2487 * <p>If you are using ActionBar in 2488 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2489 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2490 * insets it adds to those given to the application. 2491 */ 2492 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2493 2494 /** 2495 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2496 * to be laid out as if it has requested 2497 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2498 * allows it to avoid artifacts when switching in and out of that mode, at 2499 * the expense that some of its user interface may be covered by screen 2500 * decorations when they are shown. You can perform layout of your inner 2501 * UI elements to account for the navigation system UI through the 2502 * {@link #fitSystemWindows(Rect)} method. 2503 */ 2504 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2505 2506 /** 2507 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2508 * to be laid out as if it has requested 2509 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2510 * allows it to avoid artifacts when switching in and out of that mode, at 2511 * the expense that some of its user interface may be covered by screen 2512 * decorations when they are shown. You can perform layout of your inner 2513 * UI elements to account for non-fullscreen system UI through the 2514 * {@link #fitSystemWindows(Rect)} method. 2515 */ 2516 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2517 2518 /** 2519 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2520 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2521 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2522 * user interaction. 2523 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2524 * has an effect when used in combination with that flag.</p> 2525 */ 2526 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2527 2528 /** 2529 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2530 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2531 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2532 * experience while also hiding the system bars. If this flag is not set, 2533 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2534 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2535 * if the user swipes from the top of the screen. 2536 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2537 * system gestures, such as swiping from the top of the screen. These transient system bars 2538 * will overlay app’s content, may have some degree of transparency, and will automatically 2539 * hide after a short timeout. 2540 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2541 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2542 * with one or both of those flags.</p> 2543 */ 2544 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2545 2546 /** 2547 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2548 * is compatible with light status bar backgrounds. 2549 * 2550 * <p>For this to take effect, the window must request 2551 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2552 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2553 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2554 * FLAG_TRANSLUCENT_STATUS}. 2555 * 2556 * @see android.R.attr#windowHasLightStatusBar 2557 */ 2558 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2559 2560 /** 2561 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2562 */ 2563 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2564 2565 /** 2566 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2567 */ 2568 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2569 2570 /** 2571 * @hide 2572 * 2573 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2574 * out of the public fields to keep the undefined bits out of the developer's way. 2575 * 2576 * Flag to make the status bar not expandable. Unless you also 2577 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2578 */ 2579 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2580 2581 /** 2582 * @hide 2583 * 2584 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2585 * out of the public fields to keep the undefined bits out of the developer's way. 2586 * 2587 * Flag to hide notification icons and scrolling ticker text. 2588 */ 2589 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2590 2591 /** 2592 * @hide 2593 * 2594 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2595 * out of the public fields to keep the undefined bits out of the developer's way. 2596 * 2597 * Flag to disable incoming notification alerts. This will not block 2598 * icons, but it will block sound, vibrating and other visual or aural notifications. 2599 */ 2600 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2601 2602 /** 2603 * @hide 2604 * 2605 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2606 * out of the public fields to keep the undefined bits out of the developer's way. 2607 * 2608 * Flag to hide only the scrolling ticker. Note that 2609 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2610 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2611 */ 2612 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2613 2614 /** 2615 * @hide 2616 * 2617 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2618 * out of the public fields to keep the undefined bits out of the developer's way. 2619 * 2620 * Flag to hide the center system info area. 2621 */ 2622 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2623 2624 /** 2625 * @hide 2626 * 2627 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2628 * out of the public fields to keep the undefined bits out of the developer's way. 2629 * 2630 * Flag to hide only the home button. Don't use this 2631 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2632 */ 2633 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2634 2635 /** 2636 * @hide 2637 * 2638 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2639 * out of the public fields to keep the undefined bits out of the developer's way. 2640 * 2641 * Flag to hide only the back button. Don't use this 2642 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2643 */ 2644 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2645 2646 /** 2647 * @hide 2648 * 2649 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2650 * out of the public fields to keep the undefined bits out of the developer's way. 2651 * 2652 * Flag to hide only the clock. You might use this if your activity has 2653 * its own clock making the status bar's clock redundant. 2654 */ 2655 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2656 2657 /** 2658 * @hide 2659 * 2660 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2661 * out of the public fields to keep the undefined bits out of the developer's way. 2662 * 2663 * Flag to hide only the recent apps button. Don't use this 2664 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2665 */ 2666 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2667 2668 /** 2669 * @hide 2670 * 2671 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2672 * out of the public fields to keep the undefined bits out of the developer's way. 2673 * 2674 * Flag to disable the global search gesture. Don't use this 2675 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2676 */ 2677 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2678 2679 /** 2680 * @hide 2681 * 2682 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2683 * out of the public fields to keep the undefined bits out of the developer's way. 2684 * 2685 * Flag to specify that the status bar is displayed in transient mode. 2686 */ 2687 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2688 2689 /** 2690 * @hide 2691 * 2692 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2693 * out of the public fields to keep the undefined bits out of the developer's way. 2694 * 2695 * Flag to specify that the navigation bar is displayed in transient mode. 2696 */ 2697 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2698 2699 /** 2700 * @hide 2701 * 2702 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2703 * out of the public fields to keep the undefined bits out of the developer's way. 2704 * 2705 * Flag to specify that the hidden status bar would like to be shown. 2706 */ 2707 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2708 2709 /** 2710 * @hide 2711 * 2712 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2713 * out of the public fields to keep the undefined bits out of the developer's way. 2714 * 2715 * Flag to specify that the hidden navigation bar would like to be shown. 2716 */ 2717 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2718 2719 /** 2720 * @hide 2721 * 2722 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2723 * out of the public fields to keep the undefined bits out of the developer's way. 2724 * 2725 * Flag to specify that the status bar is displayed in translucent mode. 2726 */ 2727 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2728 2729 /** 2730 * @hide 2731 * 2732 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2733 * out of the public fields to keep the undefined bits out of the developer's way. 2734 * 2735 * Flag to specify that the navigation bar is displayed in translucent mode. 2736 */ 2737 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2738 2739 /** 2740 * @hide 2741 * 2742 * Whether Recents is visible or not. 2743 */ 2744 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2745 2746 /** 2747 * @hide 2748 * 2749 * Makes system ui transparent. 2750 */ 2751 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2752 2753 /** 2754 * @hide 2755 */ 2756 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2757 2758 /** 2759 * These are the system UI flags that can be cleared by events outside 2760 * of an application. Currently this is just the ability to tap on the 2761 * screen while hiding the navigation bar to have it return. 2762 * @hide 2763 */ 2764 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2765 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2766 | SYSTEM_UI_FLAG_FULLSCREEN; 2767 2768 /** 2769 * Flags that can impact the layout in relation to system UI. 2770 */ 2771 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2772 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2773 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2774 2775 /** @hide */ 2776 @IntDef(flag = true, 2777 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2778 @Retention(RetentionPolicy.SOURCE) 2779 public @interface FindViewFlags {} 2780 2781 /** 2782 * Find views that render the specified text. 2783 * 2784 * @see #findViewsWithText(ArrayList, CharSequence, int) 2785 */ 2786 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2787 2788 /** 2789 * Find find views that contain the specified content description. 2790 * 2791 * @see #findViewsWithText(ArrayList, CharSequence, int) 2792 */ 2793 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2794 2795 /** 2796 * Find views that contain {@link AccessibilityNodeProvider}. Such 2797 * a View is a root of virtual view hierarchy and may contain the searched 2798 * text. If this flag is set Views with providers are automatically 2799 * added and it is a responsibility of the client to call the APIs of 2800 * the provider to determine whether the virtual tree rooted at this View 2801 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2802 * representing the virtual views with this text. 2803 * 2804 * @see #findViewsWithText(ArrayList, CharSequence, int) 2805 * 2806 * @hide 2807 */ 2808 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2809 2810 /** 2811 * The undefined cursor position. 2812 * 2813 * @hide 2814 */ 2815 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2816 2817 /** 2818 * Indicates that the screen has changed state and is now off. 2819 * 2820 * @see #onScreenStateChanged(int) 2821 */ 2822 public static final int SCREEN_STATE_OFF = 0x0; 2823 2824 /** 2825 * Indicates that the screen has changed state and is now on. 2826 * 2827 * @see #onScreenStateChanged(int) 2828 */ 2829 public static final int SCREEN_STATE_ON = 0x1; 2830 2831 /** 2832 * Indicates no axis of view scrolling. 2833 */ 2834 public static final int SCROLL_AXIS_NONE = 0; 2835 2836 /** 2837 * Indicates scrolling along the horizontal axis. 2838 */ 2839 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2840 2841 /** 2842 * Indicates scrolling along the vertical axis. 2843 */ 2844 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2845 2846 /** 2847 * Controls the over-scroll mode for this view. 2848 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2849 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2850 * and {@link #OVER_SCROLL_NEVER}. 2851 */ 2852 private int mOverScrollMode; 2853 2854 /** 2855 * The parent this view is attached to. 2856 * {@hide} 2857 * 2858 * @see #getParent() 2859 */ 2860 protected ViewParent mParent; 2861 2862 /** 2863 * {@hide} 2864 */ 2865 AttachInfo mAttachInfo; 2866 2867 /** 2868 * {@hide} 2869 */ 2870 @ViewDebug.ExportedProperty(flagMapping = { 2871 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2872 name = "FORCE_LAYOUT"), 2873 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2874 name = "LAYOUT_REQUIRED"), 2875 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2876 name = "DRAWING_CACHE_INVALID", outputIf = false), 2877 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2878 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2879 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2880 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2881 }, formatToHexString = true) 2882 int mPrivateFlags; 2883 int mPrivateFlags2; 2884 int mPrivateFlags3; 2885 2886 /** 2887 * This view's request for the visibility of the status bar. 2888 * @hide 2889 */ 2890 @ViewDebug.ExportedProperty(flagMapping = { 2891 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2892 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2893 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2894 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2895 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2896 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2897 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2898 equals = SYSTEM_UI_FLAG_VISIBLE, 2899 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2900 }, formatToHexString = true) 2901 int mSystemUiVisibility; 2902 2903 /** 2904 * Reference count for transient state. 2905 * @see #setHasTransientState(boolean) 2906 */ 2907 int mTransientStateCount = 0; 2908 2909 /** 2910 * Count of how many windows this view has been attached to. 2911 */ 2912 int mWindowAttachCount; 2913 2914 /** 2915 * The layout parameters associated with this view and used by the parent 2916 * {@link android.view.ViewGroup} to determine how this view should be 2917 * laid out. 2918 * {@hide} 2919 */ 2920 protected ViewGroup.LayoutParams mLayoutParams; 2921 2922 /** 2923 * The view flags hold various views states. 2924 * {@hide} 2925 */ 2926 @ViewDebug.ExportedProperty(formatToHexString = true) 2927 int mViewFlags; 2928 2929 static class TransformationInfo { 2930 /** 2931 * The transform matrix for the View. This transform is calculated internally 2932 * based on the translation, rotation, and scale properties. 2933 * 2934 * Do *not* use this variable directly; instead call getMatrix(), which will 2935 * load the value from the View's RenderNode. 2936 */ 2937 private final Matrix mMatrix = new Matrix(); 2938 2939 /** 2940 * The inverse transform matrix for the View. This transform is calculated 2941 * internally based on the translation, rotation, and scale properties. 2942 * 2943 * Do *not* use this variable directly; instead call getInverseMatrix(), 2944 * which will load the value from the View's RenderNode. 2945 */ 2946 private Matrix mInverseMatrix; 2947 2948 /** 2949 * The opacity of the View. This is a value from 0 to 1, where 0 means 2950 * completely transparent and 1 means completely opaque. 2951 */ 2952 @ViewDebug.ExportedProperty 2953 float mAlpha = 1f; 2954 2955 /** 2956 * The opacity of the view as manipulated by the Fade transition. This is a hidden 2957 * property only used by transitions, which is composited with the other alpha 2958 * values to calculate the final visual alpha value. 2959 */ 2960 float mTransitionAlpha = 1f; 2961 } 2962 2963 TransformationInfo mTransformationInfo; 2964 2965 /** 2966 * Current clip bounds. to which all drawing of this view are constrained. 2967 */ 2968 Rect mClipBounds = null; 2969 2970 private boolean mLastIsOpaque; 2971 2972 /** 2973 * The distance in pixels from the left edge of this view's parent 2974 * to the left edge of this view. 2975 * {@hide} 2976 */ 2977 @ViewDebug.ExportedProperty(category = "layout") 2978 protected int mLeft; 2979 /** 2980 * The distance in pixels from the left edge of this view's parent 2981 * to the right edge of this view. 2982 * {@hide} 2983 */ 2984 @ViewDebug.ExportedProperty(category = "layout") 2985 protected int mRight; 2986 /** 2987 * The distance in pixels from the top edge of this view's parent 2988 * to the top edge of this view. 2989 * {@hide} 2990 */ 2991 @ViewDebug.ExportedProperty(category = "layout") 2992 protected int mTop; 2993 /** 2994 * The distance in pixels from the top edge of this view's parent 2995 * to the bottom edge of this view. 2996 * {@hide} 2997 */ 2998 @ViewDebug.ExportedProperty(category = "layout") 2999 protected int mBottom; 3000 3001 /** 3002 * The offset, in pixels, by which the content of this view is scrolled 3003 * horizontally. 3004 * {@hide} 3005 */ 3006 @ViewDebug.ExportedProperty(category = "scrolling") 3007 protected int mScrollX; 3008 /** 3009 * The offset, in pixels, by which the content of this view is scrolled 3010 * vertically. 3011 * {@hide} 3012 */ 3013 @ViewDebug.ExportedProperty(category = "scrolling") 3014 protected int mScrollY; 3015 3016 /** 3017 * The left padding in pixels, that is the distance in pixels between the 3018 * left edge of this view and the left edge of its content. 3019 * {@hide} 3020 */ 3021 @ViewDebug.ExportedProperty(category = "padding") 3022 protected int mPaddingLeft = 0; 3023 /** 3024 * The right padding in pixels, that is the distance in pixels between the 3025 * right edge of this view and the right edge of its content. 3026 * {@hide} 3027 */ 3028 @ViewDebug.ExportedProperty(category = "padding") 3029 protected int mPaddingRight = 0; 3030 /** 3031 * The top padding in pixels, that is the distance in pixels between the 3032 * top edge of this view and the top edge of its content. 3033 * {@hide} 3034 */ 3035 @ViewDebug.ExportedProperty(category = "padding") 3036 protected int mPaddingTop; 3037 /** 3038 * The bottom padding in pixels, that is the distance in pixels between the 3039 * bottom edge of this view and the bottom edge of its content. 3040 * {@hide} 3041 */ 3042 @ViewDebug.ExportedProperty(category = "padding") 3043 protected int mPaddingBottom; 3044 3045 /** 3046 * The layout insets in pixels, that is the distance in pixels between the 3047 * visible edges of this view its bounds. 3048 */ 3049 private Insets mLayoutInsets; 3050 3051 /** 3052 * Briefly describes the view and is primarily used for accessibility support. 3053 */ 3054 private CharSequence mContentDescription; 3055 3056 /** 3057 * Specifies the id of a view for which this view serves as a label for 3058 * accessibility purposes. 3059 */ 3060 private int mLabelForId = View.NO_ID; 3061 3062 /** 3063 * Predicate for matching labeled view id with its label for 3064 * accessibility purposes. 3065 */ 3066 private MatchLabelForPredicate mMatchLabelForPredicate; 3067 3068 /** 3069 * Specifies a view before which this one is visited in accessibility traversal. 3070 */ 3071 private int mAccessibilityTraversalBeforeId = NO_ID; 3072 3073 /** 3074 * Specifies a view after which this one is visited in accessibility traversal. 3075 */ 3076 private int mAccessibilityTraversalAfterId = NO_ID; 3077 3078 /** 3079 * Predicate for matching a view by its id. 3080 */ 3081 private MatchIdPredicate mMatchIdPredicate; 3082 3083 /** 3084 * Cache the paddingRight set by the user to append to the scrollbar's size. 3085 * 3086 * @hide 3087 */ 3088 @ViewDebug.ExportedProperty(category = "padding") 3089 protected int mUserPaddingRight; 3090 3091 /** 3092 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3093 * 3094 * @hide 3095 */ 3096 @ViewDebug.ExportedProperty(category = "padding") 3097 protected int mUserPaddingBottom; 3098 3099 /** 3100 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3101 * 3102 * @hide 3103 */ 3104 @ViewDebug.ExportedProperty(category = "padding") 3105 protected int mUserPaddingLeft; 3106 3107 /** 3108 * Cache the paddingStart set by the user to append to the scrollbar's size. 3109 * 3110 */ 3111 @ViewDebug.ExportedProperty(category = "padding") 3112 int mUserPaddingStart; 3113 3114 /** 3115 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3116 * 3117 */ 3118 @ViewDebug.ExportedProperty(category = "padding") 3119 int mUserPaddingEnd; 3120 3121 /** 3122 * Cache initial left padding. 3123 * 3124 * @hide 3125 */ 3126 int mUserPaddingLeftInitial; 3127 3128 /** 3129 * Cache initial right padding. 3130 * 3131 * @hide 3132 */ 3133 int mUserPaddingRightInitial; 3134 3135 /** 3136 * Default undefined padding 3137 */ 3138 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3139 3140 /** 3141 * Cache if a left padding has been defined 3142 */ 3143 private boolean mLeftPaddingDefined = false; 3144 3145 /** 3146 * Cache if a right padding has been defined 3147 */ 3148 private boolean mRightPaddingDefined = false; 3149 3150 /** 3151 * @hide 3152 */ 3153 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3154 /** 3155 * @hide 3156 */ 3157 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3158 3159 private LongSparseLongArray mMeasureCache; 3160 3161 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3162 private Drawable mBackground; 3163 private TintInfo mBackgroundTint; 3164 3165 /** 3166 * RenderNode used for backgrounds. 3167 * <p> 3168 * When non-null and valid, this is expected to contain an up-to-date copy 3169 * of the background drawable. It is cleared on temporary detach, and reset 3170 * on cleanup. 3171 */ 3172 private RenderNode mBackgroundRenderNode; 3173 3174 private int mBackgroundResource; 3175 private boolean mBackgroundSizeChanged; 3176 3177 private String mTransitionName; 3178 3179 private static class TintInfo { 3180 ColorStateList mTintList; 3181 PorterDuff.Mode mTintMode; 3182 boolean mHasTintMode; 3183 boolean mHasTintList; 3184 } 3185 3186 static class ListenerInfo { 3187 /** 3188 * Listener used to dispatch focus change events. 3189 * This field should be made private, so it is hidden from the SDK. 3190 * {@hide} 3191 */ 3192 protected OnFocusChangeListener mOnFocusChangeListener; 3193 3194 /** 3195 * Listeners for layout change events. 3196 */ 3197 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3198 3199 protected OnScrollChangeListener mOnScrollChangeListener; 3200 3201 /** 3202 * Listeners for attach events. 3203 */ 3204 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3205 3206 /** 3207 * Listener used to dispatch click events. 3208 * This field should be made private, so it is hidden from the SDK. 3209 * {@hide} 3210 */ 3211 public OnClickListener mOnClickListener; 3212 3213 /** 3214 * Listener used to dispatch long click events. 3215 * This field should be made private, so it is hidden from the SDK. 3216 * {@hide} 3217 */ 3218 protected OnLongClickListener mOnLongClickListener; 3219 3220 /** 3221 * Listener used to build the context menu. 3222 * This field should be made private, so it is hidden from the SDK. 3223 * {@hide} 3224 */ 3225 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3226 3227 private OnKeyListener mOnKeyListener; 3228 3229 private OnTouchListener mOnTouchListener; 3230 3231 private OnHoverListener mOnHoverListener; 3232 3233 private OnGenericMotionListener mOnGenericMotionListener; 3234 3235 private OnDragListener mOnDragListener; 3236 3237 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3238 3239 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3240 } 3241 3242 ListenerInfo mListenerInfo; 3243 3244 /** 3245 * The application environment this view lives in. 3246 * This field should be made private, so it is hidden from the SDK. 3247 * {@hide} 3248 */ 3249 @ViewDebug.ExportedProperty(deepExport = true) 3250 protected Context mContext; 3251 3252 private final Resources mResources; 3253 3254 private ScrollabilityCache mScrollCache; 3255 3256 private int[] mDrawableState = null; 3257 3258 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3259 3260 /** 3261 * Animator that automatically runs based on state changes. 3262 */ 3263 private StateListAnimator mStateListAnimator; 3264 3265 /** 3266 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3267 * the user may specify which view to go to next. 3268 */ 3269 private int mNextFocusLeftId = View.NO_ID; 3270 3271 /** 3272 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3273 * the user may specify which view to go to next. 3274 */ 3275 private int mNextFocusRightId = View.NO_ID; 3276 3277 /** 3278 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3279 * the user may specify which view to go to next. 3280 */ 3281 private int mNextFocusUpId = View.NO_ID; 3282 3283 /** 3284 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3285 * the user may specify which view to go to next. 3286 */ 3287 private int mNextFocusDownId = View.NO_ID; 3288 3289 /** 3290 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3291 * the user may specify which view to go to next. 3292 */ 3293 int mNextFocusForwardId = View.NO_ID; 3294 3295 private CheckForLongPress mPendingCheckForLongPress; 3296 private CheckForTap mPendingCheckForTap = null; 3297 private PerformClick mPerformClick; 3298 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3299 3300 private UnsetPressedState mUnsetPressedState; 3301 3302 /** 3303 * Whether the long press's action has been invoked. The tap's action is invoked on the 3304 * up event while a long press is invoked as soon as the long press duration is reached, so 3305 * a long press could be performed before the tap is checked, in which case the tap's action 3306 * should not be invoked. 3307 */ 3308 private boolean mHasPerformedLongPress; 3309 3310 /** 3311 * The minimum height of the view. We'll try our best to have the height 3312 * of this view to at least this amount. 3313 */ 3314 @ViewDebug.ExportedProperty(category = "measurement") 3315 private int mMinHeight; 3316 3317 /** 3318 * The minimum width of the view. We'll try our best to have the width 3319 * of this view to at least this amount. 3320 */ 3321 @ViewDebug.ExportedProperty(category = "measurement") 3322 private int mMinWidth; 3323 3324 /** 3325 * The delegate to handle touch events that are physically in this view 3326 * but should be handled by another view. 3327 */ 3328 private TouchDelegate mTouchDelegate = null; 3329 3330 /** 3331 * Solid color to use as a background when creating the drawing cache. Enables 3332 * the cache to use 16 bit bitmaps instead of 32 bit. 3333 */ 3334 private int mDrawingCacheBackgroundColor = 0; 3335 3336 /** 3337 * Special tree observer used when mAttachInfo is null. 3338 */ 3339 private ViewTreeObserver mFloatingTreeObserver; 3340 3341 /** 3342 * Cache the touch slop from the context that created the view. 3343 */ 3344 private int mTouchSlop; 3345 3346 /** 3347 * Object that handles automatic animation of view properties. 3348 */ 3349 private ViewPropertyAnimator mAnimator = null; 3350 3351 /** 3352 * Flag indicating that a drag can cross window boundaries. When 3353 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3354 * with this flag set, all visible applications will be able to participate 3355 * in the drag operation and receive the dragged content. 3356 * 3357 * @hide 3358 */ 3359 public static final int DRAG_FLAG_GLOBAL = 1; 3360 3361 /** 3362 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3363 */ 3364 private float mVerticalScrollFactor; 3365 3366 /** 3367 * Position of the vertical scroll bar. 3368 */ 3369 private int mVerticalScrollbarPosition; 3370 3371 /** 3372 * Position the scroll bar at the default position as determined by the system. 3373 */ 3374 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3375 3376 /** 3377 * Position the scroll bar along the left edge. 3378 */ 3379 public static final int SCROLLBAR_POSITION_LEFT = 1; 3380 3381 /** 3382 * Position the scroll bar along the right edge. 3383 */ 3384 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3385 3386 /** 3387 * Indicates that the view does not have a layer. 3388 * 3389 * @see #getLayerType() 3390 * @see #setLayerType(int, android.graphics.Paint) 3391 * @see #LAYER_TYPE_SOFTWARE 3392 * @see #LAYER_TYPE_HARDWARE 3393 */ 3394 public static final int LAYER_TYPE_NONE = 0; 3395 3396 /** 3397 * <p>Indicates that the view has a software layer. A software layer is backed 3398 * by a bitmap and causes the view to be rendered using Android's software 3399 * rendering pipeline, even if hardware acceleration is enabled.</p> 3400 * 3401 * <p>Software layers have various usages:</p> 3402 * <p>When the application is not using hardware acceleration, a software layer 3403 * is useful to apply a specific color filter and/or blending mode and/or 3404 * translucency to a view and all its children.</p> 3405 * <p>When the application is using hardware acceleration, a software layer 3406 * is useful to render drawing primitives not supported by the hardware 3407 * accelerated pipeline. It can also be used to cache a complex view tree 3408 * into a texture and reduce the complexity of drawing operations. For instance, 3409 * when animating a complex view tree with a translation, a software layer can 3410 * be used to render the view tree only once.</p> 3411 * <p>Software layers should be avoided when the affected view tree updates 3412 * often. Every update will require to re-render the software layer, which can 3413 * potentially be slow (particularly when hardware acceleration is turned on 3414 * since the layer will have to be uploaded into a hardware texture after every 3415 * update.)</p> 3416 * 3417 * @see #getLayerType() 3418 * @see #setLayerType(int, android.graphics.Paint) 3419 * @see #LAYER_TYPE_NONE 3420 * @see #LAYER_TYPE_HARDWARE 3421 */ 3422 public static final int LAYER_TYPE_SOFTWARE = 1; 3423 3424 /** 3425 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3426 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3427 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3428 * rendering pipeline, but only if hardware acceleration is turned on for the 3429 * view hierarchy. When hardware acceleration is turned off, hardware layers 3430 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3431 * 3432 * <p>A hardware layer is useful to apply a specific color filter and/or 3433 * blending mode and/or translucency to a view and all its children.</p> 3434 * <p>A hardware layer can be used to cache a complex view tree into a 3435 * texture and reduce the complexity of drawing operations. For instance, 3436 * when animating a complex view tree with a translation, a hardware layer can 3437 * be used to render the view tree only once.</p> 3438 * <p>A hardware layer can also be used to increase the rendering quality when 3439 * rotation transformations are applied on a view. It can also be used to 3440 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3441 * 3442 * @see #getLayerType() 3443 * @see #setLayerType(int, android.graphics.Paint) 3444 * @see #LAYER_TYPE_NONE 3445 * @see #LAYER_TYPE_SOFTWARE 3446 */ 3447 public static final int LAYER_TYPE_HARDWARE = 2; 3448 3449 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3450 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3451 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3452 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3453 }) 3454 int mLayerType = LAYER_TYPE_NONE; 3455 Paint mLayerPaint; 3456 3457 /** 3458 * Set to true when drawing cache is enabled and cannot be created. 3459 * 3460 * @hide 3461 */ 3462 public boolean mCachingFailed; 3463 private Bitmap mDrawingCache; 3464 private Bitmap mUnscaledDrawingCache; 3465 3466 /** 3467 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3468 * <p> 3469 * When non-null and valid, this is expected to contain an up-to-date copy 3470 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3471 * cleanup. 3472 */ 3473 final RenderNode mRenderNode; 3474 3475 /** 3476 * Set to true when the view is sending hover accessibility events because it 3477 * is the innermost hovered view. 3478 */ 3479 private boolean mSendingHoverAccessibilityEvents; 3480 3481 /** 3482 * Delegate for injecting accessibility functionality. 3483 */ 3484 AccessibilityDelegate mAccessibilityDelegate; 3485 3486 /** 3487 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3488 * and add/remove objects to/from the overlay directly through the Overlay methods. 3489 */ 3490 ViewOverlay mOverlay; 3491 3492 /** 3493 * The currently active parent view for receiving delegated nested scrolling events. 3494 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3495 * by {@link #stopNestedScroll()} at the same point where we clear 3496 * requestDisallowInterceptTouchEvent. 3497 */ 3498 private ViewParent mNestedScrollingParent; 3499 3500 /** 3501 * Consistency verifier for debugging purposes. 3502 * @hide 3503 */ 3504 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3505 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3506 new InputEventConsistencyVerifier(this, 0) : null; 3507 3508 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3509 3510 private int[] mTempNestedScrollConsumed; 3511 3512 /** 3513 * An overlay is going to draw this View instead of being drawn as part of this 3514 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3515 * when this view is invalidated. 3516 */ 3517 GhostView mGhostView; 3518 3519 /** 3520 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3521 * @hide 3522 */ 3523 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3524 public String[] mAttributes; 3525 3526 /** 3527 * Maps a Resource id to its name. 3528 */ 3529 private static SparseArray<String> mAttributeMap; 3530 3531 /** 3532 * Simple constructor to use when creating a view from code. 3533 * 3534 * @param context The Context the view is running in, through which it can 3535 * access the current theme, resources, etc. 3536 */ 3537 public View(Context context) { 3538 mContext = context; 3539 mResources = context != null ? context.getResources() : null; 3540 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3541 // Set some flags defaults 3542 mPrivateFlags2 = 3543 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3544 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3545 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3546 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3547 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3548 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3549 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3550 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3551 mUserPaddingStart = UNDEFINED_PADDING; 3552 mUserPaddingEnd = UNDEFINED_PADDING; 3553 mRenderNode = RenderNode.create(getClass().getName(), this); 3554 3555 if (!sCompatibilityDone && context != null) { 3556 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3557 3558 // Older apps may need this compatibility hack for measurement. 3559 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3560 3561 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3562 // of whether a layout was requested on that View. 3563 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3564 3565 sCompatibilityDone = true; 3566 } 3567 } 3568 3569 /** 3570 * Constructor that is called when inflating a view from XML. This is called 3571 * when a view is being constructed from an XML file, supplying attributes 3572 * that were specified in the XML file. This version uses a default style of 3573 * 0, so the only attribute values applied are those in the Context's Theme 3574 * and the given AttributeSet. 3575 * 3576 * <p> 3577 * The method onFinishInflate() will be called after all children have been 3578 * added. 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 * @see #View(Context, AttributeSet, int) 3584 */ 3585 public View(Context context, AttributeSet attrs) { 3586 this(context, attrs, 0); 3587 } 3588 3589 /** 3590 * Perform inflation from XML and apply a class-specific base style from a 3591 * theme attribute. This constructor of View allows subclasses to use their 3592 * own base style when they are inflating. For example, a Button class's 3593 * constructor would call this version of the super class constructor and 3594 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3595 * allows the theme's button style to modify all of the base view attributes 3596 * (in particular its background) as well as the Button class's attributes. 3597 * 3598 * @param context The Context the view is running in, through which it can 3599 * access the current theme, resources, etc. 3600 * @param attrs The attributes of the XML tag that is inflating the view. 3601 * @param defStyleAttr An attribute in the current theme that contains a 3602 * reference to a style resource that supplies default values for 3603 * the view. Can be 0 to not look for defaults. 3604 * @see #View(Context, AttributeSet) 3605 */ 3606 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3607 this(context, attrs, defStyleAttr, 0); 3608 } 3609 3610 /** 3611 * Perform inflation from XML and apply a class-specific base style from a 3612 * theme attribute or style resource. This constructor of View allows 3613 * subclasses to use their own base style when they are inflating. 3614 * <p> 3615 * When determining the final value of a particular attribute, there are 3616 * four inputs that come into play: 3617 * <ol> 3618 * <li>Any attribute values in the given AttributeSet. 3619 * <li>The style resource specified in the AttributeSet (named "style"). 3620 * <li>The default style specified by <var>defStyleAttr</var>. 3621 * <li>The default style specified by <var>defStyleRes</var>. 3622 * <li>The base values in this theme. 3623 * </ol> 3624 * <p> 3625 * Each of these inputs is considered in-order, with the first listed taking 3626 * precedence over the following ones. In other words, if in the 3627 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3628 * , then the button's text will <em>always</em> be black, regardless of 3629 * what is specified in any of the styles. 3630 * 3631 * @param context The Context the view is running in, through which it can 3632 * access the current theme, resources, etc. 3633 * @param attrs The attributes of the XML tag that is inflating the view. 3634 * @param defStyleAttr An attribute in the current theme that contains a 3635 * reference to a style resource that supplies default values for 3636 * the view. Can be 0 to not look for defaults. 3637 * @param defStyleRes A resource identifier of a style resource that 3638 * supplies default values for the view, used only if 3639 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3640 * to not look for defaults. 3641 * @see #View(Context, AttributeSet, int) 3642 */ 3643 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3644 this(context); 3645 3646 final TypedArray a = context.obtainStyledAttributes( 3647 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3648 3649 if (mDebugViewAttributes) { 3650 saveAttributeData(attrs, a); 3651 } 3652 3653 Drawable background = null; 3654 3655 int leftPadding = -1; 3656 int topPadding = -1; 3657 int rightPadding = -1; 3658 int bottomPadding = -1; 3659 int startPadding = UNDEFINED_PADDING; 3660 int endPadding = UNDEFINED_PADDING; 3661 3662 int padding = -1; 3663 3664 int viewFlagValues = 0; 3665 int viewFlagMasks = 0; 3666 3667 boolean setScrollContainer = false; 3668 3669 int x = 0; 3670 int y = 0; 3671 3672 float tx = 0; 3673 float ty = 0; 3674 float tz = 0; 3675 float elevation = 0; 3676 float rotation = 0; 3677 float rotationX = 0; 3678 float rotationY = 0; 3679 float sx = 1f; 3680 float sy = 1f; 3681 boolean transformSet = false; 3682 3683 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3684 int overScrollMode = mOverScrollMode; 3685 boolean initializeScrollbars = false; 3686 3687 boolean startPaddingDefined = false; 3688 boolean endPaddingDefined = false; 3689 boolean leftPaddingDefined = false; 3690 boolean rightPaddingDefined = false; 3691 3692 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3693 3694 final int N = a.getIndexCount(); 3695 for (int i = 0; i < N; i++) { 3696 int attr = a.getIndex(i); 3697 switch (attr) { 3698 case com.android.internal.R.styleable.View_background: 3699 background = a.getDrawable(attr); 3700 break; 3701 case com.android.internal.R.styleable.View_padding: 3702 padding = a.getDimensionPixelSize(attr, -1); 3703 mUserPaddingLeftInitial = padding; 3704 mUserPaddingRightInitial = padding; 3705 leftPaddingDefined = true; 3706 rightPaddingDefined = true; 3707 break; 3708 case com.android.internal.R.styleable.View_paddingLeft: 3709 leftPadding = a.getDimensionPixelSize(attr, -1); 3710 mUserPaddingLeftInitial = leftPadding; 3711 leftPaddingDefined = true; 3712 break; 3713 case com.android.internal.R.styleable.View_paddingTop: 3714 topPadding = a.getDimensionPixelSize(attr, -1); 3715 break; 3716 case com.android.internal.R.styleable.View_paddingRight: 3717 rightPadding = a.getDimensionPixelSize(attr, -1); 3718 mUserPaddingRightInitial = rightPadding; 3719 rightPaddingDefined = true; 3720 break; 3721 case com.android.internal.R.styleable.View_paddingBottom: 3722 bottomPadding = a.getDimensionPixelSize(attr, -1); 3723 break; 3724 case com.android.internal.R.styleable.View_paddingStart: 3725 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3726 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3727 break; 3728 case com.android.internal.R.styleable.View_paddingEnd: 3729 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3730 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3731 break; 3732 case com.android.internal.R.styleable.View_scrollX: 3733 x = a.getDimensionPixelOffset(attr, 0); 3734 break; 3735 case com.android.internal.R.styleable.View_scrollY: 3736 y = a.getDimensionPixelOffset(attr, 0); 3737 break; 3738 case com.android.internal.R.styleable.View_alpha: 3739 setAlpha(a.getFloat(attr, 1f)); 3740 break; 3741 case com.android.internal.R.styleable.View_transformPivotX: 3742 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3743 break; 3744 case com.android.internal.R.styleable.View_transformPivotY: 3745 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3746 break; 3747 case com.android.internal.R.styleable.View_translationX: 3748 tx = a.getDimensionPixelOffset(attr, 0); 3749 transformSet = true; 3750 break; 3751 case com.android.internal.R.styleable.View_translationY: 3752 ty = a.getDimensionPixelOffset(attr, 0); 3753 transformSet = true; 3754 break; 3755 case com.android.internal.R.styleable.View_translationZ: 3756 tz = a.getDimensionPixelOffset(attr, 0); 3757 transformSet = true; 3758 break; 3759 case com.android.internal.R.styleable.View_elevation: 3760 elevation = a.getDimensionPixelOffset(attr, 0); 3761 transformSet = true; 3762 break; 3763 case com.android.internal.R.styleable.View_rotation: 3764 rotation = a.getFloat(attr, 0); 3765 transformSet = true; 3766 break; 3767 case com.android.internal.R.styleable.View_rotationX: 3768 rotationX = a.getFloat(attr, 0); 3769 transformSet = true; 3770 break; 3771 case com.android.internal.R.styleable.View_rotationY: 3772 rotationY = a.getFloat(attr, 0); 3773 transformSet = true; 3774 break; 3775 case com.android.internal.R.styleable.View_scaleX: 3776 sx = a.getFloat(attr, 1f); 3777 transformSet = true; 3778 break; 3779 case com.android.internal.R.styleable.View_scaleY: 3780 sy = a.getFloat(attr, 1f); 3781 transformSet = true; 3782 break; 3783 case com.android.internal.R.styleable.View_id: 3784 mID = a.getResourceId(attr, NO_ID); 3785 break; 3786 case com.android.internal.R.styleable.View_tag: 3787 mTag = a.getText(attr); 3788 break; 3789 case com.android.internal.R.styleable.View_fitsSystemWindows: 3790 if (a.getBoolean(attr, false)) { 3791 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3792 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3793 } 3794 break; 3795 case com.android.internal.R.styleable.View_focusable: 3796 if (a.getBoolean(attr, false)) { 3797 viewFlagValues |= FOCUSABLE; 3798 viewFlagMasks |= FOCUSABLE_MASK; 3799 } 3800 break; 3801 case com.android.internal.R.styleable.View_focusableInTouchMode: 3802 if (a.getBoolean(attr, false)) { 3803 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3804 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3805 } 3806 break; 3807 case com.android.internal.R.styleable.View_clickable: 3808 if (a.getBoolean(attr, false)) { 3809 viewFlagValues |= CLICKABLE; 3810 viewFlagMasks |= CLICKABLE; 3811 } 3812 break; 3813 case com.android.internal.R.styleable.View_longClickable: 3814 if (a.getBoolean(attr, false)) { 3815 viewFlagValues |= LONG_CLICKABLE; 3816 viewFlagMasks |= LONG_CLICKABLE; 3817 } 3818 break; 3819 case com.android.internal.R.styleable.View_saveEnabled: 3820 if (!a.getBoolean(attr, true)) { 3821 viewFlagValues |= SAVE_DISABLED; 3822 viewFlagMasks |= SAVE_DISABLED_MASK; 3823 } 3824 break; 3825 case com.android.internal.R.styleable.View_duplicateParentState: 3826 if (a.getBoolean(attr, false)) { 3827 viewFlagValues |= DUPLICATE_PARENT_STATE; 3828 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3829 } 3830 break; 3831 case com.android.internal.R.styleable.View_visibility: 3832 final int visibility = a.getInt(attr, 0); 3833 if (visibility != 0) { 3834 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3835 viewFlagMasks |= VISIBILITY_MASK; 3836 } 3837 break; 3838 case com.android.internal.R.styleable.View_layoutDirection: 3839 // Clear any layout direction flags (included resolved bits) already set 3840 mPrivateFlags2 &= 3841 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3842 // Set the layout direction flags depending on the value of the attribute 3843 final int layoutDirection = a.getInt(attr, -1); 3844 final int value = (layoutDirection != -1) ? 3845 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3846 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3847 break; 3848 case com.android.internal.R.styleable.View_drawingCacheQuality: 3849 final int cacheQuality = a.getInt(attr, 0); 3850 if (cacheQuality != 0) { 3851 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3852 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3853 } 3854 break; 3855 case com.android.internal.R.styleable.View_contentDescription: 3856 setContentDescription(a.getString(attr)); 3857 break; 3858 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 3859 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 3860 break; 3861 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 3862 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 3863 break; 3864 case com.android.internal.R.styleable.View_labelFor: 3865 setLabelFor(a.getResourceId(attr, NO_ID)); 3866 break; 3867 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3868 if (!a.getBoolean(attr, true)) { 3869 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3870 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3871 } 3872 break; 3873 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3874 if (!a.getBoolean(attr, true)) { 3875 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3876 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3877 } 3878 break; 3879 case R.styleable.View_scrollbars: 3880 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3881 if (scrollbars != SCROLLBARS_NONE) { 3882 viewFlagValues |= scrollbars; 3883 viewFlagMasks |= SCROLLBARS_MASK; 3884 initializeScrollbars = true; 3885 } 3886 break; 3887 //noinspection deprecation 3888 case R.styleable.View_fadingEdge: 3889 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3890 // Ignore the attribute starting with ICS 3891 break; 3892 } 3893 // With builds < ICS, fall through and apply fading edges 3894 case R.styleable.View_requiresFadingEdge: 3895 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3896 if (fadingEdge != FADING_EDGE_NONE) { 3897 viewFlagValues |= fadingEdge; 3898 viewFlagMasks |= FADING_EDGE_MASK; 3899 initializeFadingEdgeInternal(a); 3900 } 3901 break; 3902 case R.styleable.View_scrollbarStyle: 3903 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3904 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3905 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3906 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3907 } 3908 break; 3909 case R.styleable.View_isScrollContainer: 3910 setScrollContainer = true; 3911 if (a.getBoolean(attr, false)) { 3912 setScrollContainer(true); 3913 } 3914 break; 3915 case com.android.internal.R.styleable.View_keepScreenOn: 3916 if (a.getBoolean(attr, false)) { 3917 viewFlagValues |= KEEP_SCREEN_ON; 3918 viewFlagMasks |= KEEP_SCREEN_ON; 3919 } 3920 break; 3921 case R.styleable.View_filterTouchesWhenObscured: 3922 if (a.getBoolean(attr, false)) { 3923 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3924 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3925 } 3926 break; 3927 case R.styleable.View_nextFocusLeft: 3928 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3929 break; 3930 case R.styleable.View_nextFocusRight: 3931 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3932 break; 3933 case R.styleable.View_nextFocusUp: 3934 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3935 break; 3936 case R.styleable.View_nextFocusDown: 3937 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3938 break; 3939 case R.styleable.View_nextFocusForward: 3940 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3941 break; 3942 case R.styleable.View_minWidth: 3943 mMinWidth = a.getDimensionPixelSize(attr, 0); 3944 break; 3945 case R.styleable.View_minHeight: 3946 mMinHeight = a.getDimensionPixelSize(attr, 0); 3947 break; 3948 case R.styleable.View_onClick: 3949 if (context.isRestricted()) { 3950 throw new IllegalStateException("The android:onClick attribute cannot " 3951 + "be used within a restricted context"); 3952 } 3953 3954 final String handlerName = a.getString(attr); 3955 if (handlerName != null) { 3956 setOnClickListener(new OnClickListener() { 3957 private Method mHandler; 3958 3959 public void onClick(View v) { 3960 if (mHandler == null) { 3961 try { 3962 mHandler = getContext().getClass().getMethod(handlerName, 3963 View.class); 3964 } catch (NoSuchMethodException e) { 3965 int id = getId(); 3966 String idText = id == NO_ID ? "" : " with id '" 3967 + getContext().getResources().getResourceEntryName( 3968 id) + "'"; 3969 throw new IllegalStateException("Could not find a method " + 3970 handlerName + "(View) in the activity " 3971 + getContext().getClass() + " for onClick handler" 3972 + " on view " + View.this.getClass() + idText, e); 3973 } 3974 } 3975 3976 try { 3977 mHandler.invoke(getContext(), View.this); 3978 } catch (IllegalAccessException e) { 3979 throw new IllegalStateException("Could not execute non " 3980 + "public method of the activity", e); 3981 } catch (InvocationTargetException e) { 3982 throw new IllegalStateException("Could not execute " 3983 + "method of the activity", e); 3984 } 3985 } 3986 }); 3987 } 3988 break; 3989 case R.styleable.View_overScrollMode: 3990 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 3991 break; 3992 case R.styleable.View_verticalScrollbarPosition: 3993 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 3994 break; 3995 case R.styleable.View_layerType: 3996 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 3997 break; 3998 case R.styleable.View_textDirection: 3999 // Clear any text direction flag already set 4000 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4001 // Set the text direction flags depending on the value of the attribute 4002 final int textDirection = a.getInt(attr, -1); 4003 if (textDirection != -1) { 4004 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4005 } 4006 break; 4007 case R.styleable.View_textAlignment: 4008 // Clear any text alignment flag already set 4009 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4010 // Set the text alignment flag depending on the value of the attribute 4011 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4012 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4013 break; 4014 case R.styleable.View_importantForAccessibility: 4015 setImportantForAccessibility(a.getInt(attr, 4016 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4017 break; 4018 case R.styleable.View_accessibilityLiveRegion: 4019 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4020 break; 4021 case R.styleable.View_transitionName: 4022 setTransitionName(a.getString(attr)); 4023 break; 4024 case R.styleable.View_nestedScrollingEnabled: 4025 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4026 break; 4027 case R.styleable.View_stateListAnimator: 4028 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4029 a.getResourceId(attr, 0))); 4030 break; 4031 case R.styleable.View_backgroundTint: 4032 // This will get applied later during setBackground(). 4033 if (mBackgroundTint == null) { 4034 mBackgroundTint = new TintInfo(); 4035 } 4036 mBackgroundTint.mTintList = a.getColorStateList( 4037 R.styleable.View_backgroundTint); 4038 mBackgroundTint.mHasTintList = true; 4039 break; 4040 case R.styleable.View_backgroundTintMode: 4041 // This will get applied later during setBackground(). 4042 if (mBackgroundTint == null) { 4043 mBackgroundTint = new TintInfo(); 4044 } 4045 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4046 R.styleable.View_backgroundTintMode, -1), null); 4047 mBackgroundTint.mHasTintMode = true; 4048 break; 4049 case R.styleable.View_outlineProvider: 4050 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4051 PROVIDER_BACKGROUND)); 4052 break; 4053 } 4054 } 4055 4056 setOverScrollMode(overScrollMode); 4057 4058 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4059 // the resolved layout direction). Those cached values will be used later during padding 4060 // resolution. 4061 mUserPaddingStart = startPadding; 4062 mUserPaddingEnd = endPadding; 4063 4064 if (background != null) { 4065 setBackground(background); 4066 } 4067 4068 // setBackground above will record that padding is currently provided by the background. 4069 // If we have padding specified via xml, record that here instead and use it. 4070 mLeftPaddingDefined = leftPaddingDefined; 4071 mRightPaddingDefined = rightPaddingDefined; 4072 4073 if (padding >= 0) { 4074 leftPadding = padding; 4075 topPadding = padding; 4076 rightPadding = padding; 4077 bottomPadding = padding; 4078 mUserPaddingLeftInitial = padding; 4079 mUserPaddingRightInitial = padding; 4080 } 4081 4082 if (isRtlCompatibilityMode()) { 4083 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4084 // left / right padding are used if defined (meaning here nothing to do). If they are not 4085 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4086 // start / end and resolve them as left / right (layout direction is not taken into account). 4087 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4088 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4089 // defined. 4090 if (!mLeftPaddingDefined && startPaddingDefined) { 4091 leftPadding = startPadding; 4092 } 4093 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4094 if (!mRightPaddingDefined && endPaddingDefined) { 4095 rightPadding = endPadding; 4096 } 4097 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4098 } else { 4099 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4100 // values defined. Otherwise, left /right values are used. 4101 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4102 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4103 // defined. 4104 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4105 4106 if (mLeftPaddingDefined && !hasRelativePadding) { 4107 mUserPaddingLeftInitial = leftPadding; 4108 } 4109 if (mRightPaddingDefined && !hasRelativePadding) { 4110 mUserPaddingRightInitial = rightPadding; 4111 } 4112 } 4113 4114 internalSetPadding( 4115 mUserPaddingLeftInitial, 4116 topPadding >= 0 ? topPadding : mPaddingTop, 4117 mUserPaddingRightInitial, 4118 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4119 4120 if (viewFlagMasks != 0) { 4121 setFlags(viewFlagValues, viewFlagMasks); 4122 } 4123 4124 if (initializeScrollbars) { 4125 initializeScrollbarsInternal(a); 4126 } 4127 4128 a.recycle(); 4129 4130 // Needs to be called after mViewFlags is set 4131 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4132 recomputePadding(); 4133 } 4134 4135 if (x != 0 || y != 0) { 4136 scrollTo(x, y); 4137 } 4138 4139 if (transformSet) { 4140 setTranslationX(tx); 4141 setTranslationY(ty); 4142 setTranslationZ(tz); 4143 setElevation(elevation); 4144 setRotation(rotation); 4145 setRotationX(rotationX); 4146 setRotationY(rotationY); 4147 setScaleX(sx); 4148 setScaleY(sy); 4149 } 4150 4151 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4152 setScrollContainer(true); 4153 } 4154 4155 computeOpaqueFlags(); 4156 } 4157 4158 /** 4159 * Non-public constructor for use in testing 4160 */ 4161 View() { 4162 mResources = null; 4163 mRenderNode = RenderNode.create(getClass().getName(), this); 4164 } 4165 4166 private static SparseArray<String> getAttributeMap() { 4167 if (mAttributeMap == null) { 4168 mAttributeMap = new SparseArray<String>(); 4169 } 4170 return mAttributeMap; 4171 } 4172 4173 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4174 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4175 mAttributes = new String[length]; 4176 4177 int i = 0; 4178 if (attrs != null) { 4179 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4180 mAttributes[i] = attrs.getAttributeName(i); 4181 mAttributes[i + 1] = attrs.getAttributeValue(i); 4182 } 4183 4184 } 4185 4186 SparseArray<String> attributeMap = getAttributeMap(); 4187 for (int j = 0; j < a.length(); ++j) { 4188 if (a.hasValue(j)) { 4189 try { 4190 int resourceId = a.getResourceId(j, 0); 4191 if (resourceId == 0) { 4192 continue; 4193 } 4194 4195 String resourceName = attributeMap.get(resourceId); 4196 if (resourceName == null) { 4197 resourceName = a.getResources().getResourceName(resourceId); 4198 attributeMap.put(resourceId, resourceName); 4199 } 4200 4201 mAttributes[i] = resourceName; 4202 mAttributes[i + 1] = a.getText(j).toString(); 4203 i += 2; 4204 } catch (Resources.NotFoundException e) { 4205 // if we can't get the resource name, we just ignore it 4206 } 4207 } 4208 } 4209 } 4210 4211 public String toString() { 4212 StringBuilder out = new StringBuilder(128); 4213 out.append(getClass().getName()); 4214 out.append('{'); 4215 out.append(Integer.toHexString(System.identityHashCode(this))); 4216 out.append(' '); 4217 switch (mViewFlags&VISIBILITY_MASK) { 4218 case VISIBLE: out.append('V'); break; 4219 case INVISIBLE: out.append('I'); break; 4220 case GONE: out.append('G'); break; 4221 default: out.append('.'); break; 4222 } 4223 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4224 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4225 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4226 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4227 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4228 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4229 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4230 out.append(' '); 4231 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4232 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4233 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4234 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4235 out.append('p'); 4236 } else { 4237 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4238 } 4239 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4240 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4241 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4242 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4243 out.append(' '); 4244 out.append(mLeft); 4245 out.append(','); 4246 out.append(mTop); 4247 out.append('-'); 4248 out.append(mRight); 4249 out.append(','); 4250 out.append(mBottom); 4251 final int id = getId(); 4252 if (id != NO_ID) { 4253 out.append(" #"); 4254 out.append(Integer.toHexString(id)); 4255 final Resources r = mResources; 4256 if (Resources.resourceHasPackage(id) && r != null) { 4257 try { 4258 String pkgname; 4259 switch (id&0xff000000) { 4260 case 0x7f000000: 4261 pkgname="app"; 4262 break; 4263 case 0x01000000: 4264 pkgname="android"; 4265 break; 4266 default: 4267 pkgname = r.getResourcePackageName(id); 4268 break; 4269 } 4270 String typename = r.getResourceTypeName(id); 4271 String entryname = r.getResourceEntryName(id); 4272 out.append(" "); 4273 out.append(pkgname); 4274 out.append(":"); 4275 out.append(typename); 4276 out.append("/"); 4277 out.append(entryname); 4278 } catch (Resources.NotFoundException e) { 4279 } 4280 } 4281 } 4282 out.append("}"); 4283 return out.toString(); 4284 } 4285 4286 /** 4287 * <p> 4288 * Initializes the fading edges from a given set of styled attributes. This 4289 * method should be called by subclasses that need fading edges and when an 4290 * instance of these subclasses is created programmatically rather than 4291 * being inflated from XML. This method is automatically called when the XML 4292 * is inflated. 4293 * </p> 4294 * 4295 * @param a the styled attributes set to initialize the fading edges from 4296 * 4297 * @removed 4298 */ 4299 protected void initializeFadingEdge(TypedArray a) { 4300 // This method probably shouldn't have been included in the SDK to begin with. 4301 // It relies on 'a' having been initialized using an attribute filter array that is 4302 // not publicly available to the SDK. The old method has been renamed 4303 // to initializeFadingEdgeInternal and hidden for framework use only; 4304 // this one initializes using defaults to make it safe to call for apps. 4305 4306 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4307 4308 initializeFadingEdgeInternal(arr); 4309 4310 arr.recycle(); 4311 } 4312 4313 /** 4314 * <p> 4315 * Initializes the fading edges from a given set of styled attributes. This 4316 * method should be called by subclasses that need fading edges and when an 4317 * instance of these subclasses is created programmatically rather than 4318 * being inflated from XML. This method is automatically called when the XML 4319 * is inflated. 4320 * </p> 4321 * 4322 * @param a the styled attributes set to initialize the fading edges from 4323 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4324 */ 4325 protected void initializeFadingEdgeInternal(TypedArray a) { 4326 initScrollCache(); 4327 4328 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4329 R.styleable.View_fadingEdgeLength, 4330 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4331 } 4332 4333 /** 4334 * Returns the size of the vertical faded edges used to indicate that more 4335 * content in this view is visible. 4336 * 4337 * @return The size in pixels of the vertical faded edge or 0 if vertical 4338 * faded edges are not enabled for this view. 4339 * @attr ref android.R.styleable#View_fadingEdgeLength 4340 */ 4341 public int getVerticalFadingEdgeLength() { 4342 if (isVerticalFadingEdgeEnabled()) { 4343 ScrollabilityCache cache = mScrollCache; 4344 if (cache != null) { 4345 return cache.fadingEdgeLength; 4346 } 4347 } 4348 return 0; 4349 } 4350 4351 /** 4352 * Set the size of the faded edge used to indicate that more content in this 4353 * view is available. Will not change whether the fading edge is enabled; use 4354 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4355 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4356 * for the vertical or horizontal fading edges. 4357 * 4358 * @param length The size in pixels of the faded edge used to indicate that more 4359 * content in this view is visible. 4360 */ 4361 public void setFadingEdgeLength(int length) { 4362 initScrollCache(); 4363 mScrollCache.fadingEdgeLength = length; 4364 } 4365 4366 /** 4367 * Returns the size of the horizontal faded edges used to indicate that more 4368 * content in this view is visible. 4369 * 4370 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4371 * faded edges are not enabled for this view. 4372 * @attr ref android.R.styleable#View_fadingEdgeLength 4373 */ 4374 public int getHorizontalFadingEdgeLength() { 4375 if (isHorizontalFadingEdgeEnabled()) { 4376 ScrollabilityCache cache = mScrollCache; 4377 if (cache != null) { 4378 return cache.fadingEdgeLength; 4379 } 4380 } 4381 return 0; 4382 } 4383 4384 /** 4385 * Returns the width of the vertical scrollbar. 4386 * 4387 * @return The width in pixels of the vertical scrollbar or 0 if there 4388 * is no vertical scrollbar. 4389 */ 4390 public int getVerticalScrollbarWidth() { 4391 ScrollabilityCache cache = mScrollCache; 4392 if (cache != null) { 4393 ScrollBarDrawable scrollBar = cache.scrollBar; 4394 if (scrollBar != null) { 4395 int size = scrollBar.getSize(true); 4396 if (size <= 0) { 4397 size = cache.scrollBarSize; 4398 } 4399 return size; 4400 } 4401 return 0; 4402 } 4403 return 0; 4404 } 4405 4406 /** 4407 * Returns the height of the horizontal scrollbar. 4408 * 4409 * @return The height in pixels of the horizontal scrollbar or 0 if 4410 * there is no horizontal scrollbar. 4411 */ 4412 protected int getHorizontalScrollbarHeight() { 4413 ScrollabilityCache cache = mScrollCache; 4414 if (cache != null) { 4415 ScrollBarDrawable scrollBar = cache.scrollBar; 4416 if (scrollBar != null) { 4417 int size = scrollBar.getSize(false); 4418 if (size <= 0) { 4419 size = cache.scrollBarSize; 4420 } 4421 return size; 4422 } 4423 return 0; 4424 } 4425 return 0; 4426 } 4427 4428 /** 4429 * <p> 4430 * Initializes the scrollbars from a given set of styled attributes. This 4431 * method should be called by subclasses that need scrollbars and when an 4432 * instance of these subclasses is created programmatically rather than 4433 * being inflated from XML. This method is automatically called when the XML 4434 * is inflated. 4435 * </p> 4436 * 4437 * @param a the styled attributes set to initialize the scrollbars from 4438 * 4439 * @removed 4440 */ 4441 protected void initializeScrollbars(TypedArray a) { 4442 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4443 // using the View filter array which is not available to the SDK. As such, internal 4444 // framework usage now uses initializeScrollbarsInternal and we grab a default 4445 // TypedArray with the right filter instead here. 4446 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4447 4448 initializeScrollbarsInternal(arr); 4449 4450 // We ignored the method parameter. Recycle the one we actually did use. 4451 arr.recycle(); 4452 } 4453 4454 /** 4455 * <p> 4456 * Initializes the scrollbars from a given set of styled attributes. This 4457 * method should be called by subclasses that need scrollbars and when an 4458 * instance of these subclasses is created programmatically rather than 4459 * being inflated from XML. This method is automatically called when the XML 4460 * is inflated. 4461 * </p> 4462 * 4463 * @param a the styled attributes set to initialize the scrollbars from 4464 * @hide 4465 */ 4466 protected void initializeScrollbarsInternal(TypedArray a) { 4467 initScrollCache(); 4468 4469 final ScrollabilityCache scrollabilityCache = mScrollCache; 4470 4471 if (scrollabilityCache.scrollBar == null) { 4472 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4473 scrollabilityCache.scrollBar.setCallback(this); 4474 scrollabilityCache.scrollBar.setState(getDrawableState()); 4475 } 4476 4477 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4478 4479 if (!fadeScrollbars) { 4480 scrollabilityCache.state = ScrollabilityCache.ON; 4481 } 4482 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4483 4484 4485 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4486 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4487 .getScrollBarFadeDuration()); 4488 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4489 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4490 ViewConfiguration.getScrollDefaultDelay()); 4491 4492 4493 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4494 com.android.internal.R.styleable.View_scrollbarSize, 4495 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4496 4497 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4498 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4499 4500 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4501 if (thumb != null) { 4502 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4503 } 4504 4505 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4506 false); 4507 if (alwaysDraw) { 4508 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4509 } 4510 4511 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4512 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4513 4514 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4515 if (thumb != null) { 4516 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4517 } 4518 4519 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4520 false); 4521 if (alwaysDraw) { 4522 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4523 } 4524 4525 // Apply layout direction to the new Drawables if needed 4526 final int layoutDirection = getLayoutDirection(); 4527 if (track != null) { 4528 track.setLayoutDirection(layoutDirection); 4529 } 4530 if (thumb != null) { 4531 thumb.setLayoutDirection(layoutDirection); 4532 } 4533 4534 // Re-apply user/background padding so that scrollbar(s) get added 4535 resolvePadding(); 4536 } 4537 4538 /** 4539 * <p> 4540 * Initalizes the scrollability cache if necessary. 4541 * </p> 4542 */ 4543 private void initScrollCache() { 4544 if (mScrollCache == null) { 4545 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4546 } 4547 } 4548 4549 private ScrollabilityCache getScrollCache() { 4550 initScrollCache(); 4551 return mScrollCache; 4552 } 4553 4554 /** 4555 * Set the position of the vertical scroll bar. Should be one of 4556 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4557 * {@link #SCROLLBAR_POSITION_RIGHT}. 4558 * 4559 * @param position Where the vertical scroll bar should be positioned. 4560 */ 4561 public void setVerticalScrollbarPosition(int position) { 4562 if (mVerticalScrollbarPosition != position) { 4563 mVerticalScrollbarPosition = position; 4564 computeOpaqueFlags(); 4565 resolvePadding(); 4566 } 4567 } 4568 4569 /** 4570 * @return The position where the vertical scroll bar will show, if applicable. 4571 * @see #setVerticalScrollbarPosition(int) 4572 */ 4573 public int getVerticalScrollbarPosition() { 4574 return mVerticalScrollbarPosition; 4575 } 4576 4577 ListenerInfo getListenerInfo() { 4578 if (mListenerInfo != null) { 4579 return mListenerInfo; 4580 } 4581 mListenerInfo = new ListenerInfo(); 4582 return mListenerInfo; 4583 } 4584 4585 /** 4586 * Register a callback to be invoked when the scroll X or Y positions of 4587 * this view change. 4588 * <p> 4589 * <b>Note:</b> Some views handle scrolling independently from View and may 4590 * have their own separate listeners for scroll-type events. For example, 4591 * {@link android.widget.ListView ListView} allows clients to register an 4592 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 4593 * to listen for changes in list scroll position. 4594 * 4595 * @param l The listener to notify when the scroll X or Y position changes. 4596 * @see android.view.View#getScrollX() 4597 * @see android.view.View#getScrollY() 4598 */ 4599 public void setOnScrollChangeListener(OnScrollChangeListener l) { 4600 getListenerInfo().mOnScrollChangeListener = l; 4601 } 4602 4603 /** 4604 * Register a callback to be invoked when focus of this view changed. 4605 * 4606 * @param l The callback that will run. 4607 */ 4608 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4609 getListenerInfo().mOnFocusChangeListener = l; 4610 } 4611 4612 /** 4613 * Add a listener that will be called when the bounds of the view change due to 4614 * layout processing. 4615 * 4616 * @param listener The listener that will be called when layout bounds change. 4617 */ 4618 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4619 ListenerInfo li = getListenerInfo(); 4620 if (li.mOnLayoutChangeListeners == null) { 4621 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4622 } 4623 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4624 li.mOnLayoutChangeListeners.add(listener); 4625 } 4626 } 4627 4628 /** 4629 * Remove a listener for layout changes. 4630 * 4631 * @param listener The listener for layout bounds change. 4632 */ 4633 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4634 ListenerInfo li = mListenerInfo; 4635 if (li == null || li.mOnLayoutChangeListeners == null) { 4636 return; 4637 } 4638 li.mOnLayoutChangeListeners.remove(listener); 4639 } 4640 4641 /** 4642 * Add a listener for attach state changes. 4643 * 4644 * This listener will be called whenever this view is attached or detached 4645 * from a window. Remove the listener using 4646 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4647 * 4648 * @param listener Listener to attach 4649 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4650 */ 4651 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4652 ListenerInfo li = getListenerInfo(); 4653 if (li.mOnAttachStateChangeListeners == null) { 4654 li.mOnAttachStateChangeListeners 4655 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4656 } 4657 li.mOnAttachStateChangeListeners.add(listener); 4658 } 4659 4660 /** 4661 * Remove a listener for attach state changes. The listener will receive no further 4662 * notification of window attach/detach events. 4663 * 4664 * @param listener Listener to remove 4665 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4666 */ 4667 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4668 ListenerInfo li = mListenerInfo; 4669 if (li == null || li.mOnAttachStateChangeListeners == null) { 4670 return; 4671 } 4672 li.mOnAttachStateChangeListeners.remove(listener); 4673 } 4674 4675 /** 4676 * Returns the focus-change callback registered for this view. 4677 * 4678 * @return The callback, or null if one is not registered. 4679 */ 4680 public OnFocusChangeListener getOnFocusChangeListener() { 4681 ListenerInfo li = mListenerInfo; 4682 return li != null ? li.mOnFocusChangeListener : null; 4683 } 4684 4685 /** 4686 * Register a callback to be invoked when this view is clicked. If this view is not 4687 * clickable, it becomes clickable. 4688 * 4689 * @param l The callback that will run 4690 * 4691 * @see #setClickable(boolean) 4692 */ 4693 public void setOnClickListener(@Nullable OnClickListener l) { 4694 if (!isClickable()) { 4695 setClickable(true); 4696 } 4697 getListenerInfo().mOnClickListener = l; 4698 } 4699 4700 /** 4701 * Return whether this view has an attached OnClickListener. Returns 4702 * true if there is a listener, false if there is none. 4703 */ 4704 public boolean hasOnClickListeners() { 4705 ListenerInfo li = mListenerInfo; 4706 return (li != null && li.mOnClickListener != null); 4707 } 4708 4709 /** 4710 * Register a callback to be invoked when this view is clicked and held. If this view is not 4711 * long clickable, it becomes long clickable. 4712 * 4713 * @param l The callback that will run 4714 * 4715 * @see #setLongClickable(boolean) 4716 */ 4717 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 4718 if (!isLongClickable()) { 4719 setLongClickable(true); 4720 } 4721 getListenerInfo().mOnLongClickListener = l; 4722 } 4723 4724 /** 4725 * Register a callback to be invoked when the context menu for this view is 4726 * being built. If this view is not long clickable, it becomes long clickable. 4727 * 4728 * @param l The callback that will run 4729 * 4730 */ 4731 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4732 if (!isLongClickable()) { 4733 setLongClickable(true); 4734 } 4735 getListenerInfo().mOnCreateContextMenuListener = l; 4736 } 4737 4738 /** 4739 * Call this view's OnClickListener, if it is defined. Performs all normal 4740 * actions associated with clicking: reporting accessibility event, playing 4741 * a sound, etc. 4742 * 4743 * @return True there was an assigned OnClickListener that was called, false 4744 * otherwise is returned. 4745 */ 4746 public boolean performClick() { 4747 final boolean result; 4748 final ListenerInfo li = mListenerInfo; 4749 if (li != null && li.mOnClickListener != null) { 4750 playSoundEffect(SoundEffectConstants.CLICK); 4751 li.mOnClickListener.onClick(this); 4752 result = true; 4753 } else { 4754 result = false; 4755 } 4756 4757 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4758 return result; 4759 } 4760 4761 /** 4762 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4763 * this only calls the listener, and does not do any associated clicking 4764 * actions like reporting an accessibility event. 4765 * 4766 * @return True there was an assigned OnClickListener that was called, false 4767 * otherwise is returned. 4768 */ 4769 public boolean callOnClick() { 4770 ListenerInfo li = mListenerInfo; 4771 if (li != null && li.mOnClickListener != null) { 4772 li.mOnClickListener.onClick(this); 4773 return true; 4774 } 4775 return false; 4776 } 4777 4778 /** 4779 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4780 * OnLongClickListener did not consume the event. 4781 * 4782 * @return True if one of the above receivers consumed the event, false otherwise. 4783 */ 4784 public boolean performLongClick() { 4785 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4786 4787 boolean handled = false; 4788 ListenerInfo li = mListenerInfo; 4789 if (li != null && li.mOnLongClickListener != null) { 4790 handled = li.mOnLongClickListener.onLongClick(View.this); 4791 } 4792 if (!handled) { 4793 handled = showContextMenu(); 4794 } 4795 if (handled) { 4796 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4797 } 4798 return handled; 4799 } 4800 4801 /** 4802 * Performs button-related actions during a touch down event. 4803 * 4804 * @param event The event. 4805 * @return True if the down was consumed. 4806 * 4807 * @hide 4808 */ 4809 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4810 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4811 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4812 return true; 4813 } 4814 } 4815 return false; 4816 } 4817 4818 /** 4819 * Bring up the context menu for this view. 4820 * 4821 * @return Whether a context menu was displayed. 4822 */ 4823 public boolean showContextMenu() { 4824 return getParent().showContextMenuForChild(this); 4825 } 4826 4827 /** 4828 * Bring up the context menu for this view, referring to the item under the specified point. 4829 * 4830 * @param x The referenced x coordinate. 4831 * @param y The referenced y coordinate. 4832 * @param metaState The keyboard modifiers that were pressed. 4833 * @return Whether a context menu was displayed. 4834 * 4835 * @hide 4836 */ 4837 public boolean showContextMenu(float x, float y, int metaState) { 4838 return showContextMenu(); 4839 } 4840 4841 /** 4842 * Start an action mode. 4843 * 4844 * @param callback Callback that will control the lifecycle of the action mode 4845 * @return The new action mode if it is started, null otherwise 4846 * 4847 * @see ActionMode 4848 */ 4849 public ActionMode startActionMode(ActionMode.Callback callback) { 4850 ViewParent parent = getParent(); 4851 if (parent == null) return null; 4852 return parent.startActionModeForChild(this, callback); 4853 } 4854 4855 /** 4856 * Register a callback to be invoked when a hardware key is pressed in this view. 4857 * Key presses in software input methods will generally not trigger the methods of 4858 * this listener. 4859 * @param l the key listener to attach to this view 4860 */ 4861 public void setOnKeyListener(OnKeyListener l) { 4862 getListenerInfo().mOnKeyListener = l; 4863 } 4864 4865 /** 4866 * Register a callback to be invoked when a touch event is sent to this view. 4867 * @param l the touch listener to attach to this view 4868 */ 4869 public void setOnTouchListener(OnTouchListener l) { 4870 getListenerInfo().mOnTouchListener = l; 4871 } 4872 4873 /** 4874 * Register a callback to be invoked when a generic motion event is sent to this view. 4875 * @param l the generic motion listener to attach to this view 4876 */ 4877 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4878 getListenerInfo().mOnGenericMotionListener = l; 4879 } 4880 4881 /** 4882 * Register a callback to be invoked when a hover event is sent to this view. 4883 * @param l the hover listener to attach to this view 4884 */ 4885 public void setOnHoverListener(OnHoverListener l) { 4886 getListenerInfo().mOnHoverListener = l; 4887 } 4888 4889 /** 4890 * Register a drag event listener callback object for this View. The parameter is 4891 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4892 * View, the system calls the 4893 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4894 * @param l An implementation of {@link android.view.View.OnDragListener}. 4895 */ 4896 public void setOnDragListener(OnDragListener l) { 4897 getListenerInfo().mOnDragListener = l; 4898 } 4899 4900 /** 4901 * Give this view focus. This will cause 4902 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4903 * 4904 * Note: this does not check whether this {@link View} should get focus, it just 4905 * gives it focus no matter what. It should only be called internally by framework 4906 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4907 * 4908 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4909 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4910 * focus moved when requestFocus() is called. It may not always 4911 * apply, in which case use the default View.FOCUS_DOWN. 4912 * @param previouslyFocusedRect The rectangle of the view that had focus 4913 * prior in this View's coordinate system. 4914 */ 4915 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4916 if (DBG) { 4917 System.out.println(this + " requestFocus()"); 4918 } 4919 4920 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4921 mPrivateFlags |= PFLAG_FOCUSED; 4922 4923 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4924 4925 if (mParent != null) { 4926 mParent.requestChildFocus(this, this); 4927 } 4928 4929 if (mAttachInfo != null) { 4930 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4931 } 4932 4933 onFocusChanged(true, direction, previouslyFocusedRect); 4934 refreshDrawableState(); 4935 } 4936 } 4937 4938 /** 4939 * Populates <code>outRect</code> with the hotspot bounds. By default, 4940 * the hotspot bounds are identical to the screen bounds. 4941 * 4942 * @param outRect rect to populate with hotspot bounds 4943 * @hide Only for internal use by views and widgets. 4944 */ 4945 public void getHotspotBounds(Rect outRect) { 4946 final Drawable background = getBackground(); 4947 if (background != null) { 4948 background.getHotspotBounds(outRect); 4949 } else { 4950 getBoundsOnScreen(outRect); 4951 } 4952 } 4953 4954 /** 4955 * Request that a rectangle of this view be visible on the screen, 4956 * scrolling if necessary just enough. 4957 * 4958 * <p>A View should call this if it maintains some notion of which part 4959 * of its content is interesting. For example, a text editing view 4960 * should call this when its cursor moves. 4961 * 4962 * @param rectangle The rectangle. 4963 * @return Whether any parent scrolled. 4964 */ 4965 public boolean requestRectangleOnScreen(Rect rectangle) { 4966 return requestRectangleOnScreen(rectangle, false); 4967 } 4968 4969 /** 4970 * Request that a rectangle of this view be visible on the screen, 4971 * scrolling if necessary just enough. 4972 * 4973 * <p>A View should call this if it maintains some notion of which part 4974 * of its content is interesting. For example, a text editing view 4975 * should call this when its cursor moves. 4976 * 4977 * <p>When <code>immediate</code> is set to true, scrolling will not be 4978 * animated. 4979 * 4980 * @param rectangle The rectangle. 4981 * @param immediate True to forbid animated scrolling, false otherwise 4982 * @return Whether any parent scrolled. 4983 */ 4984 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4985 if (mParent == null) { 4986 return false; 4987 } 4988 4989 View child = this; 4990 4991 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4992 position.set(rectangle); 4993 4994 ViewParent parent = mParent; 4995 boolean scrolled = false; 4996 while (parent != null) { 4997 rectangle.set((int) position.left, (int) position.top, 4998 (int) position.right, (int) position.bottom); 4999 5000 scrolled |= parent.requestChildRectangleOnScreen(child, 5001 rectangle, immediate); 5002 5003 if (!child.hasIdentityMatrix()) { 5004 child.getMatrix().mapRect(position); 5005 } 5006 5007 position.offset(child.mLeft, child.mTop); 5008 5009 if (!(parent instanceof View)) { 5010 break; 5011 } 5012 5013 View parentView = (View) parent; 5014 5015 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5016 5017 child = parentView; 5018 parent = child.getParent(); 5019 } 5020 5021 return scrolled; 5022 } 5023 5024 /** 5025 * Called when this view wants to give up focus. If focus is cleared 5026 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5027 * <p> 5028 * <strong>Note:</strong> When a View clears focus the framework is trying 5029 * to give focus to the first focusable View from the top. Hence, if this 5030 * View is the first from the top that can take focus, then all callbacks 5031 * related to clearing focus will be invoked after which the framework will 5032 * give focus to this view. 5033 * </p> 5034 */ 5035 public void clearFocus() { 5036 if (DBG) { 5037 System.out.println(this + " clearFocus()"); 5038 } 5039 5040 clearFocusInternal(null, true, true); 5041 } 5042 5043 /** 5044 * Clears focus from the view, optionally propagating the change up through 5045 * the parent hierarchy and requesting that the root view place new focus. 5046 * 5047 * @param propagate whether to propagate the change up through the parent 5048 * hierarchy 5049 * @param refocus when propagate is true, specifies whether to request the 5050 * root view place new focus 5051 */ 5052 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5053 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5054 mPrivateFlags &= ~PFLAG_FOCUSED; 5055 5056 if (propagate && mParent != null) { 5057 mParent.clearChildFocus(this); 5058 } 5059 5060 onFocusChanged(false, 0, null); 5061 refreshDrawableState(); 5062 5063 if (propagate && (!refocus || !rootViewRequestFocus())) { 5064 notifyGlobalFocusCleared(this); 5065 } 5066 } 5067 } 5068 5069 void notifyGlobalFocusCleared(View oldFocus) { 5070 if (oldFocus != null && mAttachInfo != null) { 5071 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5072 } 5073 } 5074 5075 boolean rootViewRequestFocus() { 5076 final View root = getRootView(); 5077 return root != null && root.requestFocus(); 5078 } 5079 5080 /** 5081 * Called internally by the view system when a new view is getting focus. 5082 * This is what clears the old focus. 5083 * <p> 5084 * <b>NOTE:</b> The parent view's focused child must be updated manually 5085 * after calling this method. Otherwise, the view hierarchy may be left in 5086 * an inconstent state. 5087 */ 5088 void unFocus(View focused) { 5089 if (DBG) { 5090 System.out.println(this + " unFocus()"); 5091 } 5092 5093 clearFocusInternal(focused, false, false); 5094 } 5095 5096 /** 5097 * Returns true if this view has focus itself, or is the ancestor of the 5098 * view that has focus. 5099 * 5100 * @return True if this view has or contains focus, false otherwise. 5101 */ 5102 @ViewDebug.ExportedProperty(category = "focus") 5103 public boolean hasFocus() { 5104 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5105 } 5106 5107 /** 5108 * Returns true if this view is focusable or if it contains a reachable View 5109 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5110 * is a View whose parents do not block descendants focus. 5111 * 5112 * Only {@link #VISIBLE} views are considered focusable. 5113 * 5114 * @return True if the view is focusable or if the view contains a focusable 5115 * View, false otherwise. 5116 * 5117 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5118 * @see ViewGroup#getTouchscreenBlocksFocus() 5119 */ 5120 public boolean hasFocusable() { 5121 if (!isFocusableInTouchMode()) { 5122 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5123 final ViewGroup g = (ViewGroup) p; 5124 if (g.shouldBlockFocusForTouchscreen()) { 5125 return false; 5126 } 5127 } 5128 } 5129 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5130 } 5131 5132 /** 5133 * Called by the view system when the focus state of this view changes. 5134 * When the focus change event is caused by directional navigation, direction 5135 * and previouslyFocusedRect provide insight into where the focus is coming from. 5136 * When overriding, be sure to call up through to the super class so that 5137 * the standard focus handling will occur. 5138 * 5139 * @param gainFocus True if the View has focus; false otherwise. 5140 * @param direction The direction focus has moved when requestFocus() 5141 * is called to give this view focus. Values are 5142 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5143 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5144 * It may not always apply, in which case use the default. 5145 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5146 * system, of the previously focused view. If applicable, this will be 5147 * passed in as finer grained information about where the focus is coming 5148 * from (in addition to direction). Will be <code>null</code> otherwise. 5149 */ 5150 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5151 @Nullable Rect previouslyFocusedRect) { 5152 if (gainFocus) { 5153 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5154 } else { 5155 notifyViewAccessibilityStateChangedIfNeeded( 5156 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5157 } 5158 5159 InputMethodManager imm = InputMethodManager.peekInstance(); 5160 if (!gainFocus) { 5161 if (isPressed()) { 5162 setPressed(false); 5163 } 5164 if (imm != null && mAttachInfo != null 5165 && mAttachInfo.mHasWindowFocus) { 5166 imm.focusOut(this); 5167 } 5168 onFocusLost(); 5169 } else if (imm != null && mAttachInfo != null 5170 && mAttachInfo.mHasWindowFocus) { 5171 imm.focusIn(this); 5172 } 5173 5174 invalidate(true); 5175 ListenerInfo li = mListenerInfo; 5176 if (li != null && li.mOnFocusChangeListener != null) { 5177 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5178 } 5179 5180 if (mAttachInfo != null) { 5181 mAttachInfo.mKeyDispatchState.reset(this); 5182 } 5183 } 5184 5185 /** 5186 * Sends an accessibility event of the given type. If accessibility is 5187 * not enabled this method has no effect. The default implementation calls 5188 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5189 * to populate information about the event source (this View), then calls 5190 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5191 * populate the text content of the event source including its descendants, 5192 * and last calls 5193 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5194 * on its parent to request sending of the event to interested parties. 5195 * <p> 5196 * If an {@link AccessibilityDelegate} has been specified via calling 5197 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5198 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5199 * responsible for handling this call. 5200 * </p> 5201 * 5202 * @param eventType The type of the event to send, as defined by several types from 5203 * {@link android.view.accessibility.AccessibilityEvent}, such as 5204 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5205 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5206 * 5207 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5208 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5209 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5210 * @see AccessibilityDelegate 5211 */ 5212 public void sendAccessibilityEvent(int eventType) { 5213 if (mAccessibilityDelegate != null) { 5214 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5215 } else { 5216 sendAccessibilityEventInternal(eventType); 5217 } 5218 } 5219 5220 /** 5221 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5222 * {@link AccessibilityEvent} to make an announcement which is related to some 5223 * sort of a context change for which none of the events representing UI transitions 5224 * is a good fit. For example, announcing a new page in a book. If accessibility 5225 * is not enabled this method does nothing. 5226 * 5227 * @param text The announcement text. 5228 */ 5229 public void announceForAccessibility(CharSequence text) { 5230 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5231 AccessibilityEvent event = AccessibilityEvent.obtain( 5232 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5233 onInitializeAccessibilityEvent(event); 5234 event.getText().add(text); 5235 event.setContentDescription(null); 5236 mParent.requestSendAccessibilityEvent(this, event); 5237 } 5238 } 5239 5240 /** 5241 * @see #sendAccessibilityEvent(int) 5242 * 5243 * Note: Called from the default {@link AccessibilityDelegate}. 5244 * 5245 * @hide 5246 */ 5247 public void sendAccessibilityEventInternal(int eventType) { 5248 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5249 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5250 } 5251 } 5252 5253 /** 5254 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5255 * takes as an argument an empty {@link AccessibilityEvent} and does not 5256 * perform a check whether accessibility is enabled. 5257 * <p> 5258 * If an {@link AccessibilityDelegate} has been specified via calling 5259 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5260 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5261 * is responsible for handling this call. 5262 * </p> 5263 * 5264 * @param event The event to send. 5265 * 5266 * @see #sendAccessibilityEvent(int) 5267 */ 5268 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5269 if (mAccessibilityDelegate != null) { 5270 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5271 } else { 5272 sendAccessibilityEventUncheckedInternal(event); 5273 } 5274 } 5275 5276 /** 5277 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5278 * 5279 * Note: Called from the default {@link AccessibilityDelegate}. 5280 * 5281 * @hide 5282 */ 5283 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5284 if (!isShown()) { 5285 return; 5286 } 5287 onInitializeAccessibilityEvent(event); 5288 // Only a subset of accessibility events populates text content. 5289 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5290 dispatchPopulateAccessibilityEvent(event); 5291 } 5292 // In the beginning we called #isShown(), so we know that getParent() is not null. 5293 getParent().requestSendAccessibilityEvent(this, event); 5294 } 5295 5296 /** 5297 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5298 * to its children for adding their text content to the event. Note that the 5299 * event text is populated in a separate dispatch path since we add to the 5300 * event not only the text of the source but also the text of all its descendants. 5301 * A typical implementation will call 5302 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5303 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5304 * on each child. Override this method if custom population of the event text 5305 * content is required. 5306 * <p> 5307 * If an {@link AccessibilityDelegate} has been specified via calling 5308 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5309 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5310 * is responsible for handling this call. 5311 * </p> 5312 * <p> 5313 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5314 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5315 * </p> 5316 * 5317 * @param event The event. 5318 * 5319 * @return True if the event population was completed. 5320 */ 5321 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5322 if (mAccessibilityDelegate != null) { 5323 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5324 } else { 5325 return dispatchPopulateAccessibilityEventInternal(event); 5326 } 5327 } 5328 5329 /** 5330 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5331 * 5332 * Note: Called from the default {@link AccessibilityDelegate}. 5333 * 5334 * @hide 5335 */ 5336 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5337 onPopulateAccessibilityEvent(event); 5338 return false; 5339 } 5340 5341 /** 5342 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5343 * giving a chance to this View to populate the accessibility event with its 5344 * text content. While this method is free to modify event 5345 * attributes other than text content, doing so should normally be performed in 5346 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5347 * <p> 5348 * Example: Adding formatted date string to an accessibility event in addition 5349 * to the text added by the super implementation: 5350 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5351 * super.onPopulateAccessibilityEvent(event); 5352 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5353 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5354 * mCurrentDate.getTimeInMillis(), flags); 5355 * event.getText().add(selectedDateUtterance); 5356 * }</pre> 5357 * <p> 5358 * If an {@link AccessibilityDelegate} has been specified via calling 5359 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5360 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5361 * is responsible for handling this call. 5362 * </p> 5363 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5364 * information to the event, in case the default implementation has basic information to add. 5365 * </p> 5366 * 5367 * @param event The accessibility event which to populate. 5368 * 5369 * @see #sendAccessibilityEvent(int) 5370 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5371 */ 5372 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5373 if (mAccessibilityDelegate != null) { 5374 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5375 } else { 5376 onPopulateAccessibilityEventInternal(event); 5377 } 5378 } 5379 5380 /** 5381 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5382 * 5383 * Note: Called from the default {@link AccessibilityDelegate}. 5384 * 5385 * @hide 5386 */ 5387 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5388 } 5389 5390 /** 5391 * Initializes an {@link AccessibilityEvent} with information about 5392 * this View which is the event source. In other words, the source of 5393 * an accessibility event is the view whose state change triggered firing 5394 * the event. 5395 * <p> 5396 * Example: Setting the password property of an event in addition 5397 * to properties set by the super implementation: 5398 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5399 * super.onInitializeAccessibilityEvent(event); 5400 * event.setPassword(true); 5401 * }</pre> 5402 * <p> 5403 * If an {@link AccessibilityDelegate} has been specified via calling 5404 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5405 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5406 * is responsible for handling this call. 5407 * </p> 5408 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5409 * information to the event, in case the default implementation has basic information to add. 5410 * </p> 5411 * @param event The event to initialize. 5412 * 5413 * @see #sendAccessibilityEvent(int) 5414 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5415 */ 5416 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5417 if (mAccessibilityDelegate != null) { 5418 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5419 } else { 5420 onInitializeAccessibilityEventInternal(event); 5421 } 5422 } 5423 5424 /** 5425 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5426 * 5427 * Note: Called from the default {@link AccessibilityDelegate}. 5428 * 5429 * @hide 5430 */ 5431 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5432 event.setSource(this); 5433 event.setClassName(getAccessibilityClassName()); 5434 event.setPackageName(getContext().getPackageName()); 5435 event.setEnabled(isEnabled()); 5436 event.setContentDescription(mContentDescription); 5437 5438 switch (event.getEventType()) { 5439 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5440 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5441 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5442 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5443 event.setItemCount(focusablesTempList.size()); 5444 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5445 if (mAttachInfo != null) { 5446 focusablesTempList.clear(); 5447 } 5448 } break; 5449 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5450 CharSequence text = getIterableTextForAccessibility(); 5451 if (text != null && text.length() > 0) { 5452 event.setFromIndex(getAccessibilitySelectionStart()); 5453 event.setToIndex(getAccessibilitySelectionEnd()); 5454 event.setItemCount(text.length()); 5455 } 5456 } break; 5457 } 5458 } 5459 5460 /** 5461 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5462 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5463 * This method is responsible for obtaining an accessibility node info from a 5464 * pool of reusable instances and calling 5465 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5466 * initialize the former. 5467 * <p> 5468 * Note: The client is responsible for recycling the obtained instance by calling 5469 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5470 * </p> 5471 * 5472 * @return A populated {@link AccessibilityNodeInfo}. 5473 * 5474 * @see AccessibilityNodeInfo 5475 */ 5476 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5477 if (mAccessibilityDelegate != null) { 5478 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5479 } else { 5480 return createAccessibilityNodeInfoInternal(); 5481 } 5482 } 5483 5484 /** 5485 * @see #createAccessibilityNodeInfo() 5486 * 5487 * @hide 5488 */ 5489 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5490 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5491 if (provider != null) { 5492 return provider.createAccessibilityNodeInfo(View.NO_ID); 5493 } else { 5494 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5495 onInitializeAccessibilityNodeInfo(info); 5496 return info; 5497 } 5498 } 5499 5500 /** 5501 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5502 * The base implementation sets: 5503 * <ul> 5504 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5505 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5506 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5507 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5508 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5509 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5510 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5511 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5512 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5513 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5514 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5515 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5516 * </ul> 5517 * <p> 5518 * Subclasses should override this method, call the super implementation, 5519 * and set additional attributes. 5520 * </p> 5521 * <p> 5522 * If an {@link AccessibilityDelegate} has been specified via calling 5523 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5524 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5525 * is responsible for handling this call. 5526 * </p> 5527 * 5528 * @param info The instance to initialize. 5529 */ 5530 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5531 if (mAccessibilityDelegate != null) { 5532 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5533 } else { 5534 onInitializeAccessibilityNodeInfoInternal(info); 5535 } 5536 } 5537 5538 /** 5539 * Gets the location of this view in screen coordinates. 5540 * 5541 * @param outRect The output location 5542 * @hide 5543 */ 5544 public void getBoundsOnScreen(Rect outRect) { 5545 getBoundsOnScreen(outRect, false); 5546 } 5547 5548 /** 5549 * Gets the location of this view in screen coordinates. 5550 * 5551 * @param outRect The output location 5552 * @param clipToParent Whether to clip child bounds to the parent ones. 5553 * @hide 5554 */ 5555 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 5556 if (mAttachInfo == null) { 5557 return; 5558 } 5559 5560 RectF position = mAttachInfo.mTmpTransformRect; 5561 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5562 5563 if (!hasIdentityMatrix()) { 5564 getMatrix().mapRect(position); 5565 } 5566 5567 position.offset(mLeft, mTop); 5568 5569 ViewParent parent = mParent; 5570 while (parent instanceof View) { 5571 View parentView = (View) parent; 5572 5573 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5574 5575 if (clipToParent) { 5576 position.left = Math.max(position.left, 0); 5577 position.top = Math.max(position.top, 0); 5578 position.right = Math.min(position.right, parentView.getWidth()); 5579 position.bottom = Math.min(position.bottom, parentView.getHeight()); 5580 } 5581 5582 if (!parentView.hasIdentityMatrix()) { 5583 parentView.getMatrix().mapRect(position); 5584 } 5585 5586 position.offset(parentView.mLeft, parentView.mTop); 5587 5588 parent = parentView.mParent; 5589 } 5590 5591 if (parent instanceof ViewRootImpl) { 5592 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5593 position.offset(0, -viewRootImpl.mCurScrollY); 5594 } 5595 5596 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5597 5598 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5599 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5600 } 5601 5602 /** 5603 * Return the class name of this object to be used for accessibility purposes. 5604 * Subclasses should only override this if they are implementing something that 5605 * should be seen as a completely new class of view when used by accessibility, 5606 * unrelated to the class it is deriving from. This is used to fill in 5607 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 5608 */ 5609 public CharSequence getAccessibilityClassName() { 5610 return View.class.getName(); 5611 } 5612 5613 /** 5614 * Called when assist data is being retrieved from a view as part of 5615 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 5616 * @param data 5617 * @param extras 5618 */ 5619 public void onProvideAssistData(ViewAssistData data, Bundle extras) { 5620 } 5621 5622 /** 5623 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5624 * 5625 * Note: Called from the default {@link AccessibilityDelegate}. 5626 * 5627 * @hide 5628 */ 5629 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5630 Rect bounds = mAttachInfo.mTmpInvalRect; 5631 5632 getDrawingRect(bounds); 5633 info.setBoundsInParent(bounds); 5634 5635 getBoundsOnScreen(bounds, true); 5636 info.setBoundsInScreen(bounds); 5637 5638 ViewParent parent = getParentForAccessibility(); 5639 if (parent instanceof View) { 5640 info.setParent((View) parent); 5641 } 5642 5643 if (mID != View.NO_ID) { 5644 View rootView = getRootView(); 5645 if (rootView == null) { 5646 rootView = this; 5647 } 5648 5649 View label = rootView.findLabelForView(this, mID); 5650 if (label != null) { 5651 info.setLabeledBy(label); 5652 } 5653 5654 if ((mAttachInfo.mAccessibilityFetchFlags 5655 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5656 && Resources.resourceHasPackage(mID)) { 5657 try { 5658 String viewId = getResources().getResourceName(mID); 5659 info.setViewIdResourceName(viewId); 5660 } catch (Resources.NotFoundException nfe) { 5661 /* ignore */ 5662 } 5663 } 5664 } 5665 5666 if (mLabelForId != View.NO_ID) { 5667 View rootView = getRootView(); 5668 if (rootView == null) { 5669 rootView = this; 5670 } 5671 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5672 if (labeled != null) { 5673 info.setLabelFor(labeled); 5674 } 5675 } 5676 5677 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 5678 View rootView = getRootView(); 5679 if (rootView == null) { 5680 rootView = this; 5681 } 5682 View next = rootView.findViewInsideOutShouldExist(this, 5683 mAccessibilityTraversalBeforeId); 5684 if (next != null) { 5685 info.setTraversalBefore(next); 5686 } 5687 } 5688 5689 if (mAccessibilityTraversalAfterId != View.NO_ID) { 5690 View rootView = getRootView(); 5691 if (rootView == null) { 5692 rootView = this; 5693 } 5694 View next = rootView.findViewInsideOutShouldExist(this, 5695 mAccessibilityTraversalAfterId); 5696 if (next != null) { 5697 info.setTraversalAfter(next); 5698 } 5699 } 5700 5701 info.setVisibleToUser(isVisibleToUser()); 5702 5703 info.setPackageName(mContext.getPackageName()); 5704 info.setClassName(getAccessibilityClassName()); 5705 info.setContentDescription(getContentDescription()); 5706 5707 info.setEnabled(isEnabled()); 5708 info.setClickable(isClickable()); 5709 info.setFocusable(isFocusable()); 5710 info.setFocused(isFocused()); 5711 info.setAccessibilityFocused(isAccessibilityFocused()); 5712 info.setSelected(isSelected()); 5713 info.setLongClickable(isLongClickable()); 5714 info.setLiveRegion(getAccessibilityLiveRegion()); 5715 5716 // TODO: These make sense only if we are in an AdapterView but all 5717 // views can be selected. Maybe from accessibility perspective 5718 // we should report as selectable view in an AdapterView. 5719 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5720 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5721 5722 if (isFocusable()) { 5723 if (isFocused()) { 5724 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5725 } else { 5726 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5727 } 5728 } 5729 5730 if (!isAccessibilityFocused()) { 5731 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5732 } else { 5733 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5734 } 5735 5736 if (isClickable() && isEnabled()) { 5737 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5738 } 5739 5740 if (isLongClickable() && isEnabled()) { 5741 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5742 } 5743 5744 CharSequence text = getIterableTextForAccessibility(); 5745 if (text != null && text.length() > 0) { 5746 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5747 5748 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5749 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5750 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5751 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5752 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5753 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5754 } 5755 } 5756 5757 private View findLabelForView(View view, int labeledId) { 5758 if (mMatchLabelForPredicate == null) { 5759 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5760 } 5761 mMatchLabelForPredicate.mLabeledId = labeledId; 5762 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5763 } 5764 5765 /** 5766 * Computes whether this view is visible to the user. Such a view is 5767 * attached, visible, all its predecessors are visible, it is not clipped 5768 * entirely by its predecessors, and has an alpha greater than zero. 5769 * 5770 * @return Whether the view is visible on the screen. 5771 * 5772 * @hide 5773 */ 5774 protected boolean isVisibleToUser() { 5775 return isVisibleToUser(null); 5776 } 5777 5778 /** 5779 * Computes whether the given portion of this view is visible to the user. 5780 * Such a view is attached, visible, all its predecessors are visible, 5781 * has an alpha greater than zero, and the specified portion is not 5782 * clipped entirely by its predecessors. 5783 * 5784 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5785 * <code>null</code>, and the entire view will be tested in this case. 5786 * When <code>true</code> is returned by the function, the actual visible 5787 * region will be stored in this parameter; that is, if boundInView is fully 5788 * contained within the view, no modification will be made, otherwise regions 5789 * outside of the visible area of the view will be clipped. 5790 * 5791 * @return Whether the specified portion of the view is visible on the screen. 5792 * 5793 * @hide 5794 */ 5795 protected boolean isVisibleToUser(Rect boundInView) { 5796 if (mAttachInfo != null) { 5797 // Attached to invisible window means this view is not visible. 5798 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5799 return false; 5800 } 5801 // An invisible predecessor or one with alpha zero means 5802 // that this view is not visible to the user. 5803 Object current = this; 5804 while (current instanceof View) { 5805 View view = (View) current; 5806 // We have attach info so this view is attached and there is no 5807 // need to check whether we reach to ViewRootImpl on the way up. 5808 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5809 view.getVisibility() != VISIBLE) { 5810 return false; 5811 } 5812 current = view.mParent; 5813 } 5814 // Check if the view is entirely covered by its predecessors. 5815 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5816 Point offset = mAttachInfo.mPoint; 5817 if (!getGlobalVisibleRect(visibleRect, offset)) { 5818 return false; 5819 } 5820 // Check if the visible portion intersects the rectangle of interest. 5821 if (boundInView != null) { 5822 visibleRect.offset(-offset.x, -offset.y); 5823 return boundInView.intersect(visibleRect); 5824 } 5825 return true; 5826 } 5827 return false; 5828 } 5829 5830 /** 5831 * Returns the delegate for implementing accessibility support via 5832 * composition. For more details see {@link AccessibilityDelegate}. 5833 * 5834 * @return The delegate, or null if none set. 5835 * 5836 * @hide 5837 */ 5838 public AccessibilityDelegate getAccessibilityDelegate() { 5839 return mAccessibilityDelegate; 5840 } 5841 5842 /** 5843 * Sets a delegate for implementing accessibility support via composition as 5844 * opposed to inheritance. The delegate's primary use is for implementing 5845 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5846 * 5847 * @param delegate The delegate instance. 5848 * 5849 * @see AccessibilityDelegate 5850 */ 5851 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5852 mAccessibilityDelegate = delegate; 5853 } 5854 5855 /** 5856 * Gets the provider for managing a virtual view hierarchy rooted at this View 5857 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5858 * that explore the window content. 5859 * <p> 5860 * If this method returns an instance, this instance is responsible for managing 5861 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5862 * View including the one representing the View itself. Similarly the returned 5863 * instance is responsible for performing accessibility actions on any virtual 5864 * view or the root view itself. 5865 * </p> 5866 * <p> 5867 * If an {@link AccessibilityDelegate} has been specified via calling 5868 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5869 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5870 * is responsible for handling this call. 5871 * </p> 5872 * 5873 * @return The provider. 5874 * 5875 * @see AccessibilityNodeProvider 5876 */ 5877 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5878 if (mAccessibilityDelegate != null) { 5879 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5880 } else { 5881 return null; 5882 } 5883 } 5884 5885 /** 5886 * Gets the unique identifier of this view on the screen for accessibility purposes. 5887 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5888 * 5889 * @return The view accessibility id. 5890 * 5891 * @hide 5892 */ 5893 public int getAccessibilityViewId() { 5894 if (mAccessibilityViewId == NO_ID) { 5895 mAccessibilityViewId = sNextAccessibilityViewId++; 5896 } 5897 return mAccessibilityViewId; 5898 } 5899 5900 /** 5901 * Gets the unique identifier of the window in which this View reseides. 5902 * 5903 * @return The window accessibility id. 5904 * 5905 * @hide 5906 */ 5907 public int getAccessibilityWindowId() { 5908 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5909 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5910 } 5911 5912 /** 5913 * Gets the {@link View} description. It briefly describes the view and is 5914 * primarily used for accessibility support. Set this property to enable 5915 * better accessibility support for your application. This is especially 5916 * true for views that do not have textual representation (For example, 5917 * ImageButton). 5918 * 5919 * @return The content description. 5920 * 5921 * @attr ref android.R.styleable#View_contentDescription 5922 */ 5923 @ViewDebug.ExportedProperty(category = "accessibility") 5924 public CharSequence getContentDescription() { 5925 return mContentDescription; 5926 } 5927 5928 /** 5929 * Sets the {@link View} description. It briefly describes the view and is 5930 * primarily used for accessibility support. Set this property to enable 5931 * better accessibility support for your application. This is especially 5932 * true for views that do not have textual representation (For example, 5933 * ImageButton). 5934 * 5935 * @param contentDescription The content description. 5936 * 5937 * @attr ref android.R.styleable#View_contentDescription 5938 */ 5939 @RemotableViewMethod 5940 public void setContentDescription(CharSequence contentDescription) { 5941 if (mContentDescription == null) { 5942 if (contentDescription == null) { 5943 return; 5944 } 5945 } else if (mContentDescription.equals(contentDescription)) { 5946 return; 5947 } 5948 mContentDescription = contentDescription; 5949 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 5950 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5951 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 5952 notifySubtreeAccessibilityStateChangedIfNeeded(); 5953 } else { 5954 notifyViewAccessibilityStateChangedIfNeeded( 5955 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 5956 } 5957 } 5958 5959 /** 5960 * Sets the id of a view before which this one is visited in accessibility traversal. 5961 * A screen-reader must visit the content of this view before the content of the one 5962 * it precedes. For example, if view B is set to be before view A, then a screen-reader 5963 * will traverse the entire content of B before traversing the entire content of A, 5964 * regardles of what traversal strategy it is using. 5965 * <p> 5966 * Views that do not have specified before/after relationships are traversed in order 5967 * determined by the screen-reader. 5968 * </p> 5969 * <p> 5970 * Setting that this view is before a view that is not important for accessibility 5971 * or if this view is not important for accessibility will have no effect as the 5972 * screen-reader is not aware of unimportant views. 5973 * </p> 5974 * 5975 * @param beforeId The id of a view this one precedes in accessibility traversal. 5976 * 5977 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 5978 * 5979 * @see #setImportantForAccessibility(int) 5980 */ 5981 @RemotableViewMethod 5982 public void setAccessibilityTraversalBefore(int beforeId) { 5983 if (mAccessibilityTraversalBeforeId == beforeId) { 5984 return; 5985 } 5986 mAccessibilityTraversalBeforeId = beforeId; 5987 notifyViewAccessibilityStateChangedIfNeeded( 5988 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5989 } 5990 5991 /** 5992 * Gets the id of a view before which this one is visited in accessibility traversal. 5993 * 5994 * @return The id of a view this one precedes in accessibility traversal if 5995 * specified, otherwise {@link #NO_ID}. 5996 * 5997 * @see #setAccessibilityTraversalBefore(int) 5998 */ 5999 public int getAccessibilityTraversalBefore() { 6000 return mAccessibilityTraversalBeforeId; 6001 } 6002 6003 /** 6004 * Sets the id of a view after which this one is visited in accessibility traversal. 6005 * A screen-reader must visit the content of the other view before the content of this 6006 * one. For example, if view B is set to be after view A, then a screen-reader 6007 * will traverse the entire content of A before traversing the entire content of B, 6008 * regardles of what traversal strategy it is using. 6009 * <p> 6010 * Views that do not have specified before/after relationships are traversed in order 6011 * determined by the screen-reader. 6012 * </p> 6013 * <p> 6014 * Setting that this view is after a view that is not important for accessibility 6015 * or if this view is not important for accessibility will have no effect as the 6016 * screen-reader is not aware of unimportant views. 6017 * </p> 6018 * 6019 * @param afterId The id of a view this one succedees in accessibility traversal. 6020 * 6021 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 6022 * 6023 * @see #setImportantForAccessibility(int) 6024 */ 6025 @RemotableViewMethod 6026 public void setAccessibilityTraversalAfter(int afterId) { 6027 if (mAccessibilityTraversalAfterId == afterId) { 6028 return; 6029 } 6030 mAccessibilityTraversalAfterId = afterId; 6031 notifyViewAccessibilityStateChangedIfNeeded( 6032 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6033 } 6034 6035 /** 6036 * Gets the id of a view after which this one is visited in accessibility traversal. 6037 * 6038 * @return The id of a view this one succeedes in accessibility traversal if 6039 * specified, otherwise {@link #NO_ID}. 6040 * 6041 * @see #setAccessibilityTraversalAfter(int) 6042 */ 6043 public int getAccessibilityTraversalAfter() { 6044 return mAccessibilityTraversalAfterId; 6045 } 6046 6047 /** 6048 * Gets the id of a view for which this view serves as a label for 6049 * accessibility purposes. 6050 * 6051 * @return The labeled view id. 6052 */ 6053 @ViewDebug.ExportedProperty(category = "accessibility") 6054 public int getLabelFor() { 6055 return mLabelForId; 6056 } 6057 6058 /** 6059 * Sets the id of a view for which this view serves as a label for 6060 * accessibility purposes. 6061 * 6062 * @param id The labeled view id. 6063 */ 6064 @RemotableViewMethod 6065 public void setLabelFor(int id) { 6066 if (mLabelForId == id) { 6067 return; 6068 } 6069 mLabelForId = id; 6070 if (mLabelForId != View.NO_ID 6071 && mID == View.NO_ID) { 6072 mID = generateViewId(); 6073 } 6074 notifyViewAccessibilityStateChangedIfNeeded( 6075 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6076 } 6077 6078 /** 6079 * Invoked whenever this view loses focus, either by losing window focus or by losing 6080 * focus within its window. This method can be used to clear any state tied to the 6081 * focus. For instance, if a button is held pressed with the trackball and the window 6082 * loses focus, this method can be used to cancel the press. 6083 * 6084 * Subclasses of View overriding this method should always call super.onFocusLost(). 6085 * 6086 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6087 * @see #onWindowFocusChanged(boolean) 6088 * 6089 * @hide pending API council approval 6090 */ 6091 protected void onFocusLost() { 6092 resetPressedState(); 6093 } 6094 6095 private void resetPressedState() { 6096 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6097 return; 6098 } 6099 6100 if (isPressed()) { 6101 setPressed(false); 6102 6103 if (!mHasPerformedLongPress) { 6104 removeLongPressCallback(); 6105 } 6106 } 6107 } 6108 6109 /** 6110 * Returns true if this view has focus 6111 * 6112 * @return True if this view has focus, false otherwise. 6113 */ 6114 @ViewDebug.ExportedProperty(category = "focus") 6115 public boolean isFocused() { 6116 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6117 } 6118 6119 /** 6120 * Find the view in the hierarchy rooted at this view that currently has 6121 * focus. 6122 * 6123 * @return The view that currently has focus, or null if no focused view can 6124 * be found. 6125 */ 6126 public View findFocus() { 6127 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6128 } 6129 6130 /** 6131 * Indicates whether this view is one of the set of scrollable containers in 6132 * its window. 6133 * 6134 * @return whether this view is one of the set of scrollable containers in 6135 * its window 6136 * 6137 * @attr ref android.R.styleable#View_isScrollContainer 6138 */ 6139 public boolean isScrollContainer() { 6140 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6141 } 6142 6143 /** 6144 * Change whether this view is one of the set of scrollable containers in 6145 * its window. This will be used to determine whether the window can 6146 * resize or must pan when a soft input area is open -- scrollable 6147 * containers allow the window to use resize mode since the container 6148 * will appropriately shrink. 6149 * 6150 * @attr ref android.R.styleable#View_isScrollContainer 6151 */ 6152 public void setScrollContainer(boolean isScrollContainer) { 6153 if (isScrollContainer) { 6154 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6155 mAttachInfo.mScrollContainers.add(this); 6156 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6157 } 6158 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6159 } else { 6160 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6161 mAttachInfo.mScrollContainers.remove(this); 6162 } 6163 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6164 } 6165 } 6166 6167 /** 6168 * Returns the quality of the drawing cache. 6169 * 6170 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6171 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6172 * 6173 * @see #setDrawingCacheQuality(int) 6174 * @see #setDrawingCacheEnabled(boolean) 6175 * @see #isDrawingCacheEnabled() 6176 * 6177 * @attr ref android.R.styleable#View_drawingCacheQuality 6178 */ 6179 @DrawingCacheQuality 6180 public int getDrawingCacheQuality() { 6181 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6182 } 6183 6184 /** 6185 * Set the drawing cache quality of this view. This value is used only when the 6186 * drawing cache is enabled 6187 * 6188 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6189 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6190 * 6191 * @see #getDrawingCacheQuality() 6192 * @see #setDrawingCacheEnabled(boolean) 6193 * @see #isDrawingCacheEnabled() 6194 * 6195 * @attr ref android.R.styleable#View_drawingCacheQuality 6196 */ 6197 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6198 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6199 } 6200 6201 /** 6202 * Returns whether the screen should remain on, corresponding to the current 6203 * value of {@link #KEEP_SCREEN_ON}. 6204 * 6205 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6206 * 6207 * @see #setKeepScreenOn(boolean) 6208 * 6209 * @attr ref android.R.styleable#View_keepScreenOn 6210 */ 6211 public boolean getKeepScreenOn() { 6212 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6213 } 6214 6215 /** 6216 * Controls whether the screen should remain on, modifying the 6217 * value of {@link #KEEP_SCREEN_ON}. 6218 * 6219 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6220 * 6221 * @see #getKeepScreenOn() 6222 * 6223 * @attr ref android.R.styleable#View_keepScreenOn 6224 */ 6225 public void setKeepScreenOn(boolean keepScreenOn) { 6226 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6227 } 6228 6229 /** 6230 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6231 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6232 * 6233 * @attr ref android.R.styleable#View_nextFocusLeft 6234 */ 6235 public int getNextFocusLeftId() { 6236 return mNextFocusLeftId; 6237 } 6238 6239 /** 6240 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6241 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6242 * decide automatically. 6243 * 6244 * @attr ref android.R.styleable#View_nextFocusLeft 6245 */ 6246 public void setNextFocusLeftId(int nextFocusLeftId) { 6247 mNextFocusLeftId = nextFocusLeftId; 6248 } 6249 6250 /** 6251 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6252 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6253 * 6254 * @attr ref android.R.styleable#View_nextFocusRight 6255 */ 6256 public int getNextFocusRightId() { 6257 return mNextFocusRightId; 6258 } 6259 6260 /** 6261 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6262 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6263 * decide automatically. 6264 * 6265 * @attr ref android.R.styleable#View_nextFocusRight 6266 */ 6267 public void setNextFocusRightId(int nextFocusRightId) { 6268 mNextFocusRightId = nextFocusRightId; 6269 } 6270 6271 /** 6272 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6273 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6274 * 6275 * @attr ref android.R.styleable#View_nextFocusUp 6276 */ 6277 public int getNextFocusUpId() { 6278 return mNextFocusUpId; 6279 } 6280 6281 /** 6282 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6283 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6284 * decide automatically. 6285 * 6286 * @attr ref android.R.styleable#View_nextFocusUp 6287 */ 6288 public void setNextFocusUpId(int nextFocusUpId) { 6289 mNextFocusUpId = nextFocusUpId; 6290 } 6291 6292 /** 6293 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6294 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6295 * 6296 * @attr ref android.R.styleable#View_nextFocusDown 6297 */ 6298 public int getNextFocusDownId() { 6299 return mNextFocusDownId; 6300 } 6301 6302 /** 6303 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6304 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6305 * decide automatically. 6306 * 6307 * @attr ref android.R.styleable#View_nextFocusDown 6308 */ 6309 public void setNextFocusDownId(int nextFocusDownId) { 6310 mNextFocusDownId = nextFocusDownId; 6311 } 6312 6313 /** 6314 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6315 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6316 * 6317 * @attr ref android.R.styleable#View_nextFocusForward 6318 */ 6319 public int getNextFocusForwardId() { 6320 return mNextFocusForwardId; 6321 } 6322 6323 /** 6324 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6325 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6326 * decide automatically. 6327 * 6328 * @attr ref android.R.styleable#View_nextFocusForward 6329 */ 6330 public void setNextFocusForwardId(int nextFocusForwardId) { 6331 mNextFocusForwardId = nextFocusForwardId; 6332 } 6333 6334 /** 6335 * Returns the visibility of this view and all of its ancestors 6336 * 6337 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6338 */ 6339 public boolean isShown() { 6340 View current = this; 6341 //noinspection ConstantConditions 6342 do { 6343 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6344 return false; 6345 } 6346 ViewParent parent = current.mParent; 6347 if (parent == null) { 6348 return false; // We are not attached to the view root 6349 } 6350 if (!(parent instanceof View)) { 6351 return true; 6352 } 6353 current = (View) parent; 6354 } while (current != null); 6355 6356 return false; 6357 } 6358 6359 /** 6360 * Called by the view hierarchy when the content insets for a window have 6361 * changed, to allow it to adjust its content to fit within those windows. 6362 * The content insets tell you the space that the status bar, input method, 6363 * and other system windows infringe on the application's window. 6364 * 6365 * <p>You do not normally need to deal with this function, since the default 6366 * window decoration given to applications takes care of applying it to the 6367 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6368 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6369 * and your content can be placed under those system elements. You can then 6370 * use this method within your view hierarchy if you have parts of your UI 6371 * which you would like to ensure are not being covered. 6372 * 6373 * <p>The default implementation of this method simply applies the content 6374 * insets to the view's padding, consuming that content (modifying the 6375 * insets to be 0), and returning true. This behavior is off by default, but can 6376 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6377 * 6378 * <p>This function's traversal down the hierarchy is depth-first. The same content 6379 * insets object is propagated down the hierarchy, so any changes made to it will 6380 * be seen by all following views (including potentially ones above in 6381 * the hierarchy since this is a depth-first traversal). The first view 6382 * that returns true will abort the entire traversal. 6383 * 6384 * <p>The default implementation works well for a situation where it is 6385 * used with a container that covers the entire window, allowing it to 6386 * apply the appropriate insets to its content on all edges. If you need 6387 * a more complicated layout (such as two different views fitting system 6388 * windows, one on the top of the window, and one on the bottom), 6389 * you can override the method and handle the insets however you would like. 6390 * Note that the insets provided by the framework are always relative to the 6391 * far edges of the window, not accounting for the location of the called view 6392 * within that window. (In fact when this method is called you do not yet know 6393 * where the layout will place the view, as it is done before layout happens.) 6394 * 6395 * <p>Note: unlike many View methods, there is no dispatch phase to this 6396 * call. If you are overriding it in a ViewGroup and want to allow the 6397 * call to continue to your children, you must be sure to call the super 6398 * implementation. 6399 * 6400 * <p>Here is a sample layout that makes use of fitting system windows 6401 * to have controls for a video view placed inside of the window decorations 6402 * that it hides and shows. This can be used with code like the second 6403 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6404 * 6405 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6406 * 6407 * @param insets Current content insets of the window. Prior to 6408 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6409 * the insets or else you and Android will be unhappy. 6410 * 6411 * @return {@code true} if this view applied the insets and it should not 6412 * continue propagating further down the hierarchy, {@code false} otherwise. 6413 * @see #getFitsSystemWindows() 6414 * @see #setFitsSystemWindows(boolean) 6415 * @see #setSystemUiVisibility(int) 6416 * 6417 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6418 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6419 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6420 * to implement handling their own insets. 6421 */ 6422 protected boolean fitSystemWindows(Rect insets) { 6423 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6424 if (insets == null) { 6425 // Null insets by definition have already been consumed. 6426 // This call cannot apply insets since there are none to apply, 6427 // so return false. 6428 return false; 6429 } 6430 // If we're not in the process of dispatching the newer apply insets call, 6431 // that means we're not in the compatibility path. Dispatch into the newer 6432 // apply insets path and take things from there. 6433 try { 6434 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6435 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6436 } finally { 6437 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6438 } 6439 } else { 6440 // We're being called from the newer apply insets path. 6441 // Perform the standard fallback behavior. 6442 return fitSystemWindowsInt(insets); 6443 } 6444 } 6445 6446 private boolean fitSystemWindowsInt(Rect insets) { 6447 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6448 mUserPaddingStart = UNDEFINED_PADDING; 6449 mUserPaddingEnd = UNDEFINED_PADDING; 6450 Rect localInsets = sThreadLocal.get(); 6451 if (localInsets == null) { 6452 localInsets = new Rect(); 6453 sThreadLocal.set(localInsets); 6454 } 6455 boolean res = computeFitSystemWindows(insets, localInsets); 6456 mUserPaddingLeftInitial = localInsets.left; 6457 mUserPaddingRightInitial = localInsets.right; 6458 internalSetPadding(localInsets.left, localInsets.top, 6459 localInsets.right, localInsets.bottom); 6460 return res; 6461 } 6462 return false; 6463 } 6464 6465 /** 6466 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6467 * 6468 * <p>This method should be overridden by views that wish to apply a policy different from or 6469 * in addition to the default behavior. Clients that wish to force a view subtree 6470 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6471 * 6472 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6473 * it will be called during dispatch instead of this method. The listener may optionally 6474 * call this method from its own implementation if it wishes to apply the view's default 6475 * insets policy in addition to its own.</p> 6476 * 6477 * <p>Implementations of this method should either return the insets parameter unchanged 6478 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6479 * that this view applied itself. This allows new inset types added in future platform 6480 * versions to pass through existing implementations unchanged without being erroneously 6481 * consumed.</p> 6482 * 6483 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6484 * property is set then the view will consume the system window insets and apply them 6485 * as padding for the view.</p> 6486 * 6487 * @param insets Insets to apply 6488 * @return The supplied insets with any applied insets consumed 6489 */ 6490 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6491 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6492 // We weren't called from within a direct call to fitSystemWindows, 6493 // call into it as a fallback in case we're in a class that overrides it 6494 // and has logic to perform. 6495 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6496 return insets.consumeSystemWindowInsets(); 6497 } 6498 } else { 6499 // We were called from within a direct call to fitSystemWindows. 6500 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6501 return insets.consumeSystemWindowInsets(); 6502 } 6503 } 6504 return insets; 6505 } 6506 6507 /** 6508 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6509 * window insets to this view. The listener's 6510 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6511 * method will be called instead of the view's 6512 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6513 * 6514 * @param listener Listener to set 6515 * 6516 * @see #onApplyWindowInsets(WindowInsets) 6517 */ 6518 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6519 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6520 } 6521 6522 /** 6523 * Request to apply the given window insets to this view or another view in its subtree. 6524 * 6525 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6526 * obscured by window decorations or overlays. This can include the status and navigation bars, 6527 * action bars, input methods and more. New inset categories may be added in the future. 6528 * The method returns the insets provided minus any that were applied by this view or its 6529 * children.</p> 6530 * 6531 * <p>Clients wishing to provide custom behavior should override the 6532 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6533 * {@link OnApplyWindowInsetsListener} via the 6534 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6535 * method.</p> 6536 * 6537 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6538 * </p> 6539 * 6540 * @param insets Insets to apply 6541 * @return The provided insets minus the insets that were consumed 6542 */ 6543 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6544 try { 6545 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6546 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6547 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6548 } else { 6549 return onApplyWindowInsets(insets); 6550 } 6551 } finally { 6552 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6553 } 6554 } 6555 6556 /** 6557 * @hide Compute the insets that should be consumed by this view and the ones 6558 * that should propagate to those under it. 6559 */ 6560 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6561 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6562 || mAttachInfo == null 6563 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6564 && !mAttachInfo.mOverscanRequested)) { 6565 outLocalInsets.set(inoutInsets); 6566 inoutInsets.set(0, 0, 0, 0); 6567 return true; 6568 } else { 6569 // The application wants to take care of fitting system window for 6570 // the content... however we still need to take care of any overscan here. 6571 final Rect overscan = mAttachInfo.mOverscanInsets; 6572 outLocalInsets.set(overscan); 6573 inoutInsets.left -= overscan.left; 6574 inoutInsets.top -= overscan.top; 6575 inoutInsets.right -= overscan.right; 6576 inoutInsets.bottom -= overscan.bottom; 6577 return false; 6578 } 6579 } 6580 6581 /** 6582 * Compute insets that should be consumed by this view and the ones that should propagate 6583 * to those under it. 6584 * 6585 * @param in Insets currently being processed by this View, likely received as a parameter 6586 * to {@link #onApplyWindowInsets(WindowInsets)}. 6587 * @param outLocalInsets A Rect that will receive the insets that should be consumed 6588 * by this view 6589 * @return Insets that should be passed along to views under this one 6590 */ 6591 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 6592 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6593 || mAttachInfo == null 6594 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 6595 outLocalInsets.set(in.getSystemWindowInsets()); 6596 return in.consumeSystemWindowInsets(); 6597 } else { 6598 outLocalInsets.set(0, 0, 0, 0); 6599 return in; 6600 } 6601 } 6602 6603 /** 6604 * Sets whether or not this view should account for system screen decorations 6605 * such as the status bar and inset its content; that is, controlling whether 6606 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6607 * executed. See that method for more details. 6608 * 6609 * <p>Note that if you are providing your own implementation of 6610 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6611 * flag to true -- your implementation will be overriding the default 6612 * implementation that checks this flag. 6613 * 6614 * @param fitSystemWindows If true, then the default implementation of 6615 * {@link #fitSystemWindows(Rect)} will be executed. 6616 * 6617 * @attr ref android.R.styleable#View_fitsSystemWindows 6618 * @see #getFitsSystemWindows() 6619 * @see #fitSystemWindows(Rect) 6620 * @see #setSystemUiVisibility(int) 6621 */ 6622 public void setFitsSystemWindows(boolean fitSystemWindows) { 6623 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6624 } 6625 6626 /** 6627 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6628 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6629 * will be executed. 6630 * 6631 * @return {@code true} if the default implementation of 6632 * {@link #fitSystemWindows(Rect)} will be executed. 6633 * 6634 * @attr ref android.R.styleable#View_fitsSystemWindows 6635 * @see #setFitsSystemWindows(boolean) 6636 * @see #fitSystemWindows(Rect) 6637 * @see #setSystemUiVisibility(int) 6638 */ 6639 @ViewDebug.ExportedProperty 6640 public boolean getFitsSystemWindows() { 6641 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6642 } 6643 6644 /** @hide */ 6645 public boolean fitsSystemWindows() { 6646 return getFitsSystemWindows(); 6647 } 6648 6649 /** 6650 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6651 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6652 */ 6653 public void requestFitSystemWindows() { 6654 if (mParent != null) { 6655 mParent.requestFitSystemWindows(); 6656 } 6657 } 6658 6659 /** 6660 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6661 */ 6662 public void requestApplyInsets() { 6663 requestFitSystemWindows(); 6664 } 6665 6666 /** 6667 * For use by PhoneWindow to make its own system window fitting optional. 6668 * @hide 6669 */ 6670 public void makeOptionalFitsSystemWindows() { 6671 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6672 } 6673 6674 /** 6675 * Returns the visibility status for this view. 6676 * 6677 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6678 * @attr ref android.R.styleable#View_visibility 6679 */ 6680 @ViewDebug.ExportedProperty(mapping = { 6681 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6682 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6683 @ViewDebug.IntToString(from = GONE, to = "GONE") 6684 }) 6685 @Visibility 6686 public int getVisibility() { 6687 return mViewFlags & VISIBILITY_MASK; 6688 } 6689 6690 /** 6691 * Set the enabled state of this view. 6692 * 6693 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6694 * @attr ref android.R.styleable#View_visibility 6695 */ 6696 @RemotableViewMethod 6697 public void setVisibility(@Visibility int visibility) { 6698 setFlags(visibility, VISIBILITY_MASK); 6699 } 6700 6701 /** 6702 * Returns the enabled status for this view. The interpretation of the 6703 * enabled state varies by subclass. 6704 * 6705 * @return True if this view is enabled, false otherwise. 6706 */ 6707 @ViewDebug.ExportedProperty 6708 public boolean isEnabled() { 6709 return (mViewFlags & ENABLED_MASK) == ENABLED; 6710 } 6711 6712 /** 6713 * Set the enabled state of this view. The interpretation of the enabled 6714 * state varies by subclass. 6715 * 6716 * @param enabled True if this view is enabled, false otherwise. 6717 */ 6718 @RemotableViewMethod 6719 public void setEnabled(boolean enabled) { 6720 if (enabled == isEnabled()) return; 6721 6722 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6723 6724 /* 6725 * The View most likely has to change its appearance, so refresh 6726 * the drawable state. 6727 */ 6728 refreshDrawableState(); 6729 6730 // Invalidate too, since the default behavior for views is to be 6731 // be drawn at 50% alpha rather than to change the drawable. 6732 invalidate(true); 6733 6734 if (!enabled) { 6735 cancelPendingInputEvents(); 6736 } 6737 } 6738 6739 /** 6740 * Set whether this view can receive the focus. 6741 * 6742 * Setting this to false will also ensure that this view is not focusable 6743 * in touch mode. 6744 * 6745 * @param focusable If true, this view can receive the focus. 6746 * 6747 * @see #setFocusableInTouchMode(boolean) 6748 * @attr ref android.R.styleable#View_focusable 6749 */ 6750 public void setFocusable(boolean focusable) { 6751 if (!focusable) { 6752 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6753 } 6754 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6755 } 6756 6757 /** 6758 * Set whether this view can receive focus while in touch mode. 6759 * 6760 * Setting this to true will also ensure that this view is focusable. 6761 * 6762 * @param focusableInTouchMode If true, this view can receive the focus while 6763 * in touch mode. 6764 * 6765 * @see #setFocusable(boolean) 6766 * @attr ref android.R.styleable#View_focusableInTouchMode 6767 */ 6768 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6769 // Focusable in touch mode should always be set before the focusable flag 6770 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6771 // which, in touch mode, will not successfully request focus on this view 6772 // because the focusable in touch mode flag is not set 6773 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6774 if (focusableInTouchMode) { 6775 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6776 } 6777 } 6778 6779 /** 6780 * Set whether this view should have sound effects enabled for events such as 6781 * clicking and touching. 6782 * 6783 * <p>You may wish to disable sound effects for a view if you already play sounds, 6784 * for instance, a dial key that plays dtmf tones. 6785 * 6786 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6787 * @see #isSoundEffectsEnabled() 6788 * @see #playSoundEffect(int) 6789 * @attr ref android.R.styleable#View_soundEffectsEnabled 6790 */ 6791 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6792 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6793 } 6794 6795 /** 6796 * @return whether this view should have sound effects enabled for events such as 6797 * clicking and touching. 6798 * 6799 * @see #setSoundEffectsEnabled(boolean) 6800 * @see #playSoundEffect(int) 6801 * @attr ref android.R.styleable#View_soundEffectsEnabled 6802 */ 6803 @ViewDebug.ExportedProperty 6804 public boolean isSoundEffectsEnabled() { 6805 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6806 } 6807 6808 /** 6809 * Set whether this view should have haptic feedback for events such as 6810 * long presses. 6811 * 6812 * <p>You may wish to disable haptic feedback if your view already controls 6813 * its own haptic feedback. 6814 * 6815 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6816 * @see #isHapticFeedbackEnabled() 6817 * @see #performHapticFeedback(int) 6818 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6819 */ 6820 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6821 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6822 } 6823 6824 /** 6825 * @return whether this view should have haptic feedback enabled for events 6826 * long presses. 6827 * 6828 * @see #setHapticFeedbackEnabled(boolean) 6829 * @see #performHapticFeedback(int) 6830 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6831 */ 6832 @ViewDebug.ExportedProperty 6833 public boolean isHapticFeedbackEnabled() { 6834 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6835 } 6836 6837 /** 6838 * Returns the layout direction for this view. 6839 * 6840 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6841 * {@link #LAYOUT_DIRECTION_RTL}, 6842 * {@link #LAYOUT_DIRECTION_INHERIT} or 6843 * {@link #LAYOUT_DIRECTION_LOCALE}. 6844 * 6845 * @attr ref android.R.styleable#View_layoutDirection 6846 * 6847 * @hide 6848 */ 6849 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6850 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6851 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6852 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6853 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6854 }) 6855 @LayoutDir 6856 public int getRawLayoutDirection() { 6857 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6858 } 6859 6860 /** 6861 * Set the layout direction for this view. This will propagate a reset of layout direction 6862 * resolution to the view's children and resolve layout direction for this view. 6863 * 6864 * @param layoutDirection the layout direction to set. Should be one of: 6865 * 6866 * {@link #LAYOUT_DIRECTION_LTR}, 6867 * {@link #LAYOUT_DIRECTION_RTL}, 6868 * {@link #LAYOUT_DIRECTION_INHERIT}, 6869 * {@link #LAYOUT_DIRECTION_LOCALE}. 6870 * 6871 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6872 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6873 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6874 * 6875 * @attr ref android.R.styleable#View_layoutDirection 6876 */ 6877 @RemotableViewMethod 6878 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6879 if (getRawLayoutDirection() != layoutDirection) { 6880 // Reset the current layout direction and the resolved one 6881 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6882 resetRtlProperties(); 6883 // Set the new layout direction (filtered) 6884 mPrivateFlags2 |= 6885 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6886 // We need to resolve all RTL properties as they all depend on layout direction 6887 resolveRtlPropertiesIfNeeded(); 6888 requestLayout(); 6889 invalidate(true); 6890 } 6891 } 6892 6893 /** 6894 * Returns the resolved layout direction for this view. 6895 * 6896 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6897 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6898 * 6899 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6900 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6901 * 6902 * @attr ref android.R.styleable#View_layoutDirection 6903 */ 6904 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6905 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6906 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6907 }) 6908 @ResolvedLayoutDir 6909 public int getLayoutDirection() { 6910 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6911 if (targetSdkVersion < JELLY_BEAN_MR1) { 6912 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6913 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6914 } 6915 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6916 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6917 } 6918 6919 /** 6920 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6921 * layout attribute and/or the inherited value from the parent 6922 * 6923 * @return true if the layout is right-to-left. 6924 * 6925 * @hide 6926 */ 6927 @ViewDebug.ExportedProperty(category = "layout") 6928 public boolean isLayoutRtl() { 6929 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6930 } 6931 6932 /** 6933 * Indicates whether the view is currently tracking transient state that the 6934 * app should not need to concern itself with saving and restoring, but that 6935 * the framework should take special note to preserve when possible. 6936 * 6937 * <p>A view with transient state cannot be trivially rebound from an external 6938 * data source, such as an adapter binding item views in a list. This may be 6939 * because the view is performing an animation, tracking user selection 6940 * of content, or similar.</p> 6941 * 6942 * @return true if the view has transient state 6943 */ 6944 @ViewDebug.ExportedProperty(category = "layout") 6945 public boolean hasTransientState() { 6946 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6947 } 6948 6949 /** 6950 * Set whether this view is currently tracking transient state that the 6951 * framework should attempt to preserve when possible. This flag is reference counted, 6952 * so every call to setHasTransientState(true) should be paired with a later call 6953 * to setHasTransientState(false). 6954 * 6955 * <p>A view with transient state cannot be trivially rebound from an external 6956 * data source, such as an adapter binding item views in a list. This may be 6957 * because the view is performing an animation, tracking user selection 6958 * of content, or similar.</p> 6959 * 6960 * @param hasTransientState true if this view has transient state 6961 */ 6962 public void setHasTransientState(boolean hasTransientState) { 6963 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6964 mTransientStateCount - 1; 6965 if (mTransientStateCount < 0) { 6966 mTransientStateCount = 0; 6967 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6968 "unmatched pair of setHasTransientState calls"); 6969 } else if ((hasTransientState && mTransientStateCount == 1) || 6970 (!hasTransientState && mTransientStateCount == 0)) { 6971 // update flag if we've just incremented up from 0 or decremented down to 0 6972 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6973 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6974 if (mParent != null) { 6975 try { 6976 mParent.childHasTransientStateChanged(this, hasTransientState); 6977 } catch (AbstractMethodError e) { 6978 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6979 " does not fully implement ViewParent", e); 6980 } 6981 } 6982 } 6983 } 6984 6985 /** 6986 * Returns true if this view is currently attached to a window. 6987 */ 6988 public boolean isAttachedToWindow() { 6989 return mAttachInfo != null; 6990 } 6991 6992 /** 6993 * Returns true if this view has been through at least one layout since it 6994 * was last attached to or detached from a window. 6995 */ 6996 public boolean isLaidOut() { 6997 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6998 } 6999 7000 /** 7001 * If this view doesn't do any drawing on its own, set this flag to 7002 * allow further optimizations. By default, this flag is not set on 7003 * View, but could be set on some View subclasses such as ViewGroup. 7004 * 7005 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 7006 * you should clear this flag. 7007 * 7008 * @param willNotDraw whether or not this View draw on its own 7009 */ 7010 public void setWillNotDraw(boolean willNotDraw) { 7011 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 7012 } 7013 7014 /** 7015 * Returns whether or not this View draws on its own. 7016 * 7017 * @return true if this view has nothing to draw, false otherwise 7018 */ 7019 @ViewDebug.ExportedProperty(category = "drawing") 7020 public boolean willNotDraw() { 7021 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 7022 } 7023 7024 /** 7025 * When a View's drawing cache is enabled, drawing is redirected to an 7026 * offscreen bitmap. Some views, like an ImageView, must be able to 7027 * bypass this mechanism if they already draw a single bitmap, to avoid 7028 * unnecessary usage of the memory. 7029 * 7030 * @param willNotCacheDrawing true if this view does not cache its 7031 * drawing, false otherwise 7032 */ 7033 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 7034 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7035 } 7036 7037 /** 7038 * Returns whether or not this View can cache its drawing or not. 7039 * 7040 * @return true if this view does not cache its drawing, false otherwise 7041 */ 7042 @ViewDebug.ExportedProperty(category = "drawing") 7043 public boolean willNotCacheDrawing() { 7044 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7045 } 7046 7047 /** 7048 * Indicates whether this view reacts to click events or not. 7049 * 7050 * @return true if the view is clickable, false otherwise 7051 * 7052 * @see #setClickable(boolean) 7053 * @attr ref android.R.styleable#View_clickable 7054 */ 7055 @ViewDebug.ExportedProperty 7056 public boolean isClickable() { 7057 return (mViewFlags & CLICKABLE) == CLICKABLE; 7058 } 7059 7060 /** 7061 * Enables or disables click events for this view. When a view 7062 * is clickable it will change its state to "pressed" on every click. 7063 * Subclasses should set the view clickable to visually react to 7064 * user's clicks. 7065 * 7066 * @param clickable true to make the view clickable, false otherwise 7067 * 7068 * @see #isClickable() 7069 * @attr ref android.R.styleable#View_clickable 7070 */ 7071 public void setClickable(boolean clickable) { 7072 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7073 } 7074 7075 /** 7076 * Indicates whether this view reacts to long click events or not. 7077 * 7078 * @return true if the view is long clickable, false otherwise 7079 * 7080 * @see #setLongClickable(boolean) 7081 * @attr ref android.R.styleable#View_longClickable 7082 */ 7083 public boolean isLongClickable() { 7084 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7085 } 7086 7087 /** 7088 * Enables or disables long click events for this view. When a view is long 7089 * clickable it reacts to the user holding down the button for a longer 7090 * duration than a tap. This event can either launch the listener or a 7091 * context menu. 7092 * 7093 * @param longClickable true to make the view long clickable, false otherwise 7094 * @see #isLongClickable() 7095 * @attr ref android.R.styleable#View_longClickable 7096 */ 7097 public void setLongClickable(boolean longClickable) { 7098 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7099 } 7100 7101 /** 7102 * Sets the pressed state for this view and provides a touch coordinate for 7103 * animation hinting. 7104 * 7105 * @param pressed Pass true to set the View's internal state to "pressed", 7106 * or false to reverts the View's internal state from a 7107 * previously set "pressed" state. 7108 * @param x The x coordinate of the touch that caused the press 7109 * @param y The y coordinate of the touch that caused the press 7110 */ 7111 private void setPressed(boolean pressed, float x, float y) { 7112 if (pressed) { 7113 drawableHotspotChanged(x, y); 7114 } 7115 7116 setPressed(pressed); 7117 } 7118 7119 /** 7120 * Sets the pressed state for this view. 7121 * 7122 * @see #isClickable() 7123 * @see #setClickable(boolean) 7124 * 7125 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7126 * the View's internal state from a previously set "pressed" state. 7127 */ 7128 public void setPressed(boolean pressed) { 7129 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7130 7131 if (pressed) { 7132 mPrivateFlags |= PFLAG_PRESSED; 7133 } else { 7134 mPrivateFlags &= ~PFLAG_PRESSED; 7135 } 7136 7137 if (needsRefresh) { 7138 refreshDrawableState(); 7139 } 7140 dispatchSetPressed(pressed); 7141 } 7142 7143 /** 7144 * Dispatch setPressed to all of this View's children. 7145 * 7146 * @see #setPressed(boolean) 7147 * 7148 * @param pressed The new pressed state 7149 */ 7150 protected void dispatchSetPressed(boolean pressed) { 7151 } 7152 7153 /** 7154 * Indicates whether the view is currently in pressed state. Unless 7155 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7156 * the pressed state. 7157 * 7158 * @see #setPressed(boolean) 7159 * @see #isClickable() 7160 * @see #setClickable(boolean) 7161 * 7162 * @return true if the view is currently pressed, false otherwise 7163 */ 7164 @ViewDebug.ExportedProperty 7165 public boolean isPressed() { 7166 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7167 } 7168 7169 /** 7170 * Indicates whether this view will save its state (that is, 7171 * whether its {@link #onSaveInstanceState} method will be called). 7172 * 7173 * @return Returns true if the view state saving is enabled, else false. 7174 * 7175 * @see #setSaveEnabled(boolean) 7176 * @attr ref android.R.styleable#View_saveEnabled 7177 */ 7178 public boolean isSaveEnabled() { 7179 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7180 } 7181 7182 /** 7183 * Controls whether the saving of this view's state is 7184 * enabled (that is, whether its {@link #onSaveInstanceState} method 7185 * will be called). Note that even if freezing is enabled, the 7186 * view still must have an id assigned to it (via {@link #setId(int)}) 7187 * for its state to be saved. This flag can only disable the 7188 * saving of this view; any child views may still have their state saved. 7189 * 7190 * @param enabled Set to false to <em>disable</em> state saving, or true 7191 * (the default) to allow it. 7192 * 7193 * @see #isSaveEnabled() 7194 * @see #setId(int) 7195 * @see #onSaveInstanceState() 7196 * @attr ref android.R.styleable#View_saveEnabled 7197 */ 7198 public void setSaveEnabled(boolean enabled) { 7199 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7200 } 7201 7202 /** 7203 * Gets whether the framework should discard touches when the view's 7204 * window is obscured by another visible window. 7205 * Refer to the {@link View} security documentation for more details. 7206 * 7207 * @return True if touch filtering is enabled. 7208 * 7209 * @see #setFilterTouchesWhenObscured(boolean) 7210 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7211 */ 7212 @ViewDebug.ExportedProperty 7213 public boolean getFilterTouchesWhenObscured() { 7214 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7215 } 7216 7217 /** 7218 * Sets whether the framework should discard touches when the view's 7219 * window is obscured by another visible window. 7220 * Refer to the {@link View} security documentation for more details. 7221 * 7222 * @param enabled True if touch filtering should be enabled. 7223 * 7224 * @see #getFilterTouchesWhenObscured 7225 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7226 */ 7227 public void setFilterTouchesWhenObscured(boolean enabled) { 7228 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7229 FILTER_TOUCHES_WHEN_OBSCURED); 7230 } 7231 7232 /** 7233 * Indicates whether the entire hierarchy under this view will save its 7234 * state when a state saving traversal occurs from its parent. The default 7235 * is true; if false, these views will not be saved unless 7236 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7237 * 7238 * @return Returns true if the view state saving from parent is enabled, else false. 7239 * 7240 * @see #setSaveFromParentEnabled(boolean) 7241 */ 7242 public boolean isSaveFromParentEnabled() { 7243 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7244 } 7245 7246 /** 7247 * Controls whether the entire hierarchy under this view will save its 7248 * state when a state saving traversal occurs from its parent. The default 7249 * is true; if false, these views will not be saved unless 7250 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7251 * 7252 * @param enabled Set to false to <em>disable</em> state saving, or true 7253 * (the default) to allow it. 7254 * 7255 * @see #isSaveFromParentEnabled() 7256 * @see #setId(int) 7257 * @see #onSaveInstanceState() 7258 */ 7259 public void setSaveFromParentEnabled(boolean enabled) { 7260 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7261 } 7262 7263 7264 /** 7265 * Returns whether this View is able to take focus. 7266 * 7267 * @return True if this view can take focus, or false otherwise. 7268 * @attr ref android.R.styleable#View_focusable 7269 */ 7270 @ViewDebug.ExportedProperty(category = "focus") 7271 public final boolean isFocusable() { 7272 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7273 } 7274 7275 /** 7276 * When a view is focusable, it may not want to take focus when in touch mode. 7277 * For example, a button would like focus when the user is navigating via a D-pad 7278 * so that the user can click on it, but once the user starts touching the screen, 7279 * the button shouldn't take focus 7280 * @return Whether the view is focusable in touch mode. 7281 * @attr ref android.R.styleable#View_focusableInTouchMode 7282 */ 7283 @ViewDebug.ExportedProperty 7284 public final boolean isFocusableInTouchMode() { 7285 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7286 } 7287 7288 /** 7289 * Find the nearest view in the specified direction that can take focus. 7290 * This does not actually give focus to that view. 7291 * 7292 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7293 * 7294 * @return The nearest focusable in the specified direction, or null if none 7295 * can be found. 7296 */ 7297 public View focusSearch(@FocusRealDirection int direction) { 7298 if (mParent != null) { 7299 return mParent.focusSearch(this, direction); 7300 } else { 7301 return null; 7302 } 7303 } 7304 7305 /** 7306 * This method is the last chance for the focused view and its ancestors to 7307 * respond to an arrow key. This is called when the focused view did not 7308 * consume the key internally, nor could the view system find a new view in 7309 * the requested direction to give focus to. 7310 * 7311 * @param focused The currently focused view. 7312 * @param direction The direction focus wants to move. One of FOCUS_UP, 7313 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7314 * @return True if the this view consumed this unhandled move. 7315 */ 7316 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7317 return false; 7318 } 7319 7320 /** 7321 * If a user manually specified the next view id for a particular direction, 7322 * use the root to look up the view. 7323 * @param root The root view of the hierarchy containing this view. 7324 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7325 * or FOCUS_BACKWARD. 7326 * @return The user specified next view, or null if there is none. 7327 */ 7328 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7329 switch (direction) { 7330 case FOCUS_LEFT: 7331 if (mNextFocusLeftId == View.NO_ID) return null; 7332 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7333 case FOCUS_RIGHT: 7334 if (mNextFocusRightId == View.NO_ID) return null; 7335 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7336 case FOCUS_UP: 7337 if (mNextFocusUpId == View.NO_ID) return null; 7338 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7339 case FOCUS_DOWN: 7340 if (mNextFocusDownId == View.NO_ID) return null; 7341 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7342 case FOCUS_FORWARD: 7343 if (mNextFocusForwardId == View.NO_ID) return null; 7344 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7345 case FOCUS_BACKWARD: { 7346 if (mID == View.NO_ID) return null; 7347 final int id = mID; 7348 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7349 @Override 7350 public boolean apply(View t) { 7351 return t.mNextFocusForwardId == id; 7352 } 7353 }); 7354 } 7355 } 7356 return null; 7357 } 7358 7359 private View findViewInsideOutShouldExist(View root, int id) { 7360 if (mMatchIdPredicate == null) { 7361 mMatchIdPredicate = new MatchIdPredicate(); 7362 } 7363 mMatchIdPredicate.mId = id; 7364 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7365 if (result == null) { 7366 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7367 } 7368 return result; 7369 } 7370 7371 /** 7372 * Find and return all focusable views that are descendants of this view, 7373 * possibly including this view if it is focusable itself. 7374 * 7375 * @param direction The direction of the focus 7376 * @return A list of focusable views 7377 */ 7378 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7379 ArrayList<View> result = new ArrayList<View>(24); 7380 addFocusables(result, direction); 7381 return result; 7382 } 7383 7384 /** 7385 * Add any focusable views that are descendants of this view (possibly 7386 * including this view if it is focusable itself) to views. If we are in touch mode, 7387 * only add views that are also focusable in touch mode. 7388 * 7389 * @param views Focusable views found so far 7390 * @param direction The direction of the focus 7391 */ 7392 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7393 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7394 } 7395 7396 /** 7397 * Adds any focusable views that are descendants of this view (possibly 7398 * including this view if it is focusable itself) to views. This method 7399 * adds all focusable views regardless if we are in touch mode or 7400 * only views focusable in touch mode if we are in touch mode or 7401 * only views that can take accessibility focus if accessibility is enabled 7402 * depending on the focusable mode parameter. 7403 * 7404 * @param views Focusable views found so far or null if all we are interested is 7405 * the number of focusables. 7406 * @param direction The direction of the focus. 7407 * @param focusableMode The type of focusables to be added. 7408 * 7409 * @see #FOCUSABLES_ALL 7410 * @see #FOCUSABLES_TOUCH_MODE 7411 */ 7412 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7413 @FocusableMode int focusableMode) { 7414 if (views == null) { 7415 return; 7416 } 7417 if (!isFocusable()) { 7418 return; 7419 } 7420 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7421 && isInTouchMode() && !isFocusableInTouchMode()) { 7422 return; 7423 } 7424 views.add(this); 7425 } 7426 7427 /** 7428 * Finds the Views that contain given text. The containment is case insensitive. 7429 * The search is performed by either the text that the View renders or the content 7430 * description that describes the view for accessibility purposes and the view does 7431 * not render or both. Clients can specify how the search is to be performed via 7432 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7433 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7434 * 7435 * @param outViews The output list of matching Views. 7436 * @param searched The text to match against. 7437 * 7438 * @see #FIND_VIEWS_WITH_TEXT 7439 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7440 * @see #setContentDescription(CharSequence) 7441 */ 7442 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7443 @FindViewFlags int flags) { 7444 if (getAccessibilityNodeProvider() != null) { 7445 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7446 outViews.add(this); 7447 } 7448 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7449 && (searched != null && searched.length() > 0) 7450 && (mContentDescription != null && mContentDescription.length() > 0)) { 7451 String searchedLowerCase = searched.toString().toLowerCase(); 7452 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7453 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7454 outViews.add(this); 7455 } 7456 } 7457 } 7458 7459 /** 7460 * Find and return all touchable views that are descendants of this view, 7461 * possibly including this view if it is touchable itself. 7462 * 7463 * @return A list of touchable views 7464 */ 7465 public ArrayList<View> getTouchables() { 7466 ArrayList<View> result = new ArrayList<View>(); 7467 addTouchables(result); 7468 return result; 7469 } 7470 7471 /** 7472 * Add any touchable views that are descendants of this view (possibly 7473 * including this view if it is touchable itself) to views. 7474 * 7475 * @param views Touchable views found so far 7476 */ 7477 public void addTouchables(ArrayList<View> views) { 7478 final int viewFlags = mViewFlags; 7479 7480 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7481 && (viewFlags & ENABLED_MASK) == ENABLED) { 7482 views.add(this); 7483 } 7484 } 7485 7486 /** 7487 * Returns whether this View is accessibility focused. 7488 * 7489 * @return True if this View is accessibility focused. 7490 */ 7491 public boolean isAccessibilityFocused() { 7492 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7493 } 7494 7495 /** 7496 * Call this to try to give accessibility focus to this view. 7497 * 7498 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7499 * returns false or the view is no visible or the view already has accessibility 7500 * focus. 7501 * 7502 * See also {@link #focusSearch(int)}, which is what you call to say that you 7503 * have focus, and you want your parent to look for the next one. 7504 * 7505 * @return Whether this view actually took accessibility focus. 7506 * 7507 * @hide 7508 */ 7509 public boolean requestAccessibilityFocus() { 7510 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7511 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7512 return false; 7513 } 7514 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7515 return false; 7516 } 7517 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7518 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7519 ViewRootImpl viewRootImpl = getViewRootImpl(); 7520 if (viewRootImpl != null) { 7521 viewRootImpl.setAccessibilityFocus(this, null); 7522 } 7523 invalidate(); 7524 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7525 return true; 7526 } 7527 return false; 7528 } 7529 7530 /** 7531 * Call this to try to clear accessibility focus of this view. 7532 * 7533 * See also {@link #focusSearch(int)}, which is what you call to say that you 7534 * have focus, and you want your parent to look for the next one. 7535 * 7536 * @hide 7537 */ 7538 public void clearAccessibilityFocus() { 7539 clearAccessibilityFocusNoCallbacks(); 7540 // Clear the global reference of accessibility focus if this 7541 // view or any of its descendants had accessibility focus. 7542 ViewRootImpl viewRootImpl = getViewRootImpl(); 7543 if (viewRootImpl != null) { 7544 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7545 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7546 viewRootImpl.setAccessibilityFocus(null, null); 7547 } 7548 } 7549 } 7550 7551 private void sendAccessibilityHoverEvent(int eventType) { 7552 // Since we are not delivering to a client accessibility events from not 7553 // important views (unless the clinet request that) we need to fire the 7554 // event from the deepest view exposed to the client. As a consequence if 7555 // the user crosses a not exposed view the client will see enter and exit 7556 // of the exposed predecessor followed by and enter and exit of that same 7557 // predecessor when entering and exiting the not exposed descendant. This 7558 // is fine since the client has a clear idea which view is hovered at the 7559 // price of a couple more events being sent. This is a simple and 7560 // working solution. 7561 View source = this; 7562 while (true) { 7563 if (source.includeForAccessibility()) { 7564 source.sendAccessibilityEvent(eventType); 7565 return; 7566 } 7567 ViewParent parent = source.getParent(); 7568 if (parent instanceof View) { 7569 source = (View) parent; 7570 } else { 7571 return; 7572 } 7573 } 7574 } 7575 7576 /** 7577 * Clears accessibility focus without calling any callback methods 7578 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7579 * is used for clearing accessibility focus when giving this focus to 7580 * another view. 7581 */ 7582 void clearAccessibilityFocusNoCallbacks() { 7583 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7584 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7585 invalidate(); 7586 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7587 } 7588 } 7589 7590 /** 7591 * Call this to try to give focus to a specific view or to one of its 7592 * descendants. 7593 * 7594 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7595 * false), or if it is focusable and it is not focusable in touch mode 7596 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7597 * 7598 * See also {@link #focusSearch(int)}, which is what you call to say that you 7599 * have focus, and you want your parent to look for the next one. 7600 * 7601 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7602 * {@link #FOCUS_DOWN} and <code>null</code>. 7603 * 7604 * @return Whether this view or one of its descendants actually took focus. 7605 */ 7606 public final boolean requestFocus() { 7607 return requestFocus(View.FOCUS_DOWN); 7608 } 7609 7610 /** 7611 * Call this to try to give focus to a specific view or to one of its 7612 * descendants and give it a hint about what direction focus is heading. 7613 * 7614 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7615 * false), or if it is focusable and it is not focusable in touch mode 7616 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7617 * 7618 * See also {@link #focusSearch(int)}, which is what you call to say that you 7619 * have focus, and you want your parent to look for the next one. 7620 * 7621 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7622 * <code>null</code> set for the previously focused rectangle. 7623 * 7624 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7625 * @return Whether this view or one of its descendants actually took focus. 7626 */ 7627 public final boolean requestFocus(int direction) { 7628 return requestFocus(direction, null); 7629 } 7630 7631 /** 7632 * Call this to try to give focus to a specific view or to one of its descendants 7633 * and give it hints about the direction and a specific rectangle that the focus 7634 * is coming from. The rectangle can help give larger views a finer grained hint 7635 * about where focus is coming from, and therefore, where to show selection, or 7636 * forward focus change internally. 7637 * 7638 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7639 * false), or if it is focusable and it is not focusable in touch mode 7640 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7641 * 7642 * A View will not take focus if it is not visible. 7643 * 7644 * A View will not take focus if one of its parents has 7645 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7646 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7647 * 7648 * See also {@link #focusSearch(int)}, which is what you call to say that you 7649 * have focus, and you want your parent to look for the next one. 7650 * 7651 * You may wish to override this method if your custom {@link View} has an internal 7652 * {@link View} that it wishes to forward the request to. 7653 * 7654 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7655 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7656 * to give a finer grained hint about where focus is coming from. May be null 7657 * if there is no hint. 7658 * @return Whether this view or one of its descendants actually took focus. 7659 */ 7660 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7661 return requestFocusNoSearch(direction, previouslyFocusedRect); 7662 } 7663 7664 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7665 // need to be focusable 7666 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7667 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7668 return false; 7669 } 7670 7671 // need to be focusable in touch mode if in touch mode 7672 if (isInTouchMode() && 7673 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7674 return false; 7675 } 7676 7677 // need to not have any parents blocking us 7678 if (hasAncestorThatBlocksDescendantFocus()) { 7679 return false; 7680 } 7681 7682 handleFocusGainInternal(direction, previouslyFocusedRect); 7683 return true; 7684 } 7685 7686 /** 7687 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7688 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 7689 * touch mode to request focus when they are touched. 7690 * 7691 * @return Whether this view or one of its descendants actually took focus. 7692 * 7693 * @see #isInTouchMode() 7694 * 7695 */ 7696 public final boolean requestFocusFromTouch() { 7697 // Leave touch mode if we need to 7698 if (isInTouchMode()) { 7699 ViewRootImpl viewRoot = getViewRootImpl(); 7700 if (viewRoot != null) { 7701 viewRoot.ensureTouchMode(false); 7702 } 7703 } 7704 return requestFocus(View.FOCUS_DOWN); 7705 } 7706 7707 /** 7708 * @return Whether any ancestor of this view blocks descendant focus. 7709 */ 7710 private boolean hasAncestorThatBlocksDescendantFocus() { 7711 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7712 ViewParent ancestor = mParent; 7713 while (ancestor instanceof ViewGroup) { 7714 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7715 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7716 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7717 return true; 7718 } else { 7719 ancestor = vgAncestor.getParent(); 7720 } 7721 } 7722 return false; 7723 } 7724 7725 /** 7726 * Gets the mode for determining whether this View is important for accessibility 7727 * which is if it fires accessibility events and if it is reported to 7728 * accessibility services that query the screen. 7729 * 7730 * @return The mode for determining whether a View is important for accessibility. 7731 * 7732 * @attr ref android.R.styleable#View_importantForAccessibility 7733 * 7734 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7735 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7736 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7737 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7738 */ 7739 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7740 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7741 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7742 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7743 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7744 to = "noHideDescendants") 7745 }) 7746 public int getImportantForAccessibility() { 7747 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7748 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7749 } 7750 7751 /** 7752 * Sets the live region mode for this view. This indicates to accessibility 7753 * services whether they should automatically notify the user about changes 7754 * to the view's content description or text, or to the content descriptions 7755 * or text of the view's children (where applicable). 7756 * <p> 7757 * For example, in a login screen with a TextView that displays an "incorrect 7758 * password" notification, that view should be marked as a live region with 7759 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7760 * <p> 7761 * To disable change notifications for this view, use 7762 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7763 * mode for most views. 7764 * <p> 7765 * To indicate that the user should be notified of changes, use 7766 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7767 * <p> 7768 * If the view's changes should interrupt ongoing speech and notify the user 7769 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7770 * 7771 * @param mode The live region mode for this view, one of: 7772 * <ul> 7773 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7774 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7775 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7776 * </ul> 7777 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7778 */ 7779 public void setAccessibilityLiveRegion(int mode) { 7780 if (mode != getAccessibilityLiveRegion()) { 7781 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7782 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7783 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7784 notifyViewAccessibilityStateChangedIfNeeded( 7785 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7786 } 7787 } 7788 7789 /** 7790 * Gets the live region mode for this View. 7791 * 7792 * @return The live region mode for the view. 7793 * 7794 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7795 * 7796 * @see #setAccessibilityLiveRegion(int) 7797 */ 7798 public int getAccessibilityLiveRegion() { 7799 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7800 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7801 } 7802 7803 /** 7804 * Sets how to determine whether this view is important for accessibility 7805 * which is if it fires accessibility events and if it is reported to 7806 * accessibility services that query the screen. 7807 * 7808 * @param mode How to determine whether this view is important for accessibility. 7809 * 7810 * @attr ref android.R.styleable#View_importantForAccessibility 7811 * 7812 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7813 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7814 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7815 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7816 */ 7817 public void setImportantForAccessibility(int mode) { 7818 final int oldMode = getImportantForAccessibility(); 7819 if (mode != oldMode) { 7820 // If we're moving between AUTO and another state, we might not need 7821 // to send a subtree changed notification. We'll store the computed 7822 // importance, since we'll need to check it later to make sure. 7823 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7824 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7825 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7826 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7827 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7828 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7829 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7830 notifySubtreeAccessibilityStateChangedIfNeeded(); 7831 } else { 7832 notifyViewAccessibilityStateChangedIfNeeded( 7833 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7834 } 7835 } 7836 } 7837 7838 /** 7839 * Computes whether this view should be exposed for accessibility. In 7840 * general, views that are interactive or provide information are exposed 7841 * while views that serve only as containers are hidden. 7842 * <p> 7843 * If an ancestor of this view has importance 7844 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7845 * returns <code>false</code>. 7846 * <p> 7847 * Otherwise, the value is computed according to the view's 7848 * {@link #getImportantForAccessibility()} value: 7849 * <ol> 7850 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7851 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7852 * </code> 7853 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7854 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7855 * view satisfies any of the following: 7856 * <ul> 7857 * <li>Is actionable, e.g. {@link #isClickable()}, 7858 * {@link #isLongClickable()}, or {@link #isFocusable()} 7859 * <li>Has an {@link AccessibilityDelegate} 7860 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7861 * {@link OnKeyListener}, etc. 7862 * <li>Is an accessibility live region, e.g. 7863 * {@link #getAccessibilityLiveRegion()} is not 7864 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7865 * </ul> 7866 * </ol> 7867 * 7868 * @return Whether the view is exposed for accessibility. 7869 * @see #setImportantForAccessibility(int) 7870 * @see #getImportantForAccessibility() 7871 */ 7872 public boolean isImportantForAccessibility() { 7873 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7874 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7875 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7876 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7877 return false; 7878 } 7879 7880 // Check parent mode to ensure we're not hidden. 7881 ViewParent parent = mParent; 7882 while (parent instanceof View) { 7883 if (((View) parent).getImportantForAccessibility() 7884 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7885 return false; 7886 } 7887 parent = parent.getParent(); 7888 } 7889 7890 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7891 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7892 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7893 } 7894 7895 /** 7896 * Gets the parent for accessibility purposes. Note that the parent for 7897 * accessibility is not necessary the immediate parent. It is the first 7898 * predecessor that is important for accessibility. 7899 * 7900 * @return The parent for accessibility purposes. 7901 */ 7902 public ViewParent getParentForAccessibility() { 7903 if (mParent instanceof View) { 7904 View parentView = (View) mParent; 7905 if (parentView.includeForAccessibility()) { 7906 return mParent; 7907 } else { 7908 return mParent.getParentForAccessibility(); 7909 } 7910 } 7911 return null; 7912 } 7913 7914 /** 7915 * Adds the children of a given View for accessibility. Since some Views are 7916 * not important for accessibility the children for accessibility are not 7917 * necessarily direct children of the view, rather they are the first level of 7918 * descendants important for accessibility. 7919 * 7920 * @param children The list of children for accessibility. 7921 */ 7922 public void addChildrenForAccessibility(ArrayList<View> children) { 7923 7924 } 7925 7926 /** 7927 * Whether to regard this view for accessibility. A view is regarded for 7928 * accessibility if it is important for accessibility or the querying 7929 * accessibility service has explicitly requested that view not 7930 * important for accessibility are regarded. 7931 * 7932 * @return Whether to regard the view for accessibility. 7933 * 7934 * @hide 7935 */ 7936 public boolean includeForAccessibility() { 7937 if (mAttachInfo != null) { 7938 return (mAttachInfo.mAccessibilityFetchFlags 7939 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7940 || isImportantForAccessibility(); 7941 } 7942 return false; 7943 } 7944 7945 /** 7946 * Returns whether the View is considered actionable from 7947 * accessibility perspective. Such view are important for 7948 * accessibility. 7949 * 7950 * @return True if the view is actionable for accessibility. 7951 * 7952 * @hide 7953 */ 7954 public boolean isActionableForAccessibility() { 7955 return (isClickable() || isLongClickable() || isFocusable()); 7956 } 7957 7958 /** 7959 * Returns whether the View has registered callbacks which makes it 7960 * important for accessibility. 7961 * 7962 * @return True if the view is actionable for accessibility. 7963 */ 7964 private boolean hasListenersForAccessibility() { 7965 ListenerInfo info = getListenerInfo(); 7966 return mTouchDelegate != null || info.mOnKeyListener != null 7967 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7968 || info.mOnHoverListener != null || info.mOnDragListener != null; 7969 } 7970 7971 /** 7972 * Notifies that the accessibility state of this view changed. The change 7973 * is local to this view and does not represent structural changes such 7974 * as children and parent. For example, the view became focusable. The 7975 * notification is at at most once every 7976 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7977 * to avoid unnecessary load to the system. Also once a view has a pending 7978 * notification this method is a NOP until the notification has been sent. 7979 * 7980 * @hide 7981 */ 7982 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7983 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7984 return; 7985 } 7986 if (mSendViewStateChangedAccessibilityEvent == null) { 7987 mSendViewStateChangedAccessibilityEvent = 7988 new SendViewStateChangedAccessibilityEvent(); 7989 } 7990 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7991 } 7992 7993 /** 7994 * Notifies that the accessibility state of this view changed. The change 7995 * is *not* local to this view and does represent structural changes such 7996 * as children and parent. For example, the view size changed. The 7997 * notification is at at most once every 7998 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7999 * to avoid unnecessary load to the system. Also once a view has a pending 8000 * notification this method is a NOP until the notification has been sent. 8001 * 8002 * @hide 8003 */ 8004 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 8005 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 8006 return; 8007 } 8008 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 8009 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8010 if (mParent != null) { 8011 try { 8012 mParent.notifySubtreeAccessibilityStateChanged( 8013 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 8014 } catch (AbstractMethodError e) { 8015 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8016 " does not fully implement ViewParent", e); 8017 } 8018 } 8019 } 8020 } 8021 8022 /** 8023 * Reset the flag indicating the accessibility state of the subtree rooted 8024 * at this view changed. 8025 */ 8026 void resetSubtreeAccessibilityStateChanged() { 8027 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8028 } 8029 8030 /** 8031 * Report an accessibility action to this view's parents for delegated processing. 8032 * 8033 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 8034 * call this method to delegate an accessibility action to a supporting parent. If the parent 8035 * returns true from its 8036 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 8037 * method this method will return true to signify that the action was consumed.</p> 8038 * 8039 * <p>This method is useful for implementing nested scrolling child views. If 8040 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 8041 * a custom view implementation may invoke this method to allow a parent to consume the 8042 * scroll first. If this method returns true the custom view should skip its own scrolling 8043 * behavior.</p> 8044 * 8045 * @param action Accessibility action to delegate 8046 * @param arguments Optional action arguments 8047 * @return true if the action was consumed by a parent 8048 */ 8049 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 8050 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 8051 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 8052 return true; 8053 } 8054 } 8055 return false; 8056 } 8057 8058 /** 8059 * Performs the specified accessibility action on the view. For 8060 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 8061 * <p> 8062 * If an {@link AccessibilityDelegate} has been specified via calling 8063 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8064 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8065 * is responsible for handling this call. 8066 * </p> 8067 * 8068 * <p>The default implementation will delegate 8069 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 8070 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 8071 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 8072 * 8073 * @param action The action to perform. 8074 * @param arguments Optional action arguments. 8075 * @return Whether the action was performed. 8076 */ 8077 public boolean performAccessibilityAction(int action, Bundle arguments) { 8078 if (mAccessibilityDelegate != null) { 8079 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8080 } else { 8081 return performAccessibilityActionInternal(action, arguments); 8082 } 8083 } 8084 8085 /** 8086 * @see #performAccessibilityAction(int, Bundle) 8087 * 8088 * Note: Called from the default {@link AccessibilityDelegate}. 8089 * 8090 * @hide 8091 */ 8092 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8093 if (isNestedScrollingEnabled() 8094 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 8095 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) { 8096 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 8097 return true; 8098 } 8099 } 8100 8101 switch (action) { 8102 case AccessibilityNodeInfo.ACTION_CLICK: { 8103 if (isClickable()) { 8104 performClick(); 8105 return true; 8106 } 8107 } break; 8108 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8109 if (isLongClickable()) { 8110 performLongClick(); 8111 return true; 8112 } 8113 } break; 8114 case AccessibilityNodeInfo.ACTION_FOCUS: { 8115 if (!hasFocus()) { 8116 // Get out of touch mode since accessibility 8117 // wants to move focus around. 8118 getViewRootImpl().ensureTouchMode(false); 8119 return requestFocus(); 8120 } 8121 } break; 8122 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8123 if (hasFocus()) { 8124 clearFocus(); 8125 return !isFocused(); 8126 } 8127 } break; 8128 case AccessibilityNodeInfo.ACTION_SELECT: { 8129 if (!isSelected()) { 8130 setSelected(true); 8131 return isSelected(); 8132 } 8133 } break; 8134 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8135 if (isSelected()) { 8136 setSelected(false); 8137 return !isSelected(); 8138 } 8139 } break; 8140 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8141 if (!isAccessibilityFocused()) { 8142 return requestAccessibilityFocus(); 8143 } 8144 } break; 8145 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8146 if (isAccessibilityFocused()) { 8147 clearAccessibilityFocus(); 8148 return true; 8149 } 8150 } break; 8151 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8152 if (arguments != null) { 8153 final int granularity = arguments.getInt( 8154 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8155 final boolean extendSelection = arguments.getBoolean( 8156 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8157 return traverseAtGranularity(granularity, true, extendSelection); 8158 } 8159 } break; 8160 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8161 if (arguments != null) { 8162 final int granularity = arguments.getInt( 8163 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8164 final boolean extendSelection = arguments.getBoolean( 8165 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8166 return traverseAtGranularity(granularity, false, extendSelection); 8167 } 8168 } break; 8169 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8170 CharSequence text = getIterableTextForAccessibility(); 8171 if (text == null) { 8172 return false; 8173 } 8174 final int start = (arguments != null) ? arguments.getInt( 8175 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8176 final int end = (arguments != null) ? arguments.getInt( 8177 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8178 // Only cursor position can be specified (selection length == 0) 8179 if ((getAccessibilitySelectionStart() != start 8180 || getAccessibilitySelectionEnd() != end) 8181 && (start == end)) { 8182 setAccessibilitySelection(start, end); 8183 notifyViewAccessibilityStateChangedIfNeeded( 8184 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8185 return true; 8186 } 8187 } break; 8188 } 8189 return false; 8190 } 8191 8192 private boolean traverseAtGranularity(int granularity, boolean forward, 8193 boolean extendSelection) { 8194 CharSequence text = getIterableTextForAccessibility(); 8195 if (text == null || text.length() == 0) { 8196 return false; 8197 } 8198 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8199 if (iterator == null) { 8200 return false; 8201 } 8202 int current = getAccessibilitySelectionEnd(); 8203 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8204 current = forward ? 0 : text.length(); 8205 } 8206 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8207 if (range == null) { 8208 return false; 8209 } 8210 final int segmentStart = range[0]; 8211 final int segmentEnd = range[1]; 8212 int selectionStart; 8213 int selectionEnd; 8214 if (extendSelection && isAccessibilitySelectionExtendable()) { 8215 selectionStart = getAccessibilitySelectionStart(); 8216 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8217 selectionStart = forward ? segmentStart : segmentEnd; 8218 } 8219 selectionEnd = forward ? segmentEnd : segmentStart; 8220 } else { 8221 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8222 } 8223 setAccessibilitySelection(selectionStart, selectionEnd); 8224 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8225 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8226 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8227 return true; 8228 } 8229 8230 /** 8231 * Gets the text reported for accessibility purposes. 8232 * 8233 * @return The accessibility text. 8234 * 8235 * @hide 8236 */ 8237 public CharSequence getIterableTextForAccessibility() { 8238 return getContentDescription(); 8239 } 8240 8241 /** 8242 * Gets whether accessibility selection can be extended. 8243 * 8244 * @return If selection is extensible. 8245 * 8246 * @hide 8247 */ 8248 public boolean isAccessibilitySelectionExtendable() { 8249 return false; 8250 } 8251 8252 /** 8253 * @hide 8254 */ 8255 public int getAccessibilitySelectionStart() { 8256 return mAccessibilityCursorPosition; 8257 } 8258 8259 /** 8260 * @hide 8261 */ 8262 public int getAccessibilitySelectionEnd() { 8263 return getAccessibilitySelectionStart(); 8264 } 8265 8266 /** 8267 * @hide 8268 */ 8269 public void setAccessibilitySelection(int start, int end) { 8270 if (start == end && end == mAccessibilityCursorPosition) { 8271 return; 8272 } 8273 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 8274 mAccessibilityCursorPosition = start; 8275 } else { 8276 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 8277 } 8278 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 8279 } 8280 8281 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 8282 int fromIndex, int toIndex) { 8283 if (mParent == null) { 8284 return; 8285 } 8286 AccessibilityEvent event = AccessibilityEvent.obtain( 8287 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 8288 onInitializeAccessibilityEvent(event); 8289 onPopulateAccessibilityEvent(event); 8290 event.setFromIndex(fromIndex); 8291 event.setToIndex(toIndex); 8292 event.setAction(action); 8293 event.setMovementGranularity(granularity); 8294 mParent.requestSendAccessibilityEvent(this, event); 8295 } 8296 8297 /** 8298 * @hide 8299 */ 8300 public TextSegmentIterator getIteratorForGranularity(int granularity) { 8301 switch (granularity) { 8302 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 8303 CharSequence text = getIterableTextForAccessibility(); 8304 if (text != null && text.length() > 0) { 8305 CharacterTextSegmentIterator iterator = 8306 CharacterTextSegmentIterator.getInstance( 8307 mContext.getResources().getConfiguration().locale); 8308 iterator.initialize(text.toString()); 8309 return iterator; 8310 } 8311 } break; 8312 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8313 CharSequence text = getIterableTextForAccessibility(); 8314 if (text != null && text.length() > 0) { 8315 WordTextSegmentIterator iterator = 8316 WordTextSegmentIterator.getInstance( 8317 mContext.getResources().getConfiguration().locale); 8318 iterator.initialize(text.toString()); 8319 return iterator; 8320 } 8321 } break; 8322 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8323 CharSequence text = getIterableTextForAccessibility(); 8324 if (text != null && text.length() > 0) { 8325 ParagraphTextSegmentIterator iterator = 8326 ParagraphTextSegmentIterator.getInstance(); 8327 iterator.initialize(text.toString()); 8328 return iterator; 8329 } 8330 } break; 8331 } 8332 return null; 8333 } 8334 8335 /** 8336 * @hide 8337 */ 8338 public void dispatchStartTemporaryDetach() { 8339 onStartTemporaryDetach(); 8340 } 8341 8342 /** 8343 * This is called when a container is going to temporarily detach a child, with 8344 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8345 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8346 * {@link #onDetachedFromWindow()} when the container is done. 8347 */ 8348 public void onStartTemporaryDetach() { 8349 removeUnsetPressCallback(); 8350 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8351 } 8352 8353 /** 8354 * @hide 8355 */ 8356 public void dispatchFinishTemporaryDetach() { 8357 onFinishTemporaryDetach(); 8358 } 8359 8360 /** 8361 * Called after {@link #onStartTemporaryDetach} when the container is done 8362 * changing the view. 8363 */ 8364 public void onFinishTemporaryDetach() { 8365 } 8366 8367 /** 8368 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8369 * for this view's window. Returns null if the view is not currently attached 8370 * to the window. Normally you will not need to use this directly, but 8371 * just use the standard high-level event callbacks like 8372 * {@link #onKeyDown(int, KeyEvent)}. 8373 */ 8374 public KeyEvent.DispatcherState getKeyDispatcherState() { 8375 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8376 } 8377 8378 /** 8379 * Dispatch a key event before it is processed by any input method 8380 * associated with the view hierarchy. This can be used to intercept 8381 * key events in special situations before the IME consumes them; a 8382 * typical example would be handling the BACK key to update the application's 8383 * UI instead of allowing the IME to see it and close itself. 8384 * 8385 * @param event The key event to be dispatched. 8386 * @return True if the event was handled, false otherwise. 8387 */ 8388 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8389 return onKeyPreIme(event.getKeyCode(), event); 8390 } 8391 8392 /** 8393 * Dispatch a key event to the next view on the focus path. This path runs 8394 * from the top of the view tree down to the currently focused view. If this 8395 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8396 * the next node down the focus path. This method also fires any key 8397 * listeners. 8398 * 8399 * @param event The key event to be dispatched. 8400 * @return True if the event was handled, false otherwise. 8401 */ 8402 public boolean dispatchKeyEvent(KeyEvent event) { 8403 if (mInputEventConsistencyVerifier != null) { 8404 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8405 } 8406 8407 // Give any attached key listener a first crack at the event. 8408 //noinspection SimplifiableIfStatement 8409 ListenerInfo li = mListenerInfo; 8410 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8411 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8412 return true; 8413 } 8414 8415 if (event.dispatch(this, mAttachInfo != null 8416 ? mAttachInfo.mKeyDispatchState : null, this)) { 8417 return true; 8418 } 8419 8420 if (mInputEventConsistencyVerifier != null) { 8421 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8422 } 8423 return false; 8424 } 8425 8426 /** 8427 * Dispatches a key shortcut event. 8428 * 8429 * @param event The key event to be dispatched. 8430 * @return True if the event was handled by the view, false otherwise. 8431 */ 8432 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8433 return onKeyShortcut(event.getKeyCode(), event); 8434 } 8435 8436 /** 8437 * Pass the touch screen motion event down to the target view, or this 8438 * view if it is the target. 8439 * 8440 * @param event The motion event to be dispatched. 8441 * @return True if the event was handled by the view, false otherwise. 8442 */ 8443 public boolean dispatchTouchEvent(MotionEvent event) { 8444 // If the event should be handled by accessibility focus first. 8445 if (event.isTargetAccessibilityFocus()) { 8446 // We don't have focus or no virtual descendant has it, do not handle the event. 8447 if (!isAccessibilityFocused() && !(getViewRootImpl() != null && getViewRootImpl() 8448 .getAccessibilityFocusedHost() == this)) { 8449 return false; 8450 } 8451 // We have focus and got the event, then use normal event dispatch. 8452 event.setTargetAccessibilityFocus(false); 8453 } 8454 8455 boolean result = false; 8456 8457 if (mInputEventConsistencyVerifier != null) { 8458 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8459 } 8460 8461 final int actionMasked = event.getActionMasked(); 8462 if (actionMasked == MotionEvent.ACTION_DOWN) { 8463 // Defensive cleanup for new gesture 8464 stopNestedScroll(); 8465 } 8466 8467 if (onFilterTouchEventForSecurity(event)) { 8468 //noinspection SimplifiableIfStatement 8469 ListenerInfo li = mListenerInfo; 8470 if (li != null && li.mOnTouchListener != null 8471 && (mViewFlags & ENABLED_MASK) == ENABLED 8472 && li.mOnTouchListener.onTouch(this, event)) { 8473 result = true; 8474 } 8475 8476 if (!result && onTouchEvent(event)) { 8477 result = true; 8478 } 8479 } 8480 8481 if (!result && mInputEventConsistencyVerifier != null) { 8482 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8483 } 8484 8485 // Clean up after nested scrolls if this is the end of a gesture; 8486 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8487 // of the gesture. 8488 if (actionMasked == MotionEvent.ACTION_UP || 8489 actionMasked == MotionEvent.ACTION_CANCEL || 8490 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8491 stopNestedScroll(); 8492 } 8493 8494 return result; 8495 } 8496 8497 /** 8498 * Filter the touch event to apply security policies. 8499 * 8500 * @param event The motion event to be filtered. 8501 * @return True if the event should be dispatched, false if the event should be dropped. 8502 * 8503 * @see #getFilterTouchesWhenObscured 8504 */ 8505 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8506 //noinspection RedundantIfStatement 8507 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8508 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8509 // Window is obscured, drop this touch. 8510 return false; 8511 } 8512 return true; 8513 } 8514 8515 /** 8516 * Pass a trackball motion event down to the focused view. 8517 * 8518 * @param event The motion event to be dispatched. 8519 * @return True if the event was handled by the view, false otherwise. 8520 */ 8521 public boolean dispatchTrackballEvent(MotionEvent event) { 8522 if (mInputEventConsistencyVerifier != null) { 8523 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8524 } 8525 8526 return onTrackballEvent(event); 8527 } 8528 8529 /** 8530 * Dispatch a generic motion event. 8531 * <p> 8532 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8533 * are delivered to the view under the pointer. All other generic motion events are 8534 * delivered to the focused view. Hover events are handled specially and are delivered 8535 * to {@link #onHoverEvent(MotionEvent)}. 8536 * </p> 8537 * 8538 * @param event The motion event to be dispatched. 8539 * @return True if the event was handled by the view, false otherwise. 8540 */ 8541 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8542 if (mInputEventConsistencyVerifier != null) { 8543 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8544 } 8545 8546 final int source = event.getSource(); 8547 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8548 final int action = event.getAction(); 8549 if (action == MotionEvent.ACTION_HOVER_ENTER 8550 || action == MotionEvent.ACTION_HOVER_MOVE 8551 || action == MotionEvent.ACTION_HOVER_EXIT) { 8552 if (dispatchHoverEvent(event)) { 8553 return true; 8554 } 8555 } else if (dispatchGenericPointerEvent(event)) { 8556 return true; 8557 } 8558 } else if (dispatchGenericFocusedEvent(event)) { 8559 return true; 8560 } 8561 8562 if (dispatchGenericMotionEventInternal(event)) { 8563 return true; 8564 } 8565 8566 if (mInputEventConsistencyVerifier != null) { 8567 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8568 } 8569 return false; 8570 } 8571 8572 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8573 //noinspection SimplifiableIfStatement 8574 ListenerInfo li = mListenerInfo; 8575 if (li != null && li.mOnGenericMotionListener != null 8576 && (mViewFlags & ENABLED_MASK) == ENABLED 8577 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8578 return true; 8579 } 8580 8581 if (onGenericMotionEvent(event)) { 8582 return true; 8583 } 8584 8585 if (mInputEventConsistencyVerifier != null) { 8586 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8587 } 8588 return false; 8589 } 8590 8591 /** 8592 * Dispatch a hover event. 8593 * <p> 8594 * Do not call this method directly. 8595 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8596 * </p> 8597 * 8598 * @param event The motion event to be dispatched. 8599 * @return True if the event was handled by the view, false otherwise. 8600 */ 8601 protected boolean dispatchHoverEvent(MotionEvent event) { 8602 ListenerInfo li = mListenerInfo; 8603 //noinspection SimplifiableIfStatement 8604 if (li != null && li.mOnHoverListener != null 8605 && (mViewFlags & ENABLED_MASK) == ENABLED 8606 && li.mOnHoverListener.onHover(this, event)) { 8607 return true; 8608 } 8609 8610 return onHoverEvent(event); 8611 } 8612 8613 /** 8614 * Returns true if the view has a child to which it has recently sent 8615 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8616 * it does not have a hovered child, then it must be the innermost hovered view. 8617 * @hide 8618 */ 8619 protected boolean hasHoveredChild() { 8620 return false; 8621 } 8622 8623 /** 8624 * Dispatch a generic motion event to the view under the first pointer. 8625 * <p> 8626 * Do not call this method directly. 8627 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8628 * </p> 8629 * 8630 * @param event The motion event to be dispatched. 8631 * @return True if the event was handled by the view, false otherwise. 8632 */ 8633 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8634 return false; 8635 } 8636 8637 /** 8638 * Dispatch a generic motion event to the currently focused view. 8639 * <p> 8640 * Do not call this method directly. 8641 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8642 * </p> 8643 * 8644 * @param event The motion event to be dispatched. 8645 * @return True if the event was handled by the view, false otherwise. 8646 */ 8647 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8648 return false; 8649 } 8650 8651 /** 8652 * Dispatch a pointer event. 8653 * <p> 8654 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8655 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8656 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8657 * and should not be expected to handle other pointing device features. 8658 * </p> 8659 * 8660 * @param event The motion event to be dispatched. 8661 * @return True if the event was handled by the view, false otherwise. 8662 * @hide 8663 */ 8664 public final boolean dispatchPointerEvent(MotionEvent event) { 8665 if (event.isTouchEvent()) { 8666 return dispatchTouchEvent(event); 8667 } else { 8668 return dispatchGenericMotionEvent(event); 8669 } 8670 } 8671 8672 /** 8673 * Called when the window containing this view gains or loses window focus. 8674 * ViewGroups should override to route to their children. 8675 * 8676 * @param hasFocus True if the window containing this view now has focus, 8677 * false otherwise. 8678 */ 8679 public void dispatchWindowFocusChanged(boolean hasFocus) { 8680 onWindowFocusChanged(hasFocus); 8681 } 8682 8683 /** 8684 * Called when the window containing this view gains or loses focus. Note 8685 * that this is separate from view focus: to receive key events, both 8686 * your view and its window must have focus. If a window is displayed 8687 * on top of yours that takes input focus, then your own window will lose 8688 * focus but the view focus will remain unchanged. 8689 * 8690 * @param hasWindowFocus True if the window containing this view now has 8691 * focus, false otherwise. 8692 */ 8693 public void onWindowFocusChanged(boolean hasWindowFocus) { 8694 InputMethodManager imm = InputMethodManager.peekInstance(); 8695 if (!hasWindowFocus) { 8696 if (isPressed()) { 8697 setPressed(false); 8698 } 8699 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8700 imm.focusOut(this); 8701 } 8702 removeLongPressCallback(); 8703 removeTapCallback(); 8704 onFocusLost(); 8705 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8706 imm.focusIn(this); 8707 } 8708 refreshDrawableState(); 8709 } 8710 8711 /** 8712 * Returns true if this view is in a window that currently has window focus. 8713 * Note that this is not the same as the view itself having focus. 8714 * 8715 * @return True if this view is in a window that currently has window focus. 8716 */ 8717 public boolean hasWindowFocus() { 8718 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8719 } 8720 8721 /** 8722 * Dispatch a view visibility change down the view hierarchy. 8723 * ViewGroups should override to route to their children. 8724 * @param changedView The view whose visibility changed. Could be 'this' or 8725 * an ancestor view. 8726 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8727 * {@link #INVISIBLE} or {@link #GONE}. 8728 */ 8729 protected void dispatchVisibilityChanged(@NonNull View changedView, 8730 @Visibility int visibility) { 8731 onVisibilityChanged(changedView, visibility); 8732 } 8733 8734 /** 8735 * Called when the visibility of the view or an ancestor of the view has 8736 * changed. 8737 * 8738 * @param changedView The view whose visibility changed. May be 8739 * {@code this} or an ancestor view. 8740 * @param visibility The new visibility, one of {@link #VISIBLE}, 8741 * {@link #INVISIBLE} or {@link #GONE}. 8742 */ 8743 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8744 final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE; 8745 if (visible) { 8746 if (mAttachInfo != null) { 8747 initialAwakenScrollBars(); 8748 } else { 8749 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8750 } 8751 } 8752 8753 final Drawable dr = mBackground; 8754 if (dr != null && visible != dr.isVisible()) { 8755 dr.setVisible(visible, false); 8756 } 8757 } 8758 8759 /** 8760 * Dispatch a hint about whether this view is displayed. For instance, when 8761 * a View moves out of the screen, it might receives a display hint indicating 8762 * the view is not displayed. Applications should not <em>rely</em> on this hint 8763 * as there is no guarantee that they will receive one. 8764 * 8765 * @param hint A hint about whether or not this view is displayed: 8766 * {@link #VISIBLE} or {@link #INVISIBLE}. 8767 */ 8768 public void dispatchDisplayHint(@Visibility int hint) { 8769 onDisplayHint(hint); 8770 } 8771 8772 /** 8773 * Gives this view a hint about whether is displayed or not. For instance, when 8774 * a View moves out of the screen, it might receives a display hint indicating 8775 * the view is not displayed. Applications should not <em>rely</em> on this hint 8776 * as there is no guarantee that they will receive one. 8777 * 8778 * @param hint A hint about whether or not this view is displayed: 8779 * {@link #VISIBLE} or {@link #INVISIBLE}. 8780 */ 8781 protected void onDisplayHint(@Visibility int hint) { 8782 } 8783 8784 /** 8785 * Dispatch a window visibility change down the view hierarchy. 8786 * ViewGroups should override to route to their children. 8787 * 8788 * @param visibility The new visibility of the window. 8789 * 8790 * @see #onWindowVisibilityChanged(int) 8791 */ 8792 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8793 onWindowVisibilityChanged(visibility); 8794 } 8795 8796 /** 8797 * Called when the window containing has change its visibility 8798 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8799 * that this tells you whether or not your window is being made visible 8800 * to the window manager; this does <em>not</em> tell you whether or not 8801 * your window is obscured by other windows on the screen, even if it 8802 * is itself visible. 8803 * 8804 * @param visibility The new visibility of the window. 8805 */ 8806 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8807 if (visibility == VISIBLE) { 8808 initialAwakenScrollBars(); 8809 } 8810 } 8811 8812 /** 8813 * Returns the current visibility of the window this view is attached to 8814 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8815 * 8816 * @return Returns the current visibility of the view's window. 8817 */ 8818 @Visibility 8819 public int getWindowVisibility() { 8820 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8821 } 8822 8823 /** 8824 * Retrieve the overall visible display size in which the window this view is 8825 * attached to has been positioned in. This takes into account screen 8826 * decorations above the window, for both cases where the window itself 8827 * is being position inside of them or the window is being placed under 8828 * then and covered insets are used for the window to position its content 8829 * inside. In effect, this tells you the available area where content can 8830 * be placed and remain visible to users. 8831 * 8832 * <p>This function requires an IPC back to the window manager to retrieve 8833 * the requested information, so should not be used in performance critical 8834 * code like drawing. 8835 * 8836 * @param outRect Filled in with the visible display frame. If the view 8837 * is not attached to a window, this is simply the raw display size. 8838 */ 8839 public void getWindowVisibleDisplayFrame(Rect outRect) { 8840 if (mAttachInfo != null) { 8841 try { 8842 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8843 } catch (RemoteException e) { 8844 return; 8845 } 8846 // XXX This is really broken, and probably all needs to be done 8847 // in the window manager, and we need to know more about whether 8848 // we want the area behind or in front of the IME. 8849 final Rect insets = mAttachInfo.mVisibleInsets; 8850 outRect.left += insets.left; 8851 outRect.top += insets.top; 8852 outRect.right -= insets.right; 8853 outRect.bottom -= insets.bottom; 8854 return; 8855 } 8856 // The view is not attached to a display so we don't have a context. 8857 // Make a best guess about the display size. 8858 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8859 d.getRectSize(outRect); 8860 } 8861 8862 /** 8863 * Dispatch a notification about a resource configuration change down 8864 * the view hierarchy. 8865 * ViewGroups should override to route to their children. 8866 * 8867 * @param newConfig The new resource configuration. 8868 * 8869 * @see #onConfigurationChanged(android.content.res.Configuration) 8870 */ 8871 public void dispatchConfigurationChanged(Configuration newConfig) { 8872 onConfigurationChanged(newConfig); 8873 } 8874 8875 /** 8876 * Called when the current configuration of the resources being used 8877 * by the application have changed. You can use this to decide when 8878 * to reload resources that can changed based on orientation and other 8879 * configuration characteristics. You only need to use this if you are 8880 * not relying on the normal {@link android.app.Activity} mechanism of 8881 * recreating the activity instance upon a configuration change. 8882 * 8883 * @param newConfig The new resource configuration. 8884 */ 8885 protected void onConfigurationChanged(Configuration newConfig) { 8886 } 8887 8888 /** 8889 * Private function to aggregate all per-view attributes in to the view 8890 * root. 8891 */ 8892 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8893 performCollectViewAttributes(attachInfo, visibility); 8894 } 8895 8896 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8897 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8898 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8899 attachInfo.mKeepScreenOn = true; 8900 } 8901 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8902 ListenerInfo li = mListenerInfo; 8903 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8904 attachInfo.mHasSystemUiListeners = true; 8905 } 8906 } 8907 } 8908 8909 void needGlobalAttributesUpdate(boolean force) { 8910 final AttachInfo ai = mAttachInfo; 8911 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8912 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8913 || ai.mHasSystemUiListeners) { 8914 ai.mRecomputeGlobalAttributes = true; 8915 } 8916 } 8917 } 8918 8919 /** 8920 * Returns whether the device is currently in touch mode. Touch mode is entered 8921 * once the user begins interacting with the device by touch, and affects various 8922 * things like whether focus is always visible to the user. 8923 * 8924 * @return Whether the device is in touch mode. 8925 */ 8926 @ViewDebug.ExportedProperty 8927 public boolean isInTouchMode() { 8928 if (mAttachInfo != null) { 8929 return mAttachInfo.mInTouchMode; 8930 } else { 8931 return ViewRootImpl.isInTouchMode(); 8932 } 8933 } 8934 8935 /** 8936 * Returns the context the view is running in, through which it can 8937 * access the current theme, resources, etc. 8938 * 8939 * @return The view's Context. 8940 */ 8941 @ViewDebug.CapturedViewProperty 8942 public final Context getContext() { 8943 return mContext; 8944 } 8945 8946 /** 8947 * Handle a key event before it is processed by any input method 8948 * associated with the view hierarchy. This can be used to intercept 8949 * key events in special situations before the IME consumes them; a 8950 * typical example would be handling the BACK key to update the application's 8951 * UI instead of allowing the IME to see it and close itself. 8952 * 8953 * @param keyCode The value in event.getKeyCode(). 8954 * @param event Description of the key event. 8955 * @return If you handled the event, return true. If you want to allow the 8956 * event to be handled by the next receiver, return false. 8957 */ 8958 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8959 return false; 8960 } 8961 8962 /** 8963 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8964 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8965 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8966 * is released, if the view is enabled and clickable. 8967 * 8968 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8969 * although some may elect to do so in some situations. Do not rely on this to 8970 * catch software key presses. 8971 * 8972 * @param keyCode A key code that represents the button pressed, from 8973 * {@link android.view.KeyEvent}. 8974 * @param event The KeyEvent object that defines the button action. 8975 */ 8976 public boolean onKeyDown(int keyCode, KeyEvent event) { 8977 boolean result = false; 8978 8979 if (KeyEvent.isConfirmKey(keyCode)) { 8980 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8981 return true; 8982 } 8983 // Long clickable items don't necessarily have to be clickable 8984 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8985 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8986 (event.getRepeatCount() == 0)) { 8987 setPressed(true); 8988 checkForLongClick(0); 8989 return true; 8990 } 8991 } 8992 return result; 8993 } 8994 8995 /** 8996 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8997 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8998 * the event). 8999 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9000 * although some may elect to do so in some situations. Do not rely on this to 9001 * catch software key presses. 9002 */ 9003 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 9004 return false; 9005 } 9006 9007 /** 9008 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 9009 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 9010 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 9011 * {@link KeyEvent#KEYCODE_ENTER} is released. 9012 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9013 * although some may elect to do so in some situations. Do not rely on this to 9014 * catch software key presses. 9015 * 9016 * @param keyCode A key code that represents the button pressed, from 9017 * {@link android.view.KeyEvent}. 9018 * @param event The KeyEvent object that defines the button action. 9019 */ 9020 public boolean onKeyUp(int keyCode, KeyEvent event) { 9021 if (KeyEvent.isConfirmKey(keyCode)) { 9022 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9023 return true; 9024 } 9025 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 9026 setPressed(false); 9027 9028 if (!mHasPerformedLongPress) { 9029 // This is a tap, so remove the longpress check 9030 removeLongPressCallback(); 9031 return performClick(); 9032 } 9033 } 9034 } 9035 return false; 9036 } 9037 9038 /** 9039 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 9040 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 9041 * the event). 9042 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9043 * although some may elect to do so in some situations. Do not rely on this to 9044 * catch software key presses. 9045 * 9046 * @param keyCode A key code that represents the button pressed, from 9047 * {@link android.view.KeyEvent}. 9048 * @param repeatCount The number of times the action was made. 9049 * @param event The KeyEvent object that defines the button action. 9050 */ 9051 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 9052 return false; 9053 } 9054 9055 /** 9056 * Called on the focused view when a key shortcut event is not handled. 9057 * Override this method to implement local key shortcuts for the View. 9058 * Key shortcuts can also be implemented by setting the 9059 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 9060 * 9061 * @param keyCode The value in event.getKeyCode(). 9062 * @param event Description of the key event. 9063 * @return If you handled the event, return true. If you want to allow the 9064 * event to be handled by the next receiver, return false. 9065 */ 9066 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 9067 return false; 9068 } 9069 9070 /** 9071 * Check whether the called view is a text editor, in which case it 9072 * would make sense to automatically display a soft input window for 9073 * it. Subclasses should override this if they implement 9074 * {@link #onCreateInputConnection(EditorInfo)} to return true if 9075 * a call on that method would return a non-null InputConnection, and 9076 * they are really a first-class editor that the user would normally 9077 * start typing on when the go into a window containing your view. 9078 * 9079 * <p>The default implementation always returns false. This does 9080 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 9081 * will not be called or the user can not otherwise perform edits on your 9082 * view; it is just a hint to the system that this is not the primary 9083 * purpose of this view. 9084 * 9085 * @return Returns true if this view is a text editor, else false. 9086 */ 9087 public boolean onCheckIsTextEditor() { 9088 return false; 9089 } 9090 9091 /** 9092 * Create a new InputConnection for an InputMethod to interact 9093 * with the view. The default implementation returns null, since it doesn't 9094 * support input methods. You can override this to implement such support. 9095 * This is only needed for views that take focus and text input. 9096 * 9097 * <p>When implementing this, you probably also want to implement 9098 * {@link #onCheckIsTextEditor()} to indicate you will return a 9099 * non-null InputConnection.</p> 9100 * 9101 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9102 * object correctly and in its entirety, so that the connected IME can rely 9103 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9104 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9105 * must be filled in with the correct cursor position for IMEs to work correctly 9106 * with your application.</p> 9107 * 9108 * @param outAttrs Fill in with attribute information about the connection. 9109 */ 9110 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9111 return null; 9112 } 9113 9114 /** 9115 * Called by the {@link android.view.inputmethod.InputMethodManager} 9116 * when a view who is not the current 9117 * input connection target is trying to make a call on the manager. The 9118 * default implementation returns false; you can override this to return 9119 * true for certain views if you are performing InputConnection proxying 9120 * to them. 9121 * @param view The View that is making the InputMethodManager call. 9122 * @return Return true to allow the call, false to reject. 9123 */ 9124 public boolean checkInputConnectionProxy(View view) { 9125 return false; 9126 } 9127 9128 /** 9129 * Show the context menu for this view. It is not safe to hold on to the 9130 * menu after returning from this method. 9131 * 9132 * You should normally not overload this method. Overload 9133 * {@link #onCreateContextMenu(ContextMenu)} or define an 9134 * {@link OnCreateContextMenuListener} to add items to the context menu. 9135 * 9136 * @param menu The context menu to populate 9137 */ 9138 public void createContextMenu(ContextMenu menu) { 9139 ContextMenuInfo menuInfo = getContextMenuInfo(); 9140 9141 // Sets the current menu info so all items added to menu will have 9142 // my extra info set. 9143 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9144 9145 onCreateContextMenu(menu); 9146 ListenerInfo li = mListenerInfo; 9147 if (li != null && li.mOnCreateContextMenuListener != null) { 9148 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9149 } 9150 9151 // Clear the extra information so subsequent items that aren't mine don't 9152 // have my extra info. 9153 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9154 9155 if (mParent != null) { 9156 mParent.createContextMenu(menu); 9157 } 9158 } 9159 9160 /** 9161 * Views should implement this if they have extra information to associate 9162 * with the context menu. The return result is supplied as a parameter to 9163 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9164 * callback. 9165 * 9166 * @return Extra information about the item for which the context menu 9167 * should be shown. This information will vary across different 9168 * subclasses of View. 9169 */ 9170 protected ContextMenuInfo getContextMenuInfo() { 9171 return null; 9172 } 9173 9174 /** 9175 * Views should implement this if the view itself is going to add items to 9176 * the context menu. 9177 * 9178 * @param menu the context menu to populate 9179 */ 9180 protected void onCreateContextMenu(ContextMenu menu) { 9181 } 9182 9183 /** 9184 * Implement this method to handle trackball motion events. The 9185 * <em>relative</em> movement of the trackball since the last event 9186 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9187 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9188 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9189 * they will often be fractional values, representing the more fine-grained 9190 * movement information available from a trackball). 9191 * 9192 * @param event The motion event. 9193 * @return True if the event was handled, false otherwise. 9194 */ 9195 public boolean onTrackballEvent(MotionEvent event) { 9196 return false; 9197 } 9198 9199 /** 9200 * Implement this method to handle generic motion events. 9201 * <p> 9202 * Generic motion events describe joystick movements, mouse hovers, track pad 9203 * touches, scroll wheel movements and other input events. The 9204 * {@link MotionEvent#getSource() source} of the motion event specifies 9205 * the class of input that was received. Implementations of this method 9206 * must examine the bits in the source before processing the event. 9207 * The following code example shows how this is done. 9208 * </p><p> 9209 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9210 * are delivered to the view under the pointer. All other generic motion events are 9211 * delivered to the focused view. 9212 * </p> 9213 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9214 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9215 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9216 * // process the joystick movement... 9217 * return true; 9218 * } 9219 * } 9220 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9221 * switch (event.getAction()) { 9222 * case MotionEvent.ACTION_HOVER_MOVE: 9223 * // process the mouse hover movement... 9224 * return true; 9225 * case MotionEvent.ACTION_SCROLL: 9226 * // process the scroll wheel movement... 9227 * return true; 9228 * } 9229 * } 9230 * return super.onGenericMotionEvent(event); 9231 * }</pre> 9232 * 9233 * @param event The generic motion event being processed. 9234 * @return True if the event was handled, false otherwise. 9235 */ 9236 public boolean onGenericMotionEvent(MotionEvent event) { 9237 return false; 9238 } 9239 9240 /** 9241 * Implement this method to handle hover events. 9242 * <p> 9243 * This method is called whenever a pointer is hovering into, over, or out of the 9244 * bounds of a view and the view is not currently being touched. 9245 * Hover events are represented as pointer events with action 9246 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 9247 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 9248 * </p> 9249 * <ul> 9250 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 9251 * when the pointer enters the bounds of the view.</li> 9252 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 9253 * when the pointer has already entered the bounds of the view and has moved.</li> 9254 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 9255 * when the pointer has exited the bounds of the view or when the pointer is 9256 * about to go down due to a button click, tap, or similar user action that 9257 * causes the view to be touched.</li> 9258 * </ul> 9259 * <p> 9260 * The view should implement this method to return true to indicate that it is 9261 * handling the hover event, such as by changing its drawable state. 9262 * </p><p> 9263 * The default implementation calls {@link #setHovered} to update the hovered state 9264 * of the view when a hover enter or hover exit event is received, if the view 9265 * is enabled and is clickable. The default implementation also sends hover 9266 * accessibility events. 9267 * </p> 9268 * 9269 * @param event The motion event that describes the hover. 9270 * @return True if the view handled the hover event. 9271 * 9272 * @see #isHovered 9273 * @see #setHovered 9274 * @see #onHoverChanged 9275 */ 9276 public boolean onHoverEvent(MotionEvent event) { 9277 // The root view may receive hover (or touch) events that are outside the bounds of 9278 // the window. This code ensures that we only send accessibility events for 9279 // hovers that are actually within the bounds of the root view. 9280 final int action = event.getActionMasked(); 9281 if (!mSendingHoverAccessibilityEvents) { 9282 if ((action == MotionEvent.ACTION_HOVER_ENTER 9283 || action == MotionEvent.ACTION_HOVER_MOVE) 9284 && !hasHoveredChild() 9285 && pointInView(event.getX(), event.getY())) { 9286 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 9287 mSendingHoverAccessibilityEvents = true; 9288 } 9289 } else { 9290 if (action == MotionEvent.ACTION_HOVER_EXIT 9291 || (action == MotionEvent.ACTION_MOVE 9292 && !pointInView(event.getX(), event.getY()))) { 9293 mSendingHoverAccessibilityEvents = false; 9294 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 9295 } 9296 } 9297 9298 if (isHoverable()) { 9299 switch (action) { 9300 case MotionEvent.ACTION_HOVER_ENTER: 9301 setHovered(true); 9302 break; 9303 case MotionEvent.ACTION_HOVER_EXIT: 9304 setHovered(false); 9305 break; 9306 } 9307 9308 // Dispatch the event to onGenericMotionEvent before returning true. 9309 // This is to provide compatibility with existing applications that 9310 // handled HOVER_MOVE events in onGenericMotionEvent and that would 9311 // break because of the new default handling for hoverable views 9312 // in onHoverEvent. 9313 // Note that onGenericMotionEvent will be called by default when 9314 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 9315 dispatchGenericMotionEventInternal(event); 9316 // The event was already handled by calling setHovered(), so always 9317 // return true. 9318 return true; 9319 } 9320 9321 return false; 9322 } 9323 9324 /** 9325 * Returns true if the view should handle {@link #onHoverEvent} 9326 * by calling {@link #setHovered} to change its hovered state. 9327 * 9328 * @return True if the view is hoverable. 9329 */ 9330 private boolean isHoverable() { 9331 final int viewFlags = mViewFlags; 9332 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9333 return false; 9334 } 9335 9336 return (viewFlags & CLICKABLE) == CLICKABLE 9337 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9338 } 9339 9340 /** 9341 * Returns true if the view is currently hovered. 9342 * 9343 * @return True if the view is currently hovered. 9344 * 9345 * @see #setHovered 9346 * @see #onHoverChanged 9347 */ 9348 @ViewDebug.ExportedProperty 9349 public boolean isHovered() { 9350 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9351 } 9352 9353 /** 9354 * Sets whether the view is currently hovered. 9355 * <p> 9356 * Calling this method also changes the drawable state of the view. This 9357 * enables the view to react to hover by using different drawable resources 9358 * to change its appearance. 9359 * </p><p> 9360 * The {@link #onHoverChanged} method is called when the hovered state changes. 9361 * </p> 9362 * 9363 * @param hovered True if the view is hovered. 9364 * 9365 * @see #isHovered 9366 * @see #onHoverChanged 9367 */ 9368 public void setHovered(boolean hovered) { 9369 if (hovered) { 9370 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9371 mPrivateFlags |= PFLAG_HOVERED; 9372 refreshDrawableState(); 9373 onHoverChanged(true); 9374 } 9375 } else { 9376 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9377 mPrivateFlags &= ~PFLAG_HOVERED; 9378 refreshDrawableState(); 9379 onHoverChanged(false); 9380 } 9381 } 9382 } 9383 9384 /** 9385 * Implement this method to handle hover state changes. 9386 * <p> 9387 * This method is called whenever the hover state changes as a result of a 9388 * call to {@link #setHovered}. 9389 * </p> 9390 * 9391 * @param hovered The current hover state, as returned by {@link #isHovered}. 9392 * 9393 * @see #isHovered 9394 * @see #setHovered 9395 */ 9396 public void onHoverChanged(boolean hovered) { 9397 } 9398 9399 /** 9400 * Implement this method to handle touch screen motion events. 9401 * <p> 9402 * If this method is used to detect click actions, it is recommended that 9403 * the actions be performed by implementing and calling 9404 * {@link #performClick()}. This will ensure consistent system behavior, 9405 * including: 9406 * <ul> 9407 * <li>obeying click sound preferences 9408 * <li>dispatching OnClickListener calls 9409 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9410 * accessibility features are enabled 9411 * </ul> 9412 * 9413 * @param event The motion event. 9414 * @return True if the event was handled, false otherwise. 9415 */ 9416 public boolean onTouchEvent(MotionEvent event) { 9417 final float x = event.getX(); 9418 final float y = event.getY(); 9419 final int viewFlags = mViewFlags; 9420 9421 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9422 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9423 setPressed(false); 9424 } 9425 // A disabled view that is clickable still consumes the touch 9426 // events, it just doesn't respond to them. 9427 return (((viewFlags & CLICKABLE) == CLICKABLE || 9428 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9429 } 9430 9431 if (mTouchDelegate != null) { 9432 if (mTouchDelegate.onTouchEvent(event)) { 9433 return true; 9434 } 9435 } 9436 9437 if (((viewFlags & CLICKABLE) == CLICKABLE || 9438 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9439 switch (event.getAction()) { 9440 case MotionEvent.ACTION_UP: 9441 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9442 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9443 // take focus if we don't have it already and we should in 9444 // touch mode. 9445 boolean focusTaken = false; 9446 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9447 focusTaken = requestFocus(); 9448 } 9449 9450 if (prepressed) { 9451 // The button is being released before we actually 9452 // showed it as pressed. Make it show the pressed 9453 // state now (before scheduling the click) to ensure 9454 // the user sees it. 9455 setPressed(true, x, y); 9456 } 9457 9458 if (!mHasPerformedLongPress) { 9459 // This is a tap, so remove the longpress check 9460 removeLongPressCallback(); 9461 9462 // Only perform take click actions if we were in the pressed state 9463 if (!focusTaken) { 9464 // Use a Runnable and post this rather than calling 9465 // performClick directly. This lets other visual state 9466 // of the view update before click actions start. 9467 if (mPerformClick == null) { 9468 mPerformClick = new PerformClick(); 9469 } 9470 if (!post(mPerformClick)) { 9471 performClick(); 9472 } 9473 } 9474 } 9475 9476 if (mUnsetPressedState == null) { 9477 mUnsetPressedState = new UnsetPressedState(); 9478 } 9479 9480 if (prepressed) { 9481 postDelayed(mUnsetPressedState, 9482 ViewConfiguration.getPressedStateDuration()); 9483 } else if (!post(mUnsetPressedState)) { 9484 // If the post failed, unpress right now 9485 mUnsetPressedState.run(); 9486 } 9487 9488 removeTapCallback(); 9489 } 9490 break; 9491 9492 case MotionEvent.ACTION_DOWN: 9493 mHasPerformedLongPress = false; 9494 9495 if (performButtonActionOnTouchDown(event)) { 9496 break; 9497 } 9498 9499 // Walk up the hierarchy to determine if we're inside a scrolling container. 9500 boolean isInScrollingContainer = isInScrollingContainer(); 9501 9502 // For views inside a scrolling container, delay the pressed feedback for 9503 // a short period in case this is a scroll. 9504 if (isInScrollingContainer) { 9505 mPrivateFlags |= PFLAG_PREPRESSED; 9506 if (mPendingCheckForTap == null) { 9507 mPendingCheckForTap = new CheckForTap(); 9508 } 9509 mPendingCheckForTap.x = event.getX(); 9510 mPendingCheckForTap.y = event.getY(); 9511 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9512 } else { 9513 // Not inside a scrolling container, so show the feedback right away 9514 setPressed(true, x, y); 9515 checkForLongClick(0); 9516 } 9517 break; 9518 9519 case MotionEvent.ACTION_CANCEL: 9520 setPressed(false); 9521 removeTapCallback(); 9522 removeLongPressCallback(); 9523 break; 9524 9525 case MotionEvent.ACTION_MOVE: 9526 drawableHotspotChanged(x, y); 9527 9528 // Be lenient about moving outside of buttons 9529 if (!pointInView(x, y, mTouchSlop)) { 9530 // Outside button 9531 removeTapCallback(); 9532 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9533 // Remove any future long press/tap checks 9534 removeLongPressCallback(); 9535 9536 setPressed(false); 9537 } 9538 } 9539 break; 9540 } 9541 9542 return true; 9543 } 9544 9545 return false; 9546 } 9547 9548 /** 9549 * @hide 9550 */ 9551 public boolean isInScrollingContainer() { 9552 ViewParent p = getParent(); 9553 while (p != null && p instanceof ViewGroup) { 9554 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9555 return true; 9556 } 9557 p = p.getParent(); 9558 } 9559 return false; 9560 } 9561 9562 /** 9563 * Remove the longpress detection timer. 9564 */ 9565 private void removeLongPressCallback() { 9566 if (mPendingCheckForLongPress != null) { 9567 removeCallbacks(mPendingCheckForLongPress); 9568 } 9569 } 9570 9571 /** 9572 * Remove the pending click action 9573 */ 9574 private void removePerformClickCallback() { 9575 if (mPerformClick != null) { 9576 removeCallbacks(mPerformClick); 9577 } 9578 } 9579 9580 /** 9581 * Remove the prepress detection timer. 9582 */ 9583 private void removeUnsetPressCallback() { 9584 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9585 setPressed(false); 9586 removeCallbacks(mUnsetPressedState); 9587 } 9588 } 9589 9590 /** 9591 * Remove the tap detection timer. 9592 */ 9593 private void removeTapCallback() { 9594 if (mPendingCheckForTap != null) { 9595 mPrivateFlags &= ~PFLAG_PREPRESSED; 9596 removeCallbacks(mPendingCheckForTap); 9597 } 9598 } 9599 9600 /** 9601 * Cancels a pending long press. Your subclass can use this if you 9602 * want the context menu to come up if the user presses and holds 9603 * at the same place, but you don't want it to come up if they press 9604 * and then move around enough to cause scrolling. 9605 */ 9606 public void cancelLongPress() { 9607 removeLongPressCallback(); 9608 9609 /* 9610 * The prepressed state handled by the tap callback is a display 9611 * construct, but the tap callback will post a long press callback 9612 * less its own timeout. Remove it here. 9613 */ 9614 removeTapCallback(); 9615 } 9616 9617 /** 9618 * Remove the pending callback for sending a 9619 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9620 */ 9621 private void removeSendViewScrolledAccessibilityEventCallback() { 9622 if (mSendViewScrolledAccessibilityEvent != null) { 9623 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9624 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9625 } 9626 } 9627 9628 /** 9629 * Sets the TouchDelegate for this View. 9630 */ 9631 public void setTouchDelegate(TouchDelegate delegate) { 9632 mTouchDelegate = delegate; 9633 } 9634 9635 /** 9636 * Gets the TouchDelegate for this View. 9637 */ 9638 public TouchDelegate getTouchDelegate() { 9639 return mTouchDelegate; 9640 } 9641 9642 /** 9643 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9644 * 9645 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9646 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9647 * available. This method should only be called for touch events. 9648 * 9649 * <p class="note">This api is not intended for most applications. Buffered dispatch 9650 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9651 * streams will not improve your input latency. Side effects include: increased latency, 9652 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9653 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9654 * you.</p> 9655 */ 9656 public final void requestUnbufferedDispatch(MotionEvent event) { 9657 final int action = event.getAction(); 9658 if (mAttachInfo == null 9659 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9660 || !event.isTouchEvent()) { 9661 return; 9662 } 9663 mAttachInfo.mUnbufferedDispatchRequested = true; 9664 } 9665 9666 /** 9667 * Set flags controlling behavior of this view. 9668 * 9669 * @param flags Constant indicating the value which should be set 9670 * @param mask Constant indicating the bit range that should be changed 9671 */ 9672 void setFlags(int flags, int mask) { 9673 final boolean accessibilityEnabled = 9674 AccessibilityManager.getInstance(mContext).isEnabled(); 9675 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9676 9677 int old = mViewFlags; 9678 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9679 9680 int changed = mViewFlags ^ old; 9681 if (changed == 0) { 9682 return; 9683 } 9684 int privateFlags = mPrivateFlags; 9685 9686 /* Check if the FOCUSABLE bit has changed */ 9687 if (((changed & FOCUSABLE_MASK) != 0) && 9688 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9689 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9690 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9691 /* Give up focus if we are no longer focusable */ 9692 clearFocus(); 9693 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9694 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9695 /* 9696 * Tell the view system that we are now available to take focus 9697 * if no one else already has it. 9698 */ 9699 if (mParent != null) mParent.focusableViewAvailable(this); 9700 } 9701 } 9702 9703 final int newVisibility = flags & VISIBILITY_MASK; 9704 if (newVisibility == VISIBLE) { 9705 if ((changed & VISIBILITY_MASK) != 0) { 9706 /* 9707 * If this view is becoming visible, invalidate it in case it changed while 9708 * it was not visible. Marking it drawn ensures that the invalidation will 9709 * go through. 9710 */ 9711 mPrivateFlags |= PFLAG_DRAWN; 9712 invalidate(true); 9713 9714 needGlobalAttributesUpdate(true); 9715 9716 // a view becoming visible is worth notifying the parent 9717 // about in case nothing has focus. even if this specific view 9718 // isn't focusable, it may contain something that is, so let 9719 // the root view try to give this focus if nothing else does. 9720 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9721 mParent.focusableViewAvailable(this); 9722 } 9723 } 9724 } 9725 9726 /* Check if the GONE bit has changed */ 9727 if ((changed & GONE) != 0) { 9728 needGlobalAttributesUpdate(false); 9729 requestLayout(); 9730 9731 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9732 if (hasFocus()) clearFocus(); 9733 clearAccessibilityFocus(); 9734 destroyDrawingCache(); 9735 if (mParent instanceof View) { 9736 // GONE views noop invalidation, so invalidate the parent 9737 ((View) mParent).invalidate(true); 9738 } 9739 // Mark the view drawn to ensure that it gets invalidated properly the next 9740 // time it is visible and gets invalidated 9741 mPrivateFlags |= PFLAG_DRAWN; 9742 } 9743 if (mAttachInfo != null) { 9744 mAttachInfo.mViewVisibilityChanged = true; 9745 } 9746 } 9747 9748 /* Check if the VISIBLE bit has changed */ 9749 if ((changed & INVISIBLE) != 0) { 9750 needGlobalAttributesUpdate(false); 9751 /* 9752 * If this view is becoming invisible, set the DRAWN flag so that 9753 * the next invalidate() will not be skipped. 9754 */ 9755 mPrivateFlags |= PFLAG_DRAWN; 9756 9757 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9758 // root view becoming invisible shouldn't clear focus and accessibility focus 9759 if (getRootView() != this) { 9760 if (hasFocus()) clearFocus(); 9761 clearAccessibilityFocus(); 9762 } 9763 } 9764 if (mAttachInfo != null) { 9765 mAttachInfo.mViewVisibilityChanged = true; 9766 } 9767 } 9768 9769 if ((changed & VISIBILITY_MASK) != 0) { 9770 // If the view is invisible, cleanup its display list to free up resources 9771 if (newVisibility != VISIBLE && mAttachInfo != null) { 9772 cleanupDraw(); 9773 } 9774 9775 if (mParent instanceof ViewGroup) { 9776 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9777 (changed & VISIBILITY_MASK), newVisibility); 9778 ((View) mParent).invalidate(true); 9779 } else if (mParent != null) { 9780 mParent.invalidateChild(this, null); 9781 } 9782 dispatchVisibilityChanged(this, newVisibility); 9783 9784 notifySubtreeAccessibilityStateChangedIfNeeded(); 9785 } 9786 9787 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9788 destroyDrawingCache(); 9789 } 9790 9791 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9792 destroyDrawingCache(); 9793 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9794 invalidateParentCaches(); 9795 } 9796 9797 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9798 destroyDrawingCache(); 9799 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9800 } 9801 9802 if ((changed & DRAW_MASK) != 0) { 9803 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9804 if (mBackground != null) { 9805 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9806 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9807 } else { 9808 mPrivateFlags |= PFLAG_SKIP_DRAW; 9809 } 9810 } else { 9811 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9812 } 9813 requestLayout(); 9814 invalidate(true); 9815 } 9816 9817 if ((changed & KEEP_SCREEN_ON) != 0) { 9818 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9819 mParent.recomputeViewAttributes(this); 9820 } 9821 } 9822 9823 if (accessibilityEnabled) { 9824 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9825 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9826 if (oldIncludeForAccessibility != includeForAccessibility()) { 9827 notifySubtreeAccessibilityStateChangedIfNeeded(); 9828 } else { 9829 notifyViewAccessibilityStateChangedIfNeeded( 9830 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9831 } 9832 } else if ((changed & ENABLED_MASK) != 0) { 9833 notifyViewAccessibilityStateChangedIfNeeded( 9834 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9835 } 9836 } 9837 } 9838 9839 /** 9840 * Change the view's z order in the tree, so it's on top of other sibling 9841 * views. This ordering change may affect layout, if the parent container 9842 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9843 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9844 * method should be followed by calls to {@link #requestLayout()} and 9845 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9846 * with the new child ordering. 9847 * 9848 * @see ViewGroup#bringChildToFront(View) 9849 */ 9850 public void bringToFront() { 9851 if (mParent != null) { 9852 mParent.bringChildToFront(this); 9853 } 9854 } 9855 9856 /** 9857 * This is called in response to an internal scroll in this view (i.e., the 9858 * view scrolled its own contents). This is typically as a result of 9859 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9860 * called. 9861 * 9862 * @param l Current horizontal scroll origin. 9863 * @param t Current vertical scroll origin. 9864 * @param oldl Previous horizontal scroll origin. 9865 * @param oldt Previous vertical scroll origin. 9866 */ 9867 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9868 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9869 postSendViewScrolledAccessibilityEventCallback(); 9870 } 9871 9872 mBackgroundSizeChanged = true; 9873 9874 final AttachInfo ai = mAttachInfo; 9875 if (ai != null) { 9876 ai.mViewScrollChanged = true; 9877 } 9878 9879 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 9880 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 9881 } 9882 } 9883 9884 /** 9885 * Interface definition for a callback to be invoked when the scroll 9886 * X or Y positions of a view change. 9887 * <p> 9888 * <b>Note:</b> Some views handle scrolling independently from View and may 9889 * have their own separate listeners for scroll-type events. For example, 9890 * {@link android.widget.ListView ListView} allows clients to register an 9891 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 9892 * to listen for changes in list scroll position. 9893 * 9894 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 9895 */ 9896 public interface OnScrollChangeListener { 9897 /** 9898 * Called when the scroll position of a view changes. 9899 * 9900 * @param v The view whose scroll position has changed. 9901 * @param scrollX Current horizontal scroll origin. 9902 * @param scrollY Current vertical scroll origin. 9903 * @param oldScrollX Previous horizontal scroll origin. 9904 * @param oldScrollY Previous vertical scroll origin. 9905 */ 9906 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 9907 } 9908 9909 /** 9910 * Interface definition for a callback to be invoked when the layout bounds of a view 9911 * changes due to layout processing. 9912 */ 9913 public interface OnLayoutChangeListener { 9914 /** 9915 * Called when the layout bounds of a view changes due to layout processing. 9916 * 9917 * @param v The view whose bounds have changed. 9918 * @param left The new value of the view's left property. 9919 * @param top The new value of the view's top property. 9920 * @param right The new value of the view's right property. 9921 * @param bottom The new value of the view's bottom property. 9922 * @param oldLeft The previous value of the view's left property. 9923 * @param oldTop The previous value of the view's top property. 9924 * @param oldRight The previous value of the view's right property. 9925 * @param oldBottom The previous value of the view's bottom property. 9926 */ 9927 void onLayoutChange(View v, int left, int top, int right, int bottom, 9928 int oldLeft, int oldTop, int oldRight, int oldBottom); 9929 } 9930 9931 /** 9932 * This is called during layout when the size of this view has changed. If 9933 * you were just added to the view hierarchy, you're called with the old 9934 * values of 0. 9935 * 9936 * @param w Current width of this view. 9937 * @param h Current height of this view. 9938 * @param oldw Old width of this view. 9939 * @param oldh Old height of this view. 9940 */ 9941 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9942 } 9943 9944 /** 9945 * Called by draw to draw the child views. This may be overridden 9946 * by derived classes to gain control just before its children are drawn 9947 * (but after its own view has been drawn). 9948 * @param canvas the canvas on which to draw the view 9949 */ 9950 protected void dispatchDraw(Canvas canvas) { 9951 9952 } 9953 9954 /** 9955 * Gets the parent of this view. Note that the parent is a 9956 * ViewParent and not necessarily a View. 9957 * 9958 * @return Parent of this view. 9959 */ 9960 public final ViewParent getParent() { 9961 return mParent; 9962 } 9963 9964 /** 9965 * Set the horizontal scrolled position of your view. This will cause a call to 9966 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9967 * invalidated. 9968 * @param value the x position to scroll to 9969 */ 9970 public void setScrollX(int value) { 9971 scrollTo(value, mScrollY); 9972 } 9973 9974 /** 9975 * Set the vertical scrolled position of your view. This will cause a call to 9976 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9977 * invalidated. 9978 * @param value the y position to scroll to 9979 */ 9980 public void setScrollY(int value) { 9981 scrollTo(mScrollX, value); 9982 } 9983 9984 /** 9985 * Return the scrolled left position of this view. This is the left edge of 9986 * the displayed part of your view. You do not need to draw any pixels 9987 * farther left, since those are outside of the frame of your view on 9988 * screen. 9989 * 9990 * @return The left edge of the displayed part of your view, in pixels. 9991 */ 9992 public final int getScrollX() { 9993 return mScrollX; 9994 } 9995 9996 /** 9997 * Return the scrolled top position of this view. This is the top edge of 9998 * the displayed part of your view. You do not need to draw any pixels above 9999 * it, since those are outside of the frame of your view on screen. 10000 * 10001 * @return The top edge of the displayed part of your view, in pixels. 10002 */ 10003 public final int getScrollY() { 10004 return mScrollY; 10005 } 10006 10007 /** 10008 * Return the width of the your view. 10009 * 10010 * @return The width of your view, in pixels. 10011 */ 10012 @ViewDebug.ExportedProperty(category = "layout") 10013 public final int getWidth() { 10014 return mRight - mLeft; 10015 } 10016 10017 /** 10018 * Return the height of your view. 10019 * 10020 * @return The height of your view, in pixels. 10021 */ 10022 @ViewDebug.ExportedProperty(category = "layout") 10023 public final int getHeight() { 10024 return mBottom - mTop; 10025 } 10026 10027 /** 10028 * Return the visible drawing bounds of your view. Fills in the output 10029 * rectangle with the values from getScrollX(), getScrollY(), 10030 * getWidth(), and getHeight(). These bounds do not account for any 10031 * transformation properties currently set on the view, such as 10032 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 10033 * 10034 * @param outRect The (scrolled) drawing bounds of the view. 10035 */ 10036 public void getDrawingRect(Rect outRect) { 10037 outRect.left = mScrollX; 10038 outRect.top = mScrollY; 10039 outRect.right = mScrollX + (mRight - mLeft); 10040 outRect.bottom = mScrollY + (mBottom - mTop); 10041 } 10042 10043 /** 10044 * Like {@link #getMeasuredWidthAndState()}, but only returns the 10045 * raw width component (that is the result is masked by 10046 * {@link #MEASURED_SIZE_MASK}). 10047 * 10048 * @return The raw measured width of this view. 10049 */ 10050 public final int getMeasuredWidth() { 10051 return mMeasuredWidth & MEASURED_SIZE_MASK; 10052 } 10053 10054 /** 10055 * Return the full width measurement information for this view as computed 10056 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10057 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10058 * This should be used during measurement and layout calculations only. Use 10059 * {@link #getWidth()} to see how wide a view is after layout. 10060 * 10061 * @return The measured width of this view as a bit mask. 10062 */ 10063 public final int getMeasuredWidthAndState() { 10064 return mMeasuredWidth; 10065 } 10066 10067 /** 10068 * Like {@link #getMeasuredHeightAndState()}, but only returns the 10069 * raw width component (that is the result is masked by 10070 * {@link #MEASURED_SIZE_MASK}). 10071 * 10072 * @return The raw measured height of this view. 10073 */ 10074 public final int getMeasuredHeight() { 10075 return mMeasuredHeight & MEASURED_SIZE_MASK; 10076 } 10077 10078 /** 10079 * Return the full height measurement information for this view as computed 10080 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10081 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10082 * This should be used during measurement and layout calculations only. Use 10083 * {@link #getHeight()} to see how wide a view is after layout. 10084 * 10085 * @return The measured width of this view as a bit mask. 10086 */ 10087 public final int getMeasuredHeightAndState() { 10088 return mMeasuredHeight; 10089 } 10090 10091 /** 10092 * Return only the state bits of {@link #getMeasuredWidthAndState()} 10093 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 10094 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 10095 * and the height component is at the shifted bits 10096 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 10097 */ 10098 public final int getMeasuredState() { 10099 return (mMeasuredWidth&MEASURED_STATE_MASK) 10100 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 10101 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 10102 } 10103 10104 /** 10105 * The transform matrix of this view, which is calculated based on the current 10106 * rotation, scale, and pivot properties. 10107 * 10108 * @see #getRotation() 10109 * @see #getScaleX() 10110 * @see #getScaleY() 10111 * @see #getPivotX() 10112 * @see #getPivotY() 10113 * @return The current transform matrix for the view 10114 */ 10115 public Matrix getMatrix() { 10116 ensureTransformationInfo(); 10117 final Matrix matrix = mTransformationInfo.mMatrix; 10118 mRenderNode.getMatrix(matrix); 10119 return matrix; 10120 } 10121 10122 /** 10123 * Returns true if the transform matrix is the identity matrix. 10124 * Recomputes the matrix if necessary. 10125 * 10126 * @return True if the transform matrix is the identity matrix, false otherwise. 10127 */ 10128 final boolean hasIdentityMatrix() { 10129 return mRenderNode.hasIdentityMatrix(); 10130 } 10131 10132 void ensureTransformationInfo() { 10133 if (mTransformationInfo == null) { 10134 mTransformationInfo = new TransformationInfo(); 10135 } 10136 } 10137 10138 /** 10139 * Utility method to retrieve the inverse of the current mMatrix property. 10140 * We cache the matrix to avoid recalculating it when transform properties 10141 * have not changed. 10142 * 10143 * @return The inverse of the current matrix of this view. 10144 * @hide 10145 */ 10146 public final Matrix getInverseMatrix() { 10147 ensureTransformationInfo(); 10148 if (mTransformationInfo.mInverseMatrix == null) { 10149 mTransformationInfo.mInverseMatrix = new Matrix(); 10150 } 10151 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10152 mRenderNode.getInverseMatrix(matrix); 10153 return matrix; 10154 } 10155 10156 /** 10157 * Gets the distance along the Z axis from the camera to this view. 10158 * 10159 * @see #setCameraDistance(float) 10160 * 10161 * @return The distance along the Z axis. 10162 */ 10163 public float getCameraDistance() { 10164 final float dpi = mResources.getDisplayMetrics().densityDpi; 10165 return -(mRenderNode.getCameraDistance() * dpi); 10166 } 10167 10168 /** 10169 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10170 * views are drawn) from the camera to this view. The camera's distance 10171 * affects 3D transformations, for instance rotations around the X and Y 10172 * axis. If the rotationX or rotationY properties are changed and this view is 10173 * large (more than half the size of the screen), it is recommended to always 10174 * use a camera distance that's greater than the height (X axis rotation) or 10175 * the width (Y axis rotation) of this view.</p> 10176 * 10177 * <p>The distance of the camera from the view plane can have an affect on the 10178 * perspective distortion of the view when it is rotated around the x or y axis. 10179 * For example, a large distance will result in a large viewing angle, and there 10180 * will not be much perspective distortion of the view as it rotates. A short 10181 * distance may cause much more perspective distortion upon rotation, and can 10182 * also result in some drawing artifacts if the rotated view ends up partially 10183 * behind the camera (which is why the recommendation is to use a distance at 10184 * least as far as the size of the view, if the view is to be rotated.)</p> 10185 * 10186 * <p>The distance is expressed in "depth pixels." The default distance depends 10187 * on the screen density. For instance, on a medium density display, the 10188 * default distance is 1280. On a high density display, the default distance 10189 * is 1920.</p> 10190 * 10191 * <p>If you want to specify a distance that leads to visually consistent 10192 * results across various densities, use the following formula:</p> 10193 * <pre> 10194 * float scale = context.getResources().getDisplayMetrics().density; 10195 * view.setCameraDistance(distance * scale); 10196 * </pre> 10197 * 10198 * <p>The density scale factor of a high density display is 1.5, 10199 * and 1920 = 1280 * 1.5.</p> 10200 * 10201 * @param distance The distance in "depth pixels", if negative the opposite 10202 * value is used 10203 * 10204 * @see #setRotationX(float) 10205 * @see #setRotationY(float) 10206 */ 10207 public void setCameraDistance(float distance) { 10208 final float dpi = mResources.getDisplayMetrics().densityDpi; 10209 10210 invalidateViewProperty(true, false); 10211 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 10212 invalidateViewProperty(false, false); 10213 10214 invalidateParentIfNeededAndWasQuickRejected(); 10215 } 10216 10217 /** 10218 * The degrees that the view is rotated around the pivot point. 10219 * 10220 * @see #setRotation(float) 10221 * @see #getPivotX() 10222 * @see #getPivotY() 10223 * 10224 * @return The degrees of rotation. 10225 */ 10226 @ViewDebug.ExportedProperty(category = "drawing") 10227 public float getRotation() { 10228 return mRenderNode.getRotation(); 10229 } 10230 10231 /** 10232 * Sets the degrees that the view is rotated around the pivot point. Increasing values 10233 * result in clockwise rotation. 10234 * 10235 * @param rotation The degrees of rotation. 10236 * 10237 * @see #getRotation() 10238 * @see #getPivotX() 10239 * @see #getPivotY() 10240 * @see #setRotationX(float) 10241 * @see #setRotationY(float) 10242 * 10243 * @attr ref android.R.styleable#View_rotation 10244 */ 10245 public void setRotation(float rotation) { 10246 if (rotation != getRotation()) { 10247 // Double-invalidation is necessary to capture view's old and new areas 10248 invalidateViewProperty(true, false); 10249 mRenderNode.setRotation(rotation); 10250 invalidateViewProperty(false, true); 10251 10252 invalidateParentIfNeededAndWasQuickRejected(); 10253 notifySubtreeAccessibilityStateChangedIfNeeded(); 10254 } 10255 } 10256 10257 /** 10258 * The degrees that the view is rotated around the vertical axis through the pivot point. 10259 * 10260 * @see #getPivotX() 10261 * @see #getPivotY() 10262 * @see #setRotationY(float) 10263 * 10264 * @return The degrees of Y rotation. 10265 */ 10266 @ViewDebug.ExportedProperty(category = "drawing") 10267 public float getRotationY() { 10268 return mRenderNode.getRotationY(); 10269 } 10270 10271 /** 10272 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 10273 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 10274 * down the y axis. 10275 * 10276 * When rotating large views, it is recommended to adjust the camera distance 10277 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10278 * 10279 * @param rotationY The degrees of Y rotation. 10280 * 10281 * @see #getRotationY() 10282 * @see #getPivotX() 10283 * @see #getPivotY() 10284 * @see #setRotation(float) 10285 * @see #setRotationX(float) 10286 * @see #setCameraDistance(float) 10287 * 10288 * @attr ref android.R.styleable#View_rotationY 10289 */ 10290 public void setRotationY(float rotationY) { 10291 if (rotationY != getRotationY()) { 10292 invalidateViewProperty(true, false); 10293 mRenderNode.setRotationY(rotationY); 10294 invalidateViewProperty(false, true); 10295 10296 invalidateParentIfNeededAndWasQuickRejected(); 10297 notifySubtreeAccessibilityStateChangedIfNeeded(); 10298 } 10299 } 10300 10301 /** 10302 * The degrees that the view is rotated around the horizontal axis through the pivot point. 10303 * 10304 * @see #getPivotX() 10305 * @see #getPivotY() 10306 * @see #setRotationX(float) 10307 * 10308 * @return The degrees of X rotation. 10309 */ 10310 @ViewDebug.ExportedProperty(category = "drawing") 10311 public float getRotationX() { 10312 return mRenderNode.getRotationX(); 10313 } 10314 10315 /** 10316 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 10317 * Increasing values result in clockwise rotation from the viewpoint of looking down the 10318 * x axis. 10319 * 10320 * When rotating large views, it is recommended to adjust the camera distance 10321 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10322 * 10323 * @param rotationX The degrees of X rotation. 10324 * 10325 * @see #getRotationX() 10326 * @see #getPivotX() 10327 * @see #getPivotY() 10328 * @see #setRotation(float) 10329 * @see #setRotationY(float) 10330 * @see #setCameraDistance(float) 10331 * 10332 * @attr ref android.R.styleable#View_rotationX 10333 */ 10334 public void setRotationX(float rotationX) { 10335 if (rotationX != getRotationX()) { 10336 invalidateViewProperty(true, false); 10337 mRenderNode.setRotationX(rotationX); 10338 invalidateViewProperty(false, true); 10339 10340 invalidateParentIfNeededAndWasQuickRejected(); 10341 notifySubtreeAccessibilityStateChangedIfNeeded(); 10342 } 10343 } 10344 10345 /** 10346 * The amount that the view is scaled in x around the pivot point, as a proportion of 10347 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10348 * 10349 * <p>By default, this is 1.0f. 10350 * 10351 * @see #getPivotX() 10352 * @see #getPivotY() 10353 * @return The scaling factor. 10354 */ 10355 @ViewDebug.ExportedProperty(category = "drawing") 10356 public float getScaleX() { 10357 return mRenderNode.getScaleX(); 10358 } 10359 10360 /** 10361 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10362 * the view's unscaled width. A value of 1 means that no scaling is applied. 10363 * 10364 * @param scaleX The scaling factor. 10365 * @see #getPivotX() 10366 * @see #getPivotY() 10367 * 10368 * @attr ref android.R.styleable#View_scaleX 10369 */ 10370 public void setScaleX(float scaleX) { 10371 if (scaleX != getScaleX()) { 10372 invalidateViewProperty(true, false); 10373 mRenderNode.setScaleX(scaleX); 10374 invalidateViewProperty(false, true); 10375 10376 invalidateParentIfNeededAndWasQuickRejected(); 10377 notifySubtreeAccessibilityStateChangedIfNeeded(); 10378 } 10379 } 10380 10381 /** 10382 * The amount that the view is scaled in y around the pivot point, as a proportion of 10383 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10384 * 10385 * <p>By default, this is 1.0f. 10386 * 10387 * @see #getPivotX() 10388 * @see #getPivotY() 10389 * @return The scaling factor. 10390 */ 10391 @ViewDebug.ExportedProperty(category = "drawing") 10392 public float getScaleY() { 10393 return mRenderNode.getScaleY(); 10394 } 10395 10396 /** 10397 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10398 * the view's unscaled width. A value of 1 means that no scaling is applied. 10399 * 10400 * @param scaleY The scaling factor. 10401 * @see #getPivotX() 10402 * @see #getPivotY() 10403 * 10404 * @attr ref android.R.styleable#View_scaleY 10405 */ 10406 public void setScaleY(float scaleY) { 10407 if (scaleY != getScaleY()) { 10408 invalidateViewProperty(true, false); 10409 mRenderNode.setScaleY(scaleY); 10410 invalidateViewProperty(false, true); 10411 10412 invalidateParentIfNeededAndWasQuickRejected(); 10413 notifySubtreeAccessibilityStateChangedIfNeeded(); 10414 } 10415 } 10416 10417 /** 10418 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10419 * and {@link #setScaleX(float) scaled}. 10420 * 10421 * @see #getRotation() 10422 * @see #getScaleX() 10423 * @see #getScaleY() 10424 * @see #getPivotY() 10425 * @return The x location of the pivot point. 10426 * 10427 * @attr ref android.R.styleable#View_transformPivotX 10428 */ 10429 @ViewDebug.ExportedProperty(category = "drawing") 10430 public float getPivotX() { 10431 return mRenderNode.getPivotX(); 10432 } 10433 10434 /** 10435 * Sets the x location of the point around which the view is 10436 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10437 * By default, the pivot point is centered on the object. 10438 * Setting this property disables this behavior and causes the view to use only the 10439 * explicitly set pivotX and pivotY values. 10440 * 10441 * @param pivotX The x location of the pivot point. 10442 * @see #getRotation() 10443 * @see #getScaleX() 10444 * @see #getScaleY() 10445 * @see #getPivotY() 10446 * 10447 * @attr ref android.R.styleable#View_transformPivotX 10448 */ 10449 public void setPivotX(float pivotX) { 10450 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10451 invalidateViewProperty(true, false); 10452 mRenderNode.setPivotX(pivotX); 10453 invalidateViewProperty(false, true); 10454 10455 invalidateParentIfNeededAndWasQuickRejected(); 10456 } 10457 } 10458 10459 /** 10460 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10461 * and {@link #setScaleY(float) scaled}. 10462 * 10463 * @see #getRotation() 10464 * @see #getScaleX() 10465 * @see #getScaleY() 10466 * @see #getPivotY() 10467 * @return The y location of the pivot point. 10468 * 10469 * @attr ref android.R.styleable#View_transformPivotY 10470 */ 10471 @ViewDebug.ExportedProperty(category = "drawing") 10472 public float getPivotY() { 10473 return mRenderNode.getPivotY(); 10474 } 10475 10476 /** 10477 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10478 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10479 * Setting this property disables this behavior and causes the view to use only the 10480 * explicitly set pivotX and pivotY values. 10481 * 10482 * @param pivotY The y location of the pivot point. 10483 * @see #getRotation() 10484 * @see #getScaleX() 10485 * @see #getScaleY() 10486 * @see #getPivotY() 10487 * 10488 * @attr ref android.R.styleable#View_transformPivotY 10489 */ 10490 public void setPivotY(float pivotY) { 10491 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10492 invalidateViewProperty(true, false); 10493 mRenderNode.setPivotY(pivotY); 10494 invalidateViewProperty(false, true); 10495 10496 invalidateParentIfNeededAndWasQuickRejected(); 10497 } 10498 } 10499 10500 /** 10501 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10502 * completely transparent and 1 means the view is completely opaque. 10503 * 10504 * <p>By default this is 1.0f. 10505 * @return The opacity of the view. 10506 */ 10507 @ViewDebug.ExportedProperty(category = "drawing") 10508 public float getAlpha() { 10509 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10510 } 10511 10512 /** 10513 * Returns whether this View has content which overlaps. 10514 * 10515 * <p>This function, intended to be overridden by specific View types, is an optimization when 10516 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10517 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10518 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10519 * directly. An example of overlapping rendering is a TextView with a background image, such as 10520 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10521 * ImageView with only the foreground image. The default implementation returns true; subclasses 10522 * should override if they have cases which can be optimized.</p> 10523 * 10524 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10525 * necessitates that a View return true if it uses the methods internally without passing the 10526 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10527 * 10528 * @return true if the content in this view might overlap, false otherwise. 10529 */ 10530 @ViewDebug.ExportedProperty(category = "drawing") 10531 public boolean hasOverlappingRendering() { 10532 return true; 10533 } 10534 10535 /** 10536 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10537 * completely transparent and 1 means the view is completely opaque.</p> 10538 * 10539 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10540 * performance implications, especially for large views. It is best to use the alpha property 10541 * sparingly and transiently, as in the case of fading animations.</p> 10542 * 10543 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10544 * strongly recommended for performance reasons to either override 10545 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10546 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10547 * 10548 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10549 * responsible for applying the opacity itself.</p> 10550 * 10551 * <p>Note that if the view is backed by a 10552 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10553 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10554 * 1.0 will supersede the alpha of the layer paint.</p> 10555 * 10556 * @param alpha The opacity of the view. 10557 * 10558 * @see #hasOverlappingRendering() 10559 * @see #setLayerType(int, android.graphics.Paint) 10560 * 10561 * @attr ref android.R.styleable#View_alpha 10562 */ 10563 public void setAlpha(float alpha) { 10564 ensureTransformationInfo(); 10565 if (mTransformationInfo.mAlpha != alpha) { 10566 mTransformationInfo.mAlpha = alpha; 10567 if (onSetAlpha((int) (alpha * 255))) { 10568 mPrivateFlags |= PFLAG_ALPHA_SET; 10569 // subclass is handling alpha - don't optimize rendering cache invalidation 10570 invalidateParentCaches(); 10571 invalidate(true); 10572 } else { 10573 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10574 invalidateViewProperty(true, false); 10575 mRenderNode.setAlpha(getFinalAlpha()); 10576 notifyViewAccessibilityStateChangedIfNeeded( 10577 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10578 } 10579 } 10580 } 10581 10582 /** 10583 * Faster version of setAlpha() which performs the same steps except there are 10584 * no calls to invalidate(). The caller of this function should perform proper invalidation 10585 * on the parent and this object. The return value indicates whether the subclass handles 10586 * alpha (the return value for onSetAlpha()). 10587 * 10588 * @param alpha The new value for the alpha property 10589 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10590 * the new value for the alpha property is different from the old value 10591 */ 10592 boolean setAlphaNoInvalidation(float alpha) { 10593 ensureTransformationInfo(); 10594 if (mTransformationInfo.mAlpha != alpha) { 10595 mTransformationInfo.mAlpha = alpha; 10596 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10597 if (subclassHandlesAlpha) { 10598 mPrivateFlags |= PFLAG_ALPHA_SET; 10599 return true; 10600 } else { 10601 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10602 mRenderNode.setAlpha(getFinalAlpha()); 10603 } 10604 } 10605 return false; 10606 } 10607 10608 /** 10609 * This property is hidden and intended only for use by the Fade transition, which 10610 * animates it to produce a visual translucency that does not side-effect (or get 10611 * affected by) the real alpha property. This value is composited with the other 10612 * alpha value (and the AlphaAnimation value, when that is present) to produce 10613 * a final visual translucency result, which is what is passed into the DisplayList. 10614 * 10615 * @hide 10616 */ 10617 public void setTransitionAlpha(float alpha) { 10618 ensureTransformationInfo(); 10619 if (mTransformationInfo.mTransitionAlpha != alpha) { 10620 mTransformationInfo.mTransitionAlpha = alpha; 10621 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10622 invalidateViewProperty(true, false); 10623 mRenderNode.setAlpha(getFinalAlpha()); 10624 } 10625 } 10626 10627 /** 10628 * Calculates the visual alpha of this view, which is a combination of the actual 10629 * alpha value and the transitionAlpha value (if set). 10630 */ 10631 private float getFinalAlpha() { 10632 if (mTransformationInfo != null) { 10633 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10634 } 10635 return 1; 10636 } 10637 10638 /** 10639 * This property is hidden and intended only for use by the Fade transition, which 10640 * animates it to produce a visual translucency that does not side-effect (or get 10641 * affected by) the real alpha property. This value is composited with the other 10642 * alpha value (and the AlphaAnimation value, when that is present) to produce 10643 * a final visual translucency result, which is what is passed into the DisplayList. 10644 * 10645 * @hide 10646 */ 10647 @ViewDebug.ExportedProperty(category = "drawing") 10648 public float getTransitionAlpha() { 10649 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10650 } 10651 10652 /** 10653 * Top position of this view relative to its parent. 10654 * 10655 * @return The top of this view, in pixels. 10656 */ 10657 @ViewDebug.CapturedViewProperty 10658 public final int getTop() { 10659 return mTop; 10660 } 10661 10662 /** 10663 * Sets the top position of this view relative to its parent. This method is meant to be called 10664 * by the layout system and should not generally be called otherwise, because the property 10665 * may be changed at any time by the layout. 10666 * 10667 * @param top The top of this view, in pixels. 10668 */ 10669 public final void setTop(int top) { 10670 if (top != mTop) { 10671 final boolean matrixIsIdentity = hasIdentityMatrix(); 10672 if (matrixIsIdentity) { 10673 if (mAttachInfo != null) { 10674 int minTop; 10675 int yLoc; 10676 if (top < mTop) { 10677 minTop = top; 10678 yLoc = top - mTop; 10679 } else { 10680 minTop = mTop; 10681 yLoc = 0; 10682 } 10683 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10684 } 10685 } else { 10686 // Double-invalidation is necessary to capture view's old and new areas 10687 invalidate(true); 10688 } 10689 10690 int width = mRight - mLeft; 10691 int oldHeight = mBottom - mTop; 10692 10693 mTop = top; 10694 mRenderNode.setTop(mTop); 10695 10696 sizeChange(width, mBottom - mTop, width, oldHeight); 10697 10698 if (!matrixIsIdentity) { 10699 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10700 invalidate(true); 10701 } 10702 mBackgroundSizeChanged = true; 10703 invalidateParentIfNeeded(); 10704 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10705 // View was rejected last time it was drawn by its parent; this may have changed 10706 invalidateParentIfNeeded(); 10707 } 10708 } 10709 } 10710 10711 /** 10712 * Bottom position of this view relative to its parent. 10713 * 10714 * @return The bottom of this view, in pixels. 10715 */ 10716 @ViewDebug.CapturedViewProperty 10717 public final int getBottom() { 10718 return mBottom; 10719 } 10720 10721 /** 10722 * True if this view has changed since the last time being drawn. 10723 * 10724 * @return The dirty state of this view. 10725 */ 10726 public boolean isDirty() { 10727 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10728 } 10729 10730 /** 10731 * Sets the bottom position of this view relative to its parent. This method is meant to be 10732 * called by the layout system and should not generally be called otherwise, because the 10733 * property may be changed at any time by the layout. 10734 * 10735 * @param bottom The bottom of this view, in pixels. 10736 */ 10737 public final void setBottom(int bottom) { 10738 if (bottom != mBottom) { 10739 final boolean matrixIsIdentity = hasIdentityMatrix(); 10740 if (matrixIsIdentity) { 10741 if (mAttachInfo != null) { 10742 int maxBottom; 10743 if (bottom < mBottom) { 10744 maxBottom = mBottom; 10745 } else { 10746 maxBottom = bottom; 10747 } 10748 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10749 } 10750 } else { 10751 // Double-invalidation is necessary to capture view's old and new areas 10752 invalidate(true); 10753 } 10754 10755 int width = mRight - mLeft; 10756 int oldHeight = mBottom - mTop; 10757 10758 mBottom = bottom; 10759 mRenderNode.setBottom(mBottom); 10760 10761 sizeChange(width, mBottom - mTop, width, oldHeight); 10762 10763 if (!matrixIsIdentity) { 10764 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10765 invalidate(true); 10766 } 10767 mBackgroundSizeChanged = true; 10768 invalidateParentIfNeeded(); 10769 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10770 // View was rejected last time it was drawn by its parent; this may have changed 10771 invalidateParentIfNeeded(); 10772 } 10773 } 10774 } 10775 10776 /** 10777 * Left position of this view relative to its parent. 10778 * 10779 * @return The left edge of this view, in pixels. 10780 */ 10781 @ViewDebug.CapturedViewProperty 10782 public final int getLeft() { 10783 return mLeft; 10784 } 10785 10786 /** 10787 * Sets the left position of this view relative to its parent. This method is meant to be called 10788 * by the layout system and should not generally be called otherwise, because the property 10789 * may be changed at any time by the layout. 10790 * 10791 * @param left The left of this view, in pixels. 10792 */ 10793 public final void setLeft(int left) { 10794 if (left != mLeft) { 10795 final boolean matrixIsIdentity = hasIdentityMatrix(); 10796 if (matrixIsIdentity) { 10797 if (mAttachInfo != null) { 10798 int minLeft; 10799 int xLoc; 10800 if (left < mLeft) { 10801 minLeft = left; 10802 xLoc = left - mLeft; 10803 } else { 10804 minLeft = mLeft; 10805 xLoc = 0; 10806 } 10807 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10808 } 10809 } else { 10810 // Double-invalidation is necessary to capture view's old and new areas 10811 invalidate(true); 10812 } 10813 10814 int oldWidth = mRight - mLeft; 10815 int height = mBottom - mTop; 10816 10817 mLeft = left; 10818 mRenderNode.setLeft(left); 10819 10820 sizeChange(mRight - mLeft, height, oldWidth, height); 10821 10822 if (!matrixIsIdentity) { 10823 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10824 invalidate(true); 10825 } 10826 mBackgroundSizeChanged = true; 10827 invalidateParentIfNeeded(); 10828 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10829 // View was rejected last time it was drawn by its parent; this may have changed 10830 invalidateParentIfNeeded(); 10831 } 10832 } 10833 } 10834 10835 /** 10836 * Right position of this view relative to its parent. 10837 * 10838 * @return The right edge of this view, in pixels. 10839 */ 10840 @ViewDebug.CapturedViewProperty 10841 public final int getRight() { 10842 return mRight; 10843 } 10844 10845 /** 10846 * Sets the right position of this view relative to its parent. This method is meant to be called 10847 * by the layout system and should not generally be called otherwise, because the property 10848 * may be changed at any time by the layout. 10849 * 10850 * @param right The right of this view, in pixels. 10851 */ 10852 public final void setRight(int right) { 10853 if (right != mRight) { 10854 final boolean matrixIsIdentity = hasIdentityMatrix(); 10855 if (matrixIsIdentity) { 10856 if (mAttachInfo != null) { 10857 int maxRight; 10858 if (right < mRight) { 10859 maxRight = mRight; 10860 } else { 10861 maxRight = right; 10862 } 10863 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10864 } 10865 } else { 10866 // Double-invalidation is necessary to capture view's old and new areas 10867 invalidate(true); 10868 } 10869 10870 int oldWidth = mRight - mLeft; 10871 int height = mBottom - mTop; 10872 10873 mRight = right; 10874 mRenderNode.setRight(mRight); 10875 10876 sizeChange(mRight - mLeft, height, oldWidth, height); 10877 10878 if (!matrixIsIdentity) { 10879 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10880 invalidate(true); 10881 } 10882 mBackgroundSizeChanged = true; 10883 invalidateParentIfNeeded(); 10884 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10885 // View was rejected last time it was drawn by its parent; this may have changed 10886 invalidateParentIfNeeded(); 10887 } 10888 } 10889 } 10890 10891 /** 10892 * The visual x position of this view, in pixels. This is equivalent to the 10893 * {@link #setTranslationX(float) translationX} property plus the current 10894 * {@link #getLeft() left} property. 10895 * 10896 * @return The visual x position of this view, in pixels. 10897 */ 10898 @ViewDebug.ExportedProperty(category = "drawing") 10899 public float getX() { 10900 return mLeft + getTranslationX(); 10901 } 10902 10903 /** 10904 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10905 * {@link #setTranslationX(float) translationX} property to be the difference between 10906 * the x value passed in and the current {@link #getLeft() left} property. 10907 * 10908 * @param x The visual x position of this view, in pixels. 10909 */ 10910 public void setX(float x) { 10911 setTranslationX(x - mLeft); 10912 } 10913 10914 /** 10915 * The visual y position of this view, in pixels. This is equivalent to the 10916 * {@link #setTranslationY(float) translationY} property plus the current 10917 * {@link #getTop() top} property. 10918 * 10919 * @return The visual y position of this view, in pixels. 10920 */ 10921 @ViewDebug.ExportedProperty(category = "drawing") 10922 public float getY() { 10923 return mTop + getTranslationY(); 10924 } 10925 10926 /** 10927 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10928 * {@link #setTranslationY(float) translationY} property to be the difference between 10929 * the y value passed in and the current {@link #getTop() top} property. 10930 * 10931 * @param y The visual y position of this view, in pixels. 10932 */ 10933 public void setY(float y) { 10934 setTranslationY(y - mTop); 10935 } 10936 10937 /** 10938 * The visual z position of this view, in pixels. This is equivalent to the 10939 * {@link #setTranslationZ(float) translationZ} property plus the current 10940 * {@link #getElevation() elevation} property. 10941 * 10942 * @return The visual z position of this view, in pixels. 10943 */ 10944 @ViewDebug.ExportedProperty(category = "drawing") 10945 public float getZ() { 10946 return getElevation() + getTranslationZ(); 10947 } 10948 10949 /** 10950 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10951 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10952 * the x value passed in and the current {@link #getElevation() elevation} property. 10953 * 10954 * @param z The visual z position of this view, in pixels. 10955 */ 10956 public void setZ(float z) { 10957 setTranslationZ(z - getElevation()); 10958 } 10959 10960 /** 10961 * The base elevation of this view relative to its parent, in pixels. 10962 * 10963 * @return The base depth position of the view, in pixels. 10964 */ 10965 @ViewDebug.ExportedProperty(category = "drawing") 10966 public float getElevation() { 10967 return mRenderNode.getElevation(); 10968 } 10969 10970 /** 10971 * Sets the base elevation of this view, in pixels. 10972 * 10973 * @attr ref android.R.styleable#View_elevation 10974 */ 10975 public void setElevation(float elevation) { 10976 if (elevation != getElevation()) { 10977 invalidateViewProperty(true, false); 10978 mRenderNode.setElevation(elevation); 10979 invalidateViewProperty(false, true); 10980 10981 invalidateParentIfNeededAndWasQuickRejected(); 10982 } 10983 } 10984 10985 /** 10986 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10987 * This position is post-layout, in addition to wherever the object's 10988 * layout placed it. 10989 * 10990 * @return The horizontal position of this view relative to its left position, in pixels. 10991 */ 10992 @ViewDebug.ExportedProperty(category = "drawing") 10993 public float getTranslationX() { 10994 return mRenderNode.getTranslationX(); 10995 } 10996 10997 /** 10998 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10999 * This effectively positions the object post-layout, in addition to wherever the object's 11000 * layout placed it. 11001 * 11002 * @param translationX The horizontal position of this view relative to its left position, 11003 * in pixels. 11004 * 11005 * @attr ref android.R.styleable#View_translationX 11006 */ 11007 public void setTranslationX(float translationX) { 11008 if (translationX != getTranslationX()) { 11009 invalidateViewProperty(true, false); 11010 mRenderNode.setTranslationX(translationX); 11011 invalidateViewProperty(false, true); 11012 11013 invalidateParentIfNeededAndWasQuickRejected(); 11014 notifySubtreeAccessibilityStateChangedIfNeeded(); 11015 } 11016 } 11017 11018 /** 11019 * The vertical location of this view relative to its {@link #getTop() top} position. 11020 * This position is post-layout, in addition to wherever the object's 11021 * layout placed it. 11022 * 11023 * @return The vertical position of this view relative to its top position, 11024 * in pixels. 11025 */ 11026 @ViewDebug.ExportedProperty(category = "drawing") 11027 public float getTranslationY() { 11028 return mRenderNode.getTranslationY(); 11029 } 11030 11031 /** 11032 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 11033 * This effectively positions the object post-layout, in addition to wherever the object's 11034 * layout placed it. 11035 * 11036 * @param translationY The vertical position of this view relative to its top position, 11037 * in pixels. 11038 * 11039 * @attr ref android.R.styleable#View_translationY 11040 */ 11041 public void setTranslationY(float translationY) { 11042 if (translationY != getTranslationY()) { 11043 invalidateViewProperty(true, false); 11044 mRenderNode.setTranslationY(translationY); 11045 invalidateViewProperty(false, true); 11046 11047 invalidateParentIfNeededAndWasQuickRejected(); 11048 } 11049 } 11050 11051 /** 11052 * The depth location of this view relative to its {@link #getElevation() elevation}. 11053 * 11054 * @return The depth of this view relative to its elevation. 11055 */ 11056 @ViewDebug.ExportedProperty(category = "drawing") 11057 public float getTranslationZ() { 11058 return mRenderNode.getTranslationZ(); 11059 } 11060 11061 /** 11062 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 11063 * 11064 * @attr ref android.R.styleable#View_translationZ 11065 */ 11066 public void setTranslationZ(float translationZ) { 11067 if (translationZ != getTranslationZ()) { 11068 invalidateViewProperty(true, false); 11069 mRenderNode.setTranslationZ(translationZ); 11070 invalidateViewProperty(false, true); 11071 11072 invalidateParentIfNeededAndWasQuickRejected(); 11073 } 11074 } 11075 11076 /** @hide */ 11077 public void setAnimationMatrix(Matrix matrix) { 11078 invalidateViewProperty(true, false); 11079 mRenderNode.setAnimationMatrix(matrix); 11080 invalidateViewProperty(false, true); 11081 11082 invalidateParentIfNeededAndWasQuickRejected(); 11083 } 11084 11085 /** 11086 * Returns the current StateListAnimator if exists. 11087 * 11088 * @return StateListAnimator or null if it does not exists 11089 * @see #setStateListAnimator(android.animation.StateListAnimator) 11090 */ 11091 public StateListAnimator getStateListAnimator() { 11092 return mStateListAnimator; 11093 } 11094 11095 /** 11096 * Attaches the provided StateListAnimator to this View. 11097 * <p> 11098 * Any previously attached StateListAnimator will be detached. 11099 * 11100 * @param stateListAnimator The StateListAnimator to update the view 11101 * @see {@link android.animation.StateListAnimator} 11102 */ 11103 public void setStateListAnimator(StateListAnimator stateListAnimator) { 11104 if (mStateListAnimator == stateListAnimator) { 11105 return; 11106 } 11107 if (mStateListAnimator != null) { 11108 mStateListAnimator.setTarget(null); 11109 } 11110 mStateListAnimator = stateListAnimator; 11111 if (stateListAnimator != null) { 11112 stateListAnimator.setTarget(this); 11113 if (isAttachedToWindow()) { 11114 stateListAnimator.setState(getDrawableState()); 11115 } 11116 } 11117 } 11118 11119 /** 11120 * Returns whether the Outline should be used to clip the contents of the View. 11121 * <p> 11122 * Note that this flag will only be respected if the View's Outline returns true from 11123 * {@link Outline#canClip()}. 11124 * 11125 * @see #setOutlineProvider(ViewOutlineProvider) 11126 * @see #setClipToOutline(boolean) 11127 */ 11128 public final boolean getClipToOutline() { 11129 return mRenderNode.getClipToOutline(); 11130 } 11131 11132 /** 11133 * Sets whether the View's Outline should be used to clip the contents of the View. 11134 * <p> 11135 * Only a single non-rectangular clip can be applied on a View at any time. 11136 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 11137 * circular reveal} animation take priority over Outline clipping, and 11138 * child Outline clipping takes priority over Outline clipping done by a 11139 * parent. 11140 * <p> 11141 * Note that this flag will only be respected if the View's Outline returns true from 11142 * {@link Outline#canClip()}. 11143 * 11144 * @see #setOutlineProvider(ViewOutlineProvider) 11145 * @see #getClipToOutline() 11146 */ 11147 public void setClipToOutline(boolean clipToOutline) { 11148 damageInParent(); 11149 if (getClipToOutline() != clipToOutline) { 11150 mRenderNode.setClipToOutline(clipToOutline); 11151 } 11152 } 11153 11154 // correspond to the enum values of View_outlineProvider 11155 private static final int PROVIDER_BACKGROUND = 0; 11156 private static final int PROVIDER_NONE = 1; 11157 private static final int PROVIDER_BOUNDS = 2; 11158 private static final int PROVIDER_PADDED_BOUNDS = 3; 11159 private void setOutlineProviderFromAttribute(int providerInt) { 11160 switch (providerInt) { 11161 case PROVIDER_BACKGROUND: 11162 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11163 break; 11164 case PROVIDER_NONE: 11165 setOutlineProvider(null); 11166 break; 11167 case PROVIDER_BOUNDS: 11168 setOutlineProvider(ViewOutlineProvider.BOUNDS); 11169 break; 11170 case PROVIDER_PADDED_BOUNDS: 11171 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 11172 break; 11173 } 11174 } 11175 11176 /** 11177 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 11178 * the shape of the shadow it casts, and enables outline clipping. 11179 * <p> 11180 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 11181 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 11182 * outline provider with this method allows this behavior to be overridden. 11183 * <p> 11184 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 11185 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 11186 * <p> 11187 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 11188 * 11189 * @see #setClipToOutline(boolean) 11190 * @see #getClipToOutline() 11191 * @see #getOutlineProvider() 11192 */ 11193 public void setOutlineProvider(ViewOutlineProvider provider) { 11194 mOutlineProvider = provider; 11195 invalidateOutline(); 11196 } 11197 11198 /** 11199 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 11200 * that defines the shape of the shadow it casts, and enables outline clipping. 11201 * 11202 * @see #setOutlineProvider(ViewOutlineProvider) 11203 */ 11204 public ViewOutlineProvider getOutlineProvider() { 11205 return mOutlineProvider; 11206 } 11207 11208 /** 11209 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 11210 * 11211 * @see #setOutlineProvider(ViewOutlineProvider) 11212 */ 11213 public void invalidateOutline() { 11214 rebuildOutline(); 11215 11216 notifySubtreeAccessibilityStateChangedIfNeeded(); 11217 invalidateViewProperty(false, false); 11218 } 11219 11220 /** 11221 * Internal version of {@link #invalidateOutline()} which invalidates the 11222 * outline without invalidating the view itself. This is intended to be called from 11223 * within methods in the View class itself which are the result of the view being 11224 * invalidated already. For example, when we are drawing the background of a View, 11225 * we invalidate the outline in case it changed in the meantime, but we do not 11226 * need to invalidate the view because we're already drawing the background as part 11227 * of drawing the view in response to an earlier invalidation of the view. 11228 */ 11229 private void rebuildOutline() { 11230 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 11231 if (mAttachInfo == null) return; 11232 11233 if (mOutlineProvider == null) { 11234 // no provider, remove outline 11235 mRenderNode.setOutline(null); 11236 } else { 11237 final Outline outline = mAttachInfo.mTmpOutline; 11238 outline.setEmpty(); 11239 outline.setAlpha(1.0f); 11240 11241 mOutlineProvider.getOutline(this, outline); 11242 mRenderNode.setOutline(outline); 11243 } 11244 } 11245 11246 /** 11247 * HierarchyViewer only 11248 * 11249 * @hide 11250 */ 11251 @ViewDebug.ExportedProperty(category = "drawing") 11252 public boolean hasShadow() { 11253 return mRenderNode.hasShadow(); 11254 } 11255 11256 11257 /** @hide */ 11258 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 11259 mRenderNode.setRevealClip(shouldClip, x, y, radius); 11260 invalidateViewProperty(false, false); 11261 } 11262 11263 /** 11264 * Hit rectangle in parent's coordinates 11265 * 11266 * @param outRect The hit rectangle of the view. 11267 */ 11268 public void getHitRect(Rect outRect) { 11269 if (hasIdentityMatrix() || mAttachInfo == null) { 11270 outRect.set(mLeft, mTop, mRight, mBottom); 11271 } else { 11272 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 11273 tmpRect.set(0, 0, getWidth(), getHeight()); 11274 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 11275 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 11276 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 11277 } 11278 } 11279 11280 /** 11281 * Determines whether the given point, in local coordinates is inside the view. 11282 */ 11283 /*package*/ final boolean pointInView(float localX, float localY) { 11284 return localX >= 0 && localX < (mRight - mLeft) 11285 && localY >= 0 && localY < (mBottom - mTop); 11286 } 11287 11288 /** 11289 * Utility method to determine whether the given point, in local coordinates, 11290 * is inside the view, where the area of the view is expanded by the slop factor. 11291 * This method is called while processing touch-move events to determine if the event 11292 * is still within the view. 11293 * 11294 * @hide 11295 */ 11296 public boolean pointInView(float localX, float localY, float slop) { 11297 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 11298 localY < ((mBottom - mTop) + slop); 11299 } 11300 11301 /** 11302 * When a view has focus and the user navigates away from it, the next view is searched for 11303 * starting from the rectangle filled in by this method. 11304 * 11305 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 11306 * of the view. However, if your view maintains some idea of internal selection, 11307 * such as a cursor, or a selected row or column, you should override this method and 11308 * fill in a more specific rectangle. 11309 * 11310 * @param r The rectangle to fill in, in this view's coordinates. 11311 */ 11312 public void getFocusedRect(Rect r) { 11313 getDrawingRect(r); 11314 } 11315 11316 /** 11317 * If some part of this view is not clipped by any of its parents, then 11318 * return that area in r in global (root) coordinates. To convert r to local 11319 * coordinates (without taking possible View rotations into account), offset 11320 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 11321 * If the view is completely clipped or translated out, return false. 11322 * 11323 * @param r If true is returned, r holds the global coordinates of the 11324 * visible portion of this view. 11325 * @param globalOffset If true is returned, globalOffset holds the dx,dy 11326 * between this view and its root. globalOffet may be null. 11327 * @return true if r is non-empty (i.e. part of the view is visible at the 11328 * root level. 11329 */ 11330 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 11331 int width = mRight - mLeft; 11332 int height = mBottom - mTop; 11333 if (width > 0 && height > 0) { 11334 r.set(0, 0, width, height); 11335 if (globalOffset != null) { 11336 globalOffset.set(-mScrollX, -mScrollY); 11337 } 11338 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 11339 } 11340 return false; 11341 } 11342 11343 public final boolean getGlobalVisibleRect(Rect r) { 11344 return getGlobalVisibleRect(r, null); 11345 } 11346 11347 public final boolean getLocalVisibleRect(Rect r) { 11348 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 11349 if (getGlobalVisibleRect(r, offset)) { 11350 r.offset(-offset.x, -offset.y); // make r local 11351 return true; 11352 } 11353 return false; 11354 } 11355 11356 /** 11357 * Offset this view's vertical location by the specified number of pixels. 11358 * 11359 * @param offset the number of pixels to offset the view by 11360 */ 11361 public void offsetTopAndBottom(int offset) { 11362 if (offset != 0) { 11363 final boolean matrixIsIdentity = hasIdentityMatrix(); 11364 if (matrixIsIdentity) { 11365 if (isHardwareAccelerated()) { 11366 invalidateViewProperty(false, false); 11367 } else { 11368 final ViewParent p = mParent; 11369 if (p != null && mAttachInfo != null) { 11370 final Rect r = mAttachInfo.mTmpInvalRect; 11371 int minTop; 11372 int maxBottom; 11373 int yLoc; 11374 if (offset < 0) { 11375 minTop = mTop + offset; 11376 maxBottom = mBottom; 11377 yLoc = offset; 11378 } else { 11379 minTop = mTop; 11380 maxBottom = mBottom + offset; 11381 yLoc = 0; 11382 } 11383 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11384 p.invalidateChild(this, r); 11385 } 11386 } 11387 } else { 11388 invalidateViewProperty(false, false); 11389 } 11390 11391 mTop += offset; 11392 mBottom += offset; 11393 mRenderNode.offsetTopAndBottom(offset); 11394 if (isHardwareAccelerated()) { 11395 invalidateViewProperty(false, false); 11396 } else { 11397 if (!matrixIsIdentity) { 11398 invalidateViewProperty(false, true); 11399 } 11400 invalidateParentIfNeeded(); 11401 } 11402 notifySubtreeAccessibilityStateChangedIfNeeded(); 11403 } 11404 } 11405 11406 /** 11407 * Offset this view's horizontal location by the specified amount of pixels. 11408 * 11409 * @param offset the number of pixels to offset the view by 11410 */ 11411 public void offsetLeftAndRight(int offset) { 11412 if (offset != 0) { 11413 final boolean matrixIsIdentity = hasIdentityMatrix(); 11414 if (matrixIsIdentity) { 11415 if (isHardwareAccelerated()) { 11416 invalidateViewProperty(false, false); 11417 } else { 11418 final ViewParent p = mParent; 11419 if (p != null && mAttachInfo != null) { 11420 final Rect r = mAttachInfo.mTmpInvalRect; 11421 int minLeft; 11422 int maxRight; 11423 if (offset < 0) { 11424 minLeft = mLeft + offset; 11425 maxRight = mRight; 11426 } else { 11427 minLeft = mLeft; 11428 maxRight = mRight + offset; 11429 } 11430 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11431 p.invalidateChild(this, r); 11432 } 11433 } 11434 } else { 11435 invalidateViewProperty(false, false); 11436 } 11437 11438 mLeft += offset; 11439 mRight += offset; 11440 mRenderNode.offsetLeftAndRight(offset); 11441 if (isHardwareAccelerated()) { 11442 invalidateViewProperty(false, false); 11443 } else { 11444 if (!matrixIsIdentity) { 11445 invalidateViewProperty(false, true); 11446 } 11447 invalidateParentIfNeeded(); 11448 } 11449 notifySubtreeAccessibilityStateChangedIfNeeded(); 11450 } 11451 } 11452 11453 /** 11454 * Get the LayoutParams associated with this view. All views should have 11455 * layout parameters. These supply parameters to the <i>parent</i> of this 11456 * view specifying how it should be arranged. There are many subclasses of 11457 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11458 * of ViewGroup that are responsible for arranging their children. 11459 * 11460 * This method may return null if this View is not attached to a parent 11461 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11462 * was not invoked successfully. When a View is attached to a parent 11463 * ViewGroup, this method must not return null. 11464 * 11465 * @return The LayoutParams associated with this view, or null if no 11466 * parameters have been set yet 11467 */ 11468 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11469 public ViewGroup.LayoutParams getLayoutParams() { 11470 return mLayoutParams; 11471 } 11472 11473 /** 11474 * Set the layout parameters associated with this view. These supply 11475 * parameters to the <i>parent</i> of this view specifying how it should be 11476 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11477 * correspond to the different subclasses of ViewGroup that are responsible 11478 * for arranging their children. 11479 * 11480 * @param params The layout parameters for this view, cannot be null 11481 */ 11482 public void setLayoutParams(ViewGroup.LayoutParams params) { 11483 if (params == null) { 11484 throw new NullPointerException("Layout parameters cannot be null"); 11485 } 11486 mLayoutParams = params; 11487 resolveLayoutParams(); 11488 if (mParent instanceof ViewGroup) { 11489 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11490 } 11491 requestLayout(); 11492 } 11493 11494 /** 11495 * Resolve the layout parameters depending on the resolved layout direction 11496 * 11497 * @hide 11498 */ 11499 public void resolveLayoutParams() { 11500 if (mLayoutParams != null) { 11501 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11502 } 11503 } 11504 11505 /** 11506 * Set the scrolled position of your view. This will cause a call to 11507 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11508 * invalidated. 11509 * @param x the x position to scroll to 11510 * @param y the y position to scroll to 11511 */ 11512 public void scrollTo(int x, int y) { 11513 if (mScrollX != x || mScrollY != y) { 11514 int oldX = mScrollX; 11515 int oldY = mScrollY; 11516 mScrollX = x; 11517 mScrollY = y; 11518 invalidateParentCaches(); 11519 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11520 if (!awakenScrollBars()) { 11521 postInvalidateOnAnimation(); 11522 } 11523 } 11524 } 11525 11526 /** 11527 * Move the scrolled position of your view. This will cause a call to 11528 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11529 * invalidated. 11530 * @param x the amount of pixels to scroll by horizontally 11531 * @param y the amount of pixels to scroll by vertically 11532 */ 11533 public void scrollBy(int x, int y) { 11534 scrollTo(mScrollX + x, mScrollY + y); 11535 } 11536 11537 /** 11538 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11539 * animation to fade the scrollbars out after a default delay. If a subclass 11540 * provides animated scrolling, the start delay should equal the duration 11541 * of the scrolling animation.</p> 11542 * 11543 * <p>The animation starts only if at least one of the scrollbars is 11544 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11545 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11546 * this method returns true, and false otherwise. If the animation is 11547 * started, this method calls {@link #invalidate()}; in that case the 11548 * caller should not call {@link #invalidate()}.</p> 11549 * 11550 * <p>This method should be invoked every time a subclass directly updates 11551 * the scroll parameters.</p> 11552 * 11553 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11554 * and {@link #scrollTo(int, int)}.</p> 11555 * 11556 * @return true if the animation is played, false otherwise 11557 * 11558 * @see #awakenScrollBars(int) 11559 * @see #scrollBy(int, int) 11560 * @see #scrollTo(int, int) 11561 * @see #isHorizontalScrollBarEnabled() 11562 * @see #isVerticalScrollBarEnabled() 11563 * @see #setHorizontalScrollBarEnabled(boolean) 11564 * @see #setVerticalScrollBarEnabled(boolean) 11565 */ 11566 protected boolean awakenScrollBars() { 11567 return mScrollCache != null && 11568 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11569 } 11570 11571 /** 11572 * Trigger the scrollbars to draw. 11573 * This method differs from awakenScrollBars() only in its default duration. 11574 * initialAwakenScrollBars() will show the scroll bars for longer than 11575 * usual to give the user more of a chance to notice them. 11576 * 11577 * @return true if the animation is played, false otherwise. 11578 */ 11579 private boolean initialAwakenScrollBars() { 11580 return mScrollCache != null && 11581 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11582 } 11583 11584 /** 11585 * <p> 11586 * Trigger the scrollbars to draw. When invoked this method starts an 11587 * animation to fade the scrollbars out after a fixed delay. If a subclass 11588 * provides animated scrolling, the start delay should equal the duration of 11589 * the scrolling animation. 11590 * </p> 11591 * 11592 * <p> 11593 * The animation starts only if at least one of the scrollbars is enabled, 11594 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11595 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11596 * this method returns true, and false otherwise. If the animation is 11597 * started, this method calls {@link #invalidate()}; in that case the caller 11598 * should not call {@link #invalidate()}. 11599 * </p> 11600 * 11601 * <p> 11602 * This method should be invoked every time a subclass directly updates the 11603 * scroll parameters. 11604 * </p> 11605 * 11606 * @param startDelay the delay, in milliseconds, after which the animation 11607 * should start; when the delay is 0, the animation starts 11608 * immediately 11609 * @return true if the animation is played, false otherwise 11610 * 11611 * @see #scrollBy(int, int) 11612 * @see #scrollTo(int, int) 11613 * @see #isHorizontalScrollBarEnabled() 11614 * @see #isVerticalScrollBarEnabled() 11615 * @see #setHorizontalScrollBarEnabled(boolean) 11616 * @see #setVerticalScrollBarEnabled(boolean) 11617 */ 11618 protected boolean awakenScrollBars(int startDelay) { 11619 return awakenScrollBars(startDelay, true); 11620 } 11621 11622 /** 11623 * <p> 11624 * Trigger the scrollbars to draw. When invoked this method starts an 11625 * animation to fade the scrollbars out after a fixed delay. If a subclass 11626 * provides animated scrolling, the start delay should equal the duration of 11627 * the scrolling animation. 11628 * </p> 11629 * 11630 * <p> 11631 * The animation starts only if at least one of the scrollbars is enabled, 11632 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11633 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11634 * this method returns true, and false otherwise. If the animation is 11635 * started, this method calls {@link #invalidate()} if the invalidate parameter 11636 * is set to true; in that case the caller 11637 * should not call {@link #invalidate()}. 11638 * </p> 11639 * 11640 * <p> 11641 * This method should be invoked every time a subclass directly updates the 11642 * scroll parameters. 11643 * </p> 11644 * 11645 * @param startDelay the delay, in milliseconds, after which the animation 11646 * should start; when the delay is 0, the animation starts 11647 * immediately 11648 * 11649 * @param invalidate Whether this method should call invalidate 11650 * 11651 * @return true if the animation is played, false otherwise 11652 * 11653 * @see #scrollBy(int, int) 11654 * @see #scrollTo(int, int) 11655 * @see #isHorizontalScrollBarEnabled() 11656 * @see #isVerticalScrollBarEnabled() 11657 * @see #setHorizontalScrollBarEnabled(boolean) 11658 * @see #setVerticalScrollBarEnabled(boolean) 11659 */ 11660 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11661 final ScrollabilityCache scrollCache = mScrollCache; 11662 11663 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11664 return false; 11665 } 11666 11667 if (scrollCache.scrollBar == null) { 11668 scrollCache.scrollBar = new ScrollBarDrawable(); 11669 scrollCache.scrollBar.setCallback(this); 11670 scrollCache.scrollBar.setState(getDrawableState()); 11671 } 11672 11673 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11674 11675 if (invalidate) { 11676 // Invalidate to show the scrollbars 11677 postInvalidateOnAnimation(); 11678 } 11679 11680 if (scrollCache.state == ScrollabilityCache.OFF) { 11681 // FIXME: this is copied from WindowManagerService. 11682 // We should get this value from the system when it 11683 // is possible to do so. 11684 final int KEY_REPEAT_FIRST_DELAY = 750; 11685 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11686 } 11687 11688 // Tell mScrollCache when we should start fading. This may 11689 // extend the fade start time if one was already scheduled 11690 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11691 scrollCache.fadeStartTime = fadeStartTime; 11692 scrollCache.state = ScrollabilityCache.ON; 11693 11694 // Schedule our fader to run, unscheduling any old ones first 11695 if (mAttachInfo != null) { 11696 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11697 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11698 } 11699 11700 return true; 11701 } 11702 11703 return false; 11704 } 11705 11706 /** 11707 * Do not invalidate views which are not visible and which are not running an animation. They 11708 * will not get drawn and they should not set dirty flags as if they will be drawn 11709 */ 11710 private boolean skipInvalidate() { 11711 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11712 (!(mParent instanceof ViewGroup) || 11713 !((ViewGroup) mParent).isViewTransitioning(this)); 11714 } 11715 11716 /** 11717 * Mark the area defined by dirty as needing to be drawn. If the view is 11718 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11719 * point in the future. 11720 * <p> 11721 * This must be called from a UI thread. To call from a non-UI thread, call 11722 * {@link #postInvalidate()}. 11723 * <p> 11724 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11725 * {@code dirty}. 11726 * 11727 * @param dirty the rectangle representing the bounds of the dirty region 11728 */ 11729 public void invalidate(Rect dirty) { 11730 final int scrollX = mScrollX; 11731 final int scrollY = mScrollY; 11732 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11733 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11734 } 11735 11736 /** 11737 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11738 * coordinates of the dirty rect are relative to the view. If the view is 11739 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11740 * point in the future. 11741 * <p> 11742 * This must be called from a UI thread. To call from a non-UI thread, call 11743 * {@link #postInvalidate()}. 11744 * 11745 * @param l the left position of the dirty region 11746 * @param t the top position of the dirty region 11747 * @param r the right position of the dirty region 11748 * @param b the bottom position of the dirty region 11749 */ 11750 public void invalidate(int l, int t, int r, int b) { 11751 final int scrollX = mScrollX; 11752 final int scrollY = mScrollY; 11753 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11754 } 11755 11756 /** 11757 * Invalidate the whole view. If the view is visible, 11758 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11759 * the future. 11760 * <p> 11761 * This must be called from a UI thread. To call from a non-UI thread, call 11762 * {@link #postInvalidate()}. 11763 */ 11764 public void invalidate() { 11765 invalidate(true); 11766 } 11767 11768 /** 11769 * This is where the invalidate() work actually happens. A full invalidate() 11770 * causes the drawing cache to be invalidated, but this function can be 11771 * called with invalidateCache set to false to skip that invalidation step 11772 * for cases that do not need it (for example, a component that remains at 11773 * the same dimensions with the same content). 11774 * 11775 * @param invalidateCache Whether the drawing cache for this view should be 11776 * invalidated as well. This is usually true for a full 11777 * invalidate, but may be set to false if the View's contents or 11778 * dimensions have not changed. 11779 */ 11780 void invalidate(boolean invalidateCache) { 11781 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11782 } 11783 11784 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11785 boolean fullInvalidate) { 11786 if (mGhostView != null) { 11787 mGhostView.invalidate(true); 11788 return; 11789 } 11790 11791 if (skipInvalidate()) { 11792 return; 11793 } 11794 11795 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11796 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11797 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11798 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11799 if (fullInvalidate) { 11800 mLastIsOpaque = isOpaque(); 11801 mPrivateFlags &= ~PFLAG_DRAWN; 11802 } 11803 11804 mPrivateFlags |= PFLAG_DIRTY; 11805 11806 if (invalidateCache) { 11807 mPrivateFlags |= PFLAG_INVALIDATED; 11808 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11809 } 11810 11811 // Propagate the damage rectangle to the parent view. 11812 final AttachInfo ai = mAttachInfo; 11813 final ViewParent p = mParent; 11814 if (p != null && ai != null && l < r && t < b) { 11815 final Rect damage = ai.mTmpInvalRect; 11816 damage.set(l, t, r, b); 11817 p.invalidateChild(this, damage); 11818 } 11819 11820 // Damage the entire projection receiver, if necessary. 11821 if (mBackground != null && mBackground.isProjected()) { 11822 final View receiver = getProjectionReceiver(); 11823 if (receiver != null) { 11824 receiver.damageInParent(); 11825 } 11826 } 11827 11828 // Damage the entire IsolatedZVolume receiving this view's shadow. 11829 if (isHardwareAccelerated() && getZ() != 0) { 11830 damageShadowReceiver(); 11831 } 11832 } 11833 } 11834 11835 /** 11836 * @return this view's projection receiver, or {@code null} if none exists 11837 */ 11838 private View getProjectionReceiver() { 11839 ViewParent p = getParent(); 11840 while (p != null && p instanceof View) { 11841 final View v = (View) p; 11842 if (v.isProjectionReceiver()) { 11843 return v; 11844 } 11845 p = p.getParent(); 11846 } 11847 11848 return null; 11849 } 11850 11851 /** 11852 * @return whether the view is a projection receiver 11853 */ 11854 private boolean isProjectionReceiver() { 11855 return mBackground != null; 11856 } 11857 11858 /** 11859 * Damage area of the screen that can be covered by this View's shadow. 11860 * 11861 * This method will guarantee that any changes to shadows cast by a View 11862 * are damaged on the screen for future redraw. 11863 */ 11864 private void damageShadowReceiver() { 11865 final AttachInfo ai = mAttachInfo; 11866 if (ai != null) { 11867 ViewParent p = getParent(); 11868 if (p != null && p instanceof ViewGroup) { 11869 final ViewGroup vg = (ViewGroup) p; 11870 vg.damageInParent(); 11871 } 11872 } 11873 } 11874 11875 /** 11876 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11877 * set any flags or handle all of the cases handled by the default invalidation methods. 11878 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11879 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11880 * walk up the hierarchy, transforming the dirty rect as necessary. 11881 * 11882 * The method also handles normal invalidation logic if display list properties are not 11883 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11884 * backup approach, to handle these cases used in the various property-setting methods. 11885 * 11886 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11887 * are not being used in this view 11888 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11889 * list properties are not being used in this view 11890 */ 11891 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11892 if (!isHardwareAccelerated() 11893 || !mRenderNode.isValid() 11894 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11895 if (invalidateParent) { 11896 invalidateParentCaches(); 11897 } 11898 if (forceRedraw) { 11899 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11900 } 11901 invalidate(false); 11902 } else { 11903 damageInParent(); 11904 } 11905 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11906 damageShadowReceiver(); 11907 } 11908 } 11909 11910 /** 11911 * Tells the parent view to damage this view's bounds. 11912 * 11913 * @hide 11914 */ 11915 protected void damageInParent() { 11916 final AttachInfo ai = mAttachInfo; 11917 final ViewParent p = mParent; 11918 if (p != null && ai != null) { 11919 final Rect r = ai.mTmpInvalRect; 11920 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11921 if (mParent instanceof ViewGroup) { 11922 ((ViewGroup) mParent).damageChild(this, r); 11923 } else { 11924 mParent.invalidateChild(this, r); 11925 } 11926 } 11927 } 11928 11929 /** 11930 * Utility method to transform a given Rect by the current matrix of this view. 11931 */ 11932 void transformRect(final Rect rect) { 11933 if (!getMatrix().isIdentity()) { 11934 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11935 boundingRect.set(rect); 11936 getMatrix().mapRect(boundingRect); 11937 rect.set((int) Math.floor(boundingRect.left), 11938 (int) Math.floor(boundingRect.top), 11939 (int) Math.ceil(boundingRect.right), 11940 (int) Math.ceil(boundingRect.bottom)); 11941 } 11942 } 11943 11944 /** 11945 * Used to indicate that the parent of this view should clear its caches. This functionality 11946 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11947 * which is necessary when various parent-managed properties of the view change, such as 11948 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11949 * clears the parent caches and does not causes an invalidate event. 11950 * 11951 * @hide 11952 */ 11953 protected void invalidateParentCaches() { 11954 if (mParent instanceof View) { 11955 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11956 } 11957 } 11958 11959 /** 11960 * Used to indicate that the parent of this view should be invalidated. This functionality 11961 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11962 * which is necessary when various parent-managed properties of the view change, such as 11963 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11964 * an invalidation event to the parent. 11965 * 11966 * @hide 11967 */ 11968 protected void invalidateParentIfNeeded() { 11969 if (isHardwareAccelerated() && mParent instanceof View) { 11970 ((View) mParent).invalidate(true); 11971 } 11972 } 11973 11974 /** 11975 * @hide 11976 */ 11977 protected void invalidateParentIfNeededAndWasQuickRejected() { 11978 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11979 // View was rejected last time it was drawn by its parent; this may have changed 11980 invalidateParentIfNeeded(); 11981 } 11982 } 11983 11984 /** 11985 * Indicates whether this View is opaque. An opaque View guarantees that it will 11986 * draw all the pixels overlapping its bounds using a fully opaque color. 11987 * 11988 * Subclasses of View should override this method whenever possible to indicate 11989 * whether an instance is opaque. Opaque Views are treated in a special way by 11990 * the View hierarchy, possibly allowing it to perform optimizations during 11991 * invalidate/draw passes. 11992 * 11993 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11994 */ 11995 @ViewDebug.ExportedProperty(category = "drawing") 11996 public boolean isOpaque() { 11997 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11998 getFinalAlpha() >= 1.0f; 11999 } 12000 12001 /** 12002 * @hide 12003 */ 12004 protected void computeOpaqueFlags() { 12005 // Opaque if: 12006 // - Has a background 12007 // - Background is opaque 12008 // - Doesn't have scrollbars or scrollbars overlay 12009 12010 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 12011 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 12012 } else { 12013 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 12014 } 12015 12016 final int flags = mViewFlags; 12017 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 12018 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 12019 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 12020 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 12021 } else { 12022 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 12023 } 12024 } 12025 12026 /** 12027 * @hide 12028 */ 12029 protected boolean hasOpaqueScrollbars() { 12030 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 12031 } 12032 12033 /** 12034 * @return A handler associated with the thread running the View. This 12035 * handler can be used to pump events in the UI events queue. 12036 */ 12037 public Handler getHandler() { 12038 final AttachInfo attachInfo = mAttachInfo; 12039 if (attachInfo != null) { 12040 return attachInfo.mHandler; 12041 } 12042 return null; 12043 } 12044 12045 /** 12046 * Gets the view root associated with the View. 12047 * @return The view root, or null if none. 12048 * @hide 12049 */ 12050 public ViewRootImpl getViewRootImpl() { 12051 if (mAttachInfo != null) { 12052 return mAttachInfo.mViewRootImpl; 12053 } 12054 return null; 12055 } 12056 12057 /** 12058 * @hide 12059 */ 12060 public HardwareRenderer getHardwareRenderer() { 12061 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 12062 } 12063 12064 /** 12065 * <p>Causes the Runnable to be added to the message queue. 12066 * The runnable will be run on the user interface thread.</p> 12067 * 12068 * @param action The Runnable that will be executed. 12069 * 12070 * @return Returns true if the Runnable was successfully placed in to the 12071 * message queue. Returns false on failure, usually because the 12072 * looper processing the message queue is exiting. 12073 * 12074 * @see #postDelayed 12075 * @see #removeCallbacks 12076 */ 12077 public boolean post(Runnable action) { 12078 final AttachInfo attachInfo = mAttachInfo; 12079 if (attachInfo != null) { 12080 return attachInfo.mHandler.post(action); 12081 } 12082 // Assume that post will succeed later 12083 ViewRootImpl.getRunQueue().post(action); 12084 return true; 12085 } 12086 12087 /** 12088 * <p>Causes the Runnable to be added to the message queue, to be run 12089 * after the specified amount of time elapses. 12090 * The runnable will be run on the user interface thread.</p> 12091 * 12092 * @param action The Runnable that will be executed. 12093 * @param delayMillis The delay (in milliseconds) until the Runnable 12094 * will be executed. 12095 * 12096 * @return true if the Runnable was successfully placed in to the 12097 * message queue. Returns false on failure, usually because the 12098 * looper processing the message queue is exiting. Note that a 12099 * result of true does not mean the Runnable will be processed -- 12100 * if the looper is quit before the delivery time of the message 12101 * occurs then the message will be dropped. 12102 * 12103 * @see #post 12104 * @see #removeCallbacks 12105 */ 12106 public boolean postDelayed(Runnable action, long delayMillis) { 12107 final AttachInfo attachInfo = mAttachInfo; 12108 if (attachInfo != null) { 12109 return attachInfo.mHandler.postDelayed(action, delayMillis); 12110 } 12111 // Assume that post will succeed later 12112 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12113 return true; 12114 } 12115 12116 /** 12117 * <p>Causes the Runnable to execute on the next animation time step. 12118 * The runnable will be run on the user interface thread.</p> 12119 * 12120 * @param action The Runnable that will be executed. 12121 * 12122 * @see #postOnAnimationDelayed 12123 * @see #removeCallbacks 12124 */ 12125 public void postOnAnimation(Runnable action) { 12126 final AttachInfo attachInfo = mAttachInfo; 12127 if (attachInfo != null) { 12128 attachInfo.mViewRootImpl.mChoreographer.postCallback( 12129 Choreographer.CALLBACK_ANIMATION, action, null); 12130 } else { 12131 // Assume that post will succeed later 12132 ViewRootImpl.getRunQueue().post(action); 12133 } 12134 } 12135 12136 /** 12137 * <p>Causes the Runnable to execute on the next animation time step, 12138 * after the specified amount of time elapses. 12139 * The runnable will be run on the user interface thread.</p> 12140 * 12141 * @param action The Runnable that will be executed. 12142 * @param delayMillis The delay (in milliseconds) until the Runnable 12143 * will be executed. 12144 * 12145 * @see #postOnAnimation 12146 * @see #removeCallbacks 12147 */ 12148 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 12149 final AttachInfo attachInfo = mAttachInfo; 12150 if (attachInfo != null) { 12151 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12152 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 12153 } else { 12154 // Assume that post will succeed later 12155 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12156 } 12157 } 12158 12159 /** 12160 * <p>Removes the specified Runnable from the message queue.</p> 12161 * 12162 * @param action The Runnable to remove from the message handling queue 12163 * 12164 * @return true if this view could ask the Handler to remove the Runnable, 12165 * false otherwise. When the returned value is true, the Runnable 12166 * may or may not have been actually removed from the message queue 12167 * (for instance, if the Runnable was not in the queue already.) 12168 * 12169 * @see #post 12170 * @see #postDelayed 12171 * @see #postOnAnimation 12172 * @see #postOnAnimationDelayed 12173 */ 12174 public boolean removeCallbacks(Runnable action) { 12175 if (action != null) { 12176 final AttachInfo attachInfo = mAttachInfo; 12177 if (attachInfo != null) { 12178 attachInfo.mHandler.removeCallbacks(action); 12179 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12180 Choreographer.CALLBACK_ANIMATION, action, null); 12181 } 12182 // Assume that post will succeed later 12183 ViewRootImpl.getRunQueue().removeCallbacks(action); 12184 } 12185 return true; 12186 } 12187 12188 /** 12189 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 12190 * Use this to invalidate the View from a non-UI thread.</p> 12191 * 12192 * <p>This method can be invoked from outside of the UI thread 12193 * only when this View is attached to a window.</p> 12194 * 12195 * @see #invalidate() 12196 * @see #postInvalidateDelayed(long) 12197 */ 12198 public void postInvalidate() { 12199 postInvalidateDelayed(0); 12200 } 12201 12202 /** 12203 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12204 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 12205 * 12206 * <p>This method can be invoked from outside of the UI thread 12207 * only when this View is attached to a window.</p> 12208 * 12209 * @param left The left coordinate of the rectangle to invalidate. 12210 * @param top The top coordinate of the rectangle to invalidate. 12211 * @param right The right coordinate of the rectangle to invalidate. 12212 * @param bottom The bottom coordinate of the rectangle to invalidate. 12213 * 12214 * @see #invalidate(int, int, int, int) 12215 * @see #invalidate(Rect) 12216 * @see #postInvalidateDelayed(long, int, int, int, int) 12217 */ 12218 public void postInvalidate(int left, int top, int right, int bottom) { 12219 postInvalidateDelayed(0, left, top, right, bottom); 12220 } 12221 12222 /** 12223 * <p>Cause an invalidate to happen on a subsequent cycle through the event 12224 * loop. Waits for the specified amount of time.</p> 12225 * 12226 * <p>This method can be invoked from outside of the UI thread 12227 * only when this View is attached to a window.</p> 12228 * 12229 * @param delayMilliseconds the duration in milliseconds to delay the 12230 * invalidation by 12231 * 12232 * @see #invalidate() 12233 * @see #postInvalidate() 12234 */ 12235 public void postInvalidateDelayed(long delayMilliseconds) { 12236 // We try only with the AttachInfo because there's no point in invalidating 12237 // if we are not attached to our window 12238 final AttachInfo attachInfo = mAttachInfo; 12239 if (attachInfo != null) { 12240 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 12241 } 12242 } 12243 12244 /** 12245 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12246 * through the event loop. Waits for the specified amount of time.</p> 12247 * 12248 * <p>This method can be invoked from outside of the UI thread 12249 * only when this View is attached to a window.</p> 12250 * 12251 * @param delayMilliseconds the duration in milliseconds to delay the 12252 * invalidation by 12253 * @param left The left coordinate of the rectangle to invalidate. 12254 * @param top The top coordinate of the rectangle to invalidate. 12255 * @param right The right coordinate of the rectangle to invalidate. 12256 * @param bottom The bottom coordinate of the rectangle to invalidate. 12257 * 12258 * @see #invalidate(int, int, int, int) 12259 * @see #invalidate(Rect) 12260 * @see #postInvalidate(int, int, int, int) 12261 */ 12262 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 12263 int right, int bottom) { 12264 12265 // We try only with the AttachInfo because there's no point in invalidating 12266 // if we are not attached to our window 12267 final AttachInfo attachInfo = mAttachInfo; 12268 if (attachInfo != null) { 12269 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12270 info.target = this; 12271 info.left = left; 12272 info.top = top; 12273 info.right = right; 12274 info.bottom = bottom; 12275 12276 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 12277 } 12278 } 12279 12280 /** 12281 * <p>Cause an invalidate to happen on the next animation time step, typically the 12282 * next display frame.</p> 12283 * 12284 * <p>This method can be invoked from outside of the UI thread 12285 * only when this View is attached to a window.</p> 12286 * 12287 * @see #invalidate() 12288 */ 12289 public void postInvalidateOnAnimation() { 12290 // We try only with the AttachInfo because there's no point in invalidating 12291 // if we are not attached to our window 12292 final AttachInfo attachInfo = mAttachInfo; 12293 if (attachInfo != null) { 12294 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 12295 } 12296 } 12297 12298 /** 12299 * <p>Cause an invalidate of the specified area to happen on the next animation 12300 * time step, typically the next display frame.</p> 12301 * 12302 * <p>This method can be invoked from outside of the UI thread 12303 * only when this View is attached to a window.</p> 12304 * 12305 * @param left The left coordinate of the rectangle to invalidate. 12306 * @param top The top coordinate of the rectangle to invalidate. 12307 * @param right The right coordinate of the rectangle to invalidate. 12308 * @param bottom The bottom coordinate of the rectangle to invalidate. 12309 * 12310 * @see #invalidate(int, int, int, int) 12311 * @see #invalidate(Rect) 12312 */ 12313 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 12314 // We try only with the AttachInfo because there's no point in invalidating 12315 // if we are not attached to our window 12316 final AttachInfo attachInfo = mAttachInfo; 12317 if (attachInfo != null) { 12318 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12319 info.target = this; 12320 info.left = left; 12321 info.top = top; 12322 info.right = right; 12323 info.bottom = bottom; 12324 12325 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 12326 } 12327 } 12328 12329 /** 12330 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 12331 * This event is sent at most once every 12332 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 12333 */ 12334 private void postSendViewScrolledAccessibilityEventCallback() { 12335 if (mSendViewScrolledAccessibilityEvent == null) { 12336 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 12337 } 12338 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 12339 mSendViewScrolledAccessibilityEvent.mIsPending = true; 12340 postDelayed(mSendViewScrolledAccessibilityEvent, 12341 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 12342 } 12343 } 12344 12345 /** 12346 * Called by a parent to request that a child update its values for mScrollX 12347 * and mScrollY if necessary. This will typically be done if the child is 12348 * animating a scroll using a {@link android.widget.Scroller Scroller} 12349 * object. 12350 */ 12351 public void computeScroll() { 12352 } 12353 12354 /** 12355 * <p>Indicate whether the horizontal edges are faded when the view is 12356 * scrolled horizontally.</p> 12357 * 12358 * @return true if the horizontal edges should are faded on scroll, false 12359 * otherwise 12360 * 12361 * @see #setHorizontalFadingEdgeEnabled(boolean) 12362 * 12363 * @attr ref android.R.styleable#View_requiresFadingEdge 12364 */ 12365 public boolean isHorizontalFadingEdgeEnabled() { 12366 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 12367 } 12368 12369 /** 12370 * <p>Define whether the horizontal edges should be faded when this view 12371 * is scrolled horizontally.</p> 12372 * 12373 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12374 * be faded when the view is scrolled 12375 * horizontally 12376 * 12377 * @see #isHorizontalFadingEdgeEnabled() 12378 * 12379 * @attr ref android.R.styleable#View_requiresFadingEdge 12380 */ 12381 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12382 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12383 if (horizontalFadingEdgeEnabled) { 12384 initScrollCache(); 12385 } 12386 12387 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12388 } 12389 } 12390 12391 /** 12392 * <p>Indicate whether the vertical edges are faded when the view is 12393 * scrolled horizontally.</p> 12394 * 12395 * @return true if the vertical edges should are faded on scroll, false 12396 * otherwise 12397 * 12398 * @see #setVerticalFadingEdgeEnabled(boolean) 12399 * 12400 * @attr ref android.R.styleable#View_requiresFadingEdge 12401 */ 12402 public boolean isVerticalFadingEdgeEnabled() { 12403 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12404 } 12405 12406 /** 12407 * <p>Define whether the vertical edges should be faded when this view 12408 * is scrolled vertically.</p> 12409 * 12410 * @param verticalFadingEdgeEnabled true if the vertical edges should 12411 * be faded when the view is scrolled 12412 * vertically 12413 * 12414 * @see #isVerticalFadingEdgeEnabled() 12415 * 12416 * @attr ref android.R.styleable#View_requiresFadingEdge 12417 */ 12418 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12419 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12420 if (verticalFadingEdgeEnabled) { 12421 initScrollCache(); 12422 } 12423 12424 mViewFlags ^= FADING_EDGE_VERTICAL; 12425 } 12426 } 12427 12428 /** 12429 * Returns the strength, or intensity, of the top faded edge. The strength is 12430 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12431 * returns 0.0 or 1.0 but no value in between. 12432 * 12433 * Subclasses should override this method to provide a smoother fade transition 12434 * when scrolling occurs. 12435 * 12436 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12437 */ 12438 protected float getTopFadingEdgeStrength() { 12439 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12440 } 12441 12442 /** 12443 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12444 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12445 * returns 0.0 or 1.0 but no value in between. 12446 * 12447 * Subclasses should override this method to provide a smoother fade transition 12448 * when scrolling occurs. 12449 * 12450 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12451 */ 12452 protected float getBottomFadingEdgeStrength() { 12453 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12454 computeVerticalScrollRange() ? 1.0f : 0.0f; 12455 } 12456 12457 /** 12458 * Returns the strength, or intensity, of the left faded edge. The strength is 12459 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12460 * returns 0.0 or 1.0 but no value in between. 12461 * 12462 * Subclasses should override this method to provide a smoother fade transition 12463 * when scrolling occurs. 12464 * 12465 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12466 */ 12467 protected float getLeftFadingEdgeStrength() { 12468 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12469 } 12470 12471 /** 12472 * Returns the strength, or intensity, of the right faded edge. The strength is 12473 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12474 * returns 0.0 or 1.0 but no value in between. 12475 * 12476 * Subclasses should override this method to provide a smoother fade transition 12477 * when scrolling occurs. 12478 * 12479 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12480 */ 12481 protected float getRightFadingEdgeStrength() { 12482 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12483 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12484 } 12485 12486 /** 12487 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12488 * scrollbar is not drawn by default.</p> 12489 * 12490 * @return true if the horizontal scrollbar should be painted, false 12491 * otherwise 12492 * 12493 * @see #setHorizontalScrollBarEnabled(boolean) 12494 */ 12495 public boolean isHorizontalScrollBarEnabled() { 12496 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12497 } 12498 12499 /** 12500 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12501 * scrollbar is not drawn by default.</p> 12502 * 12503 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12504 * be painted 12505 * 12506 * @see #isHorizontalScrollBarEnabled() 12507 */ 12508 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12509 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12510 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12511 computeOpaqueFlags(); 12512 resolvePadding(); 12513 } 12514 } 12515 12516 /** 12517 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12518 * scrollbar is not drawn by default.</p> 12519 * 12520 * @return true if the vertical scrollbar should be painted, false 12521 * otherwise 12522 * 12523 * @see #setVerticalScrollBarEnabled(boolean) 12524 */ 12525 public boolean isVerticalScrollBarEnabled() { 12526 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12527 } 12528 12529 /** 12530 * <p>Define whether the vertical scrollbar should be drawn or not. The 12531 * scrollbar is not drawn by default.</p> 12532 * 12533 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12534 * be painted 12535 * 12536 * @see #isVerticalScrollBarEnabled() 12537 */ 12538 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12539 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12540 mViewFlags ^= SCROLLBARS_VERTICAL; 12541 computeOpaqueFlags(); 12542 resolvePadding(); 12543 } 12544 } 12545 12546 /** 12547 * @hide 12548 */ 12549 protected void recomputePadding() { 12550 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12551 } 12552 12553 /** 12554 * Define whether scrollbars will fade when the view is not scrolling. 12555 * 12556 * @param fadeScrollbars whether to enable fading 12557 * 12558 * @attr ref android.R.styleable#View_fadeScrollbars 12559 */ 12560 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12561 initScrollCache(); 12562 final ScrollabilityCache scrollabilityCache = mScrollCache; 12563 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12564 if (fadeScrollbars) { 12565 scrollabilityCache.state = ScrollabilityCache.OFF; 12566 } else { 12567 scrollabilityCache.state = ScrollabilityCache.ON; 12568 } 12569 } 12570 12571 /** 12572 * 12573 * Returns true if scrollbars will fade when this view is not scrolling 12574 * 12575 * @return true if scrollbar fading is enabled 12576 * 12577 * @attr ref android.R.styleable#View_fadeScrollbars 12578 */ 12579 public boolean isScrollbarFadingEnabled() { 12580 return mScrollCache != null && mScrollCache.fadeScrollBars; 12581 } 12582 12583 /** 12584 * 12585 * Returns the delay before scrollbars fade. 12586 * 12587 * @return the delay before scrollbars fade 12588 * 12589 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12590 */ 12591 public int getScrollBarDefaultDelayBeforeFade() { 12592 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12593 mScrollCache.scrollBarDefaultDelayBeforeFade; 12594 } 12595 12596 /** 12597 * Define the delay before scrollbars fade. 12598 * 12599 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12600 * 12601 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12602 */ 12603 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12604 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12605 } 12606 12607 /** 12608 * 12609 * Returns the scrollbar fade duration. 12610 * 12611 * @return the scrollbar fade duration 12612 * 12613 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12614 */ 12615 public int getScrollBarFadeDuration() { 12616 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12617 mScrollCache.scrollBarFadeDuration; 12618 } 12619 12620 /** 12621 * Define the scrollbar fade duration. 12622 * 12623 * @param scrollBarFadeDuration - the scrollbar fade duration 12624 * 12625 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12626 */ 12627 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12628 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12629 } 12630 12631 /** 12632 * 12633 * Returns the scrollbar size. 12634 * 12635 * @return the scrollbar size 12636 * 12637 * @attr ref android.R.styleable#View_scrollbarSize 12638 */ 12639 public int getScrollBarSize() { 12640 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12641 mScrollCache.scrollBarSize; 12642 } 12643 12644 /** 12645 * Define the scrollbar size. 12646 * 12647 * @param scrollBarSize - the scrollbar size 12648 * 12649 * @attr ref android.R.styleable#View_scrollbarSize 12650 */ 12651 public void setScrollBarSize(int scrollBarSize) { 12652 getScrollCache().scrollBarSize = scrollBarSize; 12653 } 12654 12655 /** 12656 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12657 * inset. When inset, they add to the padding of the view. And the scrollbars 12658 * can be drawn inside the padding area or on the edge of the view. For example, 12659 * if a view has a background drawable and you want to draw the scrollbars 12660 * inside the padding specified by the drawable, you can use 12661 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12662 * appear at the edge of the view, ignoring the padding, then you can use 12663 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12664 * @param style the style of the scrollbars. Should be one of 12665 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12666 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12667 * @see #SCROLLBARS_INSIDE_OVERLAY 12668 * @see #SCROLLBARS_INSIDE_INSET 12669 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12670 * @see #SCROLLBARS_OUTSIDE_INSET 12671 * 12672 * @attr ref android.R.styleable#View_scrollbarStyle 12673 */ 12674 public void setScrollBarStyle(@ScrollBarStyle int style) { 12675 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12676 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12677 computeOpaqueFlags(); 12678 resolvePadding(); 12679 } 12680 } 12681 12682 /** 12683 * <p>Returns the current scrollbar style.</p> 12684 * @return the current scrollbar style 12685 * @see #SCROLLBARS_INSIDE_OVERLAY 12686 * @see #SCROLLBARS_INSIDE_INSET 12687 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12688 * @see #SCROLLBARS_OUTSIDE_INSET 12689 * 12690 * @attr ref android.R.styleable#View_scrollbarStyle 12691 */ 12692 @ViewDebug.ExportedProperty(mapping = { 12693 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12694 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12695 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12696 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12697 }) 12698 @ScrollBarStyle 12699 public int getScrollBarStyle() { 12700 return mViewFlags & SCROLLBARS_STYLE_MASK; 12701 } 12702 12703 /** 12704 * <p>Compute the horizontal range that the horizontal scrollbar 12705 * represents.</p> 12706 * 12707 * <p>The range is expressed in arbitrary units that must be the same as the 12708 * units used by {@link #computeHorizontalScrollExtent()} and 12709 * {@link #computeHorizontalScrollOffset()}.</p> 12710 * 12711 * <p>The default range is the drawing width of this view.</p> 12712 * 12713 * @return the total horizontal range represented by the horizontal 12714 * scrollbar 12715 * 12716 * @see #computeHorizontalScrollExtent() 12717 * @see #computeHorizontalScrollOffset() 12718 * @see android.widget.ScrollBarDrawable 12719 */ 12720 protected int computeHorizontalScrollRange() { 12721 return getWidth(); 12722 } 12723 12724 /** 12725 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12726 * within the horizontal range. This value is used to compute the position 12727 * of the thumb within the scrollbar's track.</p> 12728 * 12729 * <p>The range is expressed in arbitrary units that must be the same as the 12730 * units used by {@link #computeHorizontalScrollRange()} and 12731 * {@link #computeHorizontalScrollExtent()}.</p> 12732 * 12733 * <p>The default offset is the scroll offset of this view.</p> 12734 * 12735 * @return the horizontal offset of the scrollbar's thumb 12736 * 12737 * @see #computeHorizontalScrollRange() 12738 * @see #computeHorizontalScrollExtent() 12739 * @see android.widget.ScrollBarDrawable 12740 */ 12741 protected int computeHorizontalScrollOffset() { 12742 return mScrollX; 12743 } 12744 12745 /** 12746 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12747 * within the horizontal range. This value is used to compute the length 12748 * of the thumb within the scrollbar's track.</p> 12749 * 12750 * <p>The range is expressed in arbitrary units that must be the same as the 12751 * units used by {@link #computeHorizontalScrollRange()} and 12752 * {@link #computeHorizontalScrollOffset()}.</p> 12753 * 12754 * <p>The default extent is the drawing width of this view.</p> 12755 * 12756 * @return the horizontal extent of the scrollbar's thumb 12757 * 12758 * @see #computeHorizontalScrollRange() 12759 * @see #computeHorizontalScrollOffset() 12760 * @see android.widget.ScrollBarDrawable 12761 */ 12762 protected int computeHorizontalScrollExtent() { 12763 return getWidth(); 12764 } 12765 12766 /** 12767 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12768 * 12769 * <p>The range is expressed in arbitrary units that must be the same as the 12770 * units used by {@link #computeVerticalScrollExtent()} and 12771 * {@link #computeVerticalScrollOffset()}.</p> 12772 * 12773 * @return the total vertical range represented by the vertical scrollbar 12774 * 12775 * <p>The default range is the drawing height of this view.</p> 12776 * 12777 * @see #computeVerticalScrollExtent() 12778 * @see #computeVerticalScrollOffset() 12779 * @see android.widget.ScrollBarDrawable 12780 */ 12781 protected int computeVerticalScrollRange() { 12782 return getHeight(); 12783 } 12784 12785 /** 12786 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12787 * within the horizontal range. This value is used to compute the position 12788 * of the thumb within the scrollbar's track.</p> 12789 * 12790 * <p>The range is expressed in arbitrary units that must be the same as the 12791 * units used by {@link #computeVerticalScrollRange()} and 12792 * {@link #computeVerticalScrollExtent()}.</p> 12793 * 12794 * <p>The default offset is the scroll offset of this view.</p> 12795 * 12796 * @return the vertical offset of the scrollbar's thumb 12797 * 12798 * @see #computeVerticalScrollRange() 12799 * @see #computeVerticalScrollExtent() 12800 * @see android.widget.ScrollBarDrawable 12801 */ 12802 protected int computeVerticalScrollOffset() { 12803 return mScrollY; 12804 } 12805 12806 /** 12807 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12808 * within the vertical range. This value is used to compute the length 12809 * of the thumb within the scrollbar's track.</p> 12810 * 12811 * <p>The range is expressed in arbitrary units that must be the same as the 12812 * units used by {@link #computeVerticalScrollRange()} and 12813 * {@link #computeVerticalScrollOffset()}.</p> 12814 * 12815 * <p>The default extent is the drawing height of this view.</p> 12816 * 12817 * @return the vertical extent of the scrollbar's thumb 12818 * 12819 * @see #computeVerticalScrollRange() 12820 * @see #computeVerticalScrollOffset() 12821 * @see android.widget.ScrollBarDrawable 12822 */ 12823 protected int computeVerticalScrollExtent() { 12824 return getHeight(); 12825 } 12826 12827 /** 12828 * Check if this view can be scrolled horizontally in a certain direction. 12829 * 12830 * @param direction Negative to check scrolling left, positive to check scrolling right. 12831 * @return true if this view can be scrolled in the specified direction, false otherwise. 12832 */ 12833 public boolean canScrollHorizontally(int direction) { 12834 final int offset = computeHorizontalScrollOffset(); 12835 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12836 if (range == 0) return false; 12837 if (direction < 0) { 12838 return offset > 0; 12839 } else { 12840 return offset < range - 1; 12841 } 12842 } 12843 12844 /** 12845 * Check if this view can be scrolled vertically in a certain direction. 12846 * 12847 * @param direction Negative to check scrolling up, positive to check scrolling down. 12848 * @return true if this view can be scrolled in the specified direction, false otherwise. 12849 */ 12850 public boolean canScrollVertically(int direction) { 12851 final int offset = computeVerticalScrollOffset(); 12852 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12853 if (range == 0) return false; 12854 if (direction < 0) { 12855 return offset > 0; 12856 } else { 12857 return offset < range - 1; 12858 } 12859 } 12860 12861 /** 12862 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12863 * scrollbars are painted only if they have been awakened first.</p> 12864 * 12865 * @param canvas the canvas on which to draw the scrollbars 12866 * 12867 * @see #awakenScrollBars(int) 12868 */ 12869 protected final void onDrawScrollBars(Canvas canvas) { 12870 // scrollbars are drawn only when the animation is running 12871 final ScrollabilityCache cache = mScrollCache; 12872 if (cache != null) { 12873 12874 int state = cache.state; 12875 12876 if (state == ScrollabilityCache.OFF) { 12877 return; 12878 } 12879 12880 boolean invalidate = false; 12881 12882 if (state == ScrollabilityCache.FADING) { 12883 // We're fading -- get our fade interpolation 12884 if (cache.interpolatorValues == null) { 12885 cache.interpolatorValues = new float[1]; 12886 } 12887 12888 float[] values = cache.interpolatorValues; 12889 12890 // Stops the animation if we're done 12891 if (cache.scrollBarInterpolator.timeToValues(values) == 12892 Interpolator.Result.FREEZE_END) { 12893 cache.state = ScrollabilityCache.OFF; 12894 } else { 12895 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 12896 } 12897 12898 // This will make the scroll bars inval themselves after 12899 // drawing. We only want this when we're fading so that 12900 // we prevent excessive redraws 12901 invalidate = true; 12902 } else { 12903 // We're just on -- but we may have been fading before so 12904 // reset alpha 12905 cache.scrollBar.mutate().setAlpha(255); 12906 } 12907 12908 12909 final int viewFlags = mViewFlags; 12910 12911 final boolean drawHorizontalScrollBar = 12912 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12913 final boolean drawVerticalScrollBar = 12914 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12915 && !isVerticalScrollBarHidden(); 12916 12917 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12918 final int width = mRight - mLeft; 12919 final int height = mBottom - mTop; 12920 12921 final ScrollBarDrawable scrollBar = cache.scrollBar; 12922 12923 final int scrollX = mScrollX; 12924 final int scrollY = mScrollY; 12925 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12926 12927 int left; 12928 int top; 12929 int right; 12930 int bottom; 12931 12932 if (drawHorizontalScrollBar) { 12933 int size = scrollBar.getSize(false); 12934 if (size <= 0) { 12935 size = cache.scrollBarSize; 12936 } 12937 12938 scrollBar.setParameters(computeHorizontalScrollRange(), 12939 computeHorizontalScrollOffset(), 12940 computeHorizontalScrollExtent(), false); 12941 final int verticalScrollBarGap = drawVerticalScrollBar ? 12942 getVerticalScrollbarWidth() : 0; 12943 top = scrollY + height - size - (mUserPaddingBottom & inside); 12944 left = scrollX + (mPaddingLeft & inside); 12945 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12946 bottom = top + size; 12947 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12948 if (invalidate) { 12949 invalidate(left, top, right, bottom); 12950 } 12951 } 12952 12953 if (drawVerticalScrollBar) { 12954 int size = scrollBar.getSize(true); 12955 if (size <= 0) { 12956 size = cache.scrollBarSize; 12957 } 12958 12959 scrollBar.setParameters(computeVerticalScrollRange(), 12960 computeVerticalScrollOffset(), 12961 computeVerticalScrollExtent(), true); 12962 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12963 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12964 verticalScrollbarPosition = isLayoutRtl() ? 12965 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12966 } 12967 switch (verticalScrollbarPosition) { 12968 default: 12969 case SCROLLBAR_POSITION_RIGHT: 12970 left = scrollX + width - size - (mUserPaddingRight & inside); 12971 break; 12972 case SCROLLBAR_POSITION_LEFT: 12973 left = scrollX + (mUserPaddingLeft & inside); 12974 break; 12975 } 12976 top = scrollY + (mPaddingTop & inside); 12977 right = left + size; 12978 bottom = scrollY + height - (mUserPaddingBottom & inside); 12979 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12980 if (invalidate) { 12981 invalidate(left, top, right, bottom); 12982 } 12983 } 12984 } 12985 } 12986 } 12987 12988 /** 12989 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12990 * FastScroller is visible. 12991 * @return whether to temporarily hide the vertical scrollbar 12992 * @hide 12993 */ 12994 protected boolean isVerticalScrollBarHidden() { 12995 return false; 12996 } 12997 12998 /** 12999 * <p>Draw the horizontal scrollbar if 13000 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 13001 * 13002 * @param canvas the canvas on which to draw the scrollbar 13003 * @param scrollBar the scrollbar's drawable 13004 * 13005 * @see #isHorizontalScrollBarEnabled() 13006 * @see #computeHorizontalScrollRange() 13007 * @see #computeHorizontalScrollExtent() 13008 * @see #computeHorizontalScrollOffset() 13009 * @see android.widget.ScrollBarDrawable 13010 * @hide 13011 */ 13012 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 13013 int l, int t, int r, int b) { 13014 scrollBar.setBounds(l, t, r, b); 13015 scrollBar.draw(canvas); 13016 } 13017 13018 /** 13019 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 13020 * returns true.</p> 13021 * 13022 * @param canvas the canvas on which to draw the scrollbar 13023 * @param scrollBar the scrollbar's drawable 13024 * 13025 * @see #isVerticalScrollBarEnabled() 13026 * @see #computeVerticalScrollRange() 13027 * @see #computeVerticalScrollExtent() 13028 * @see #computeVerticalScrollOffset() 13029 * @see android.widget.ScrollBarDrawable 13030 * @hide 13031 */ 13032 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 13033 int l, int t, int r, int b) { 13034 scrollBar.setBounds(l, t, r, b); 13035 scrollBar.draw(canvas); 13036 } 13037 13038 /** 13039 * Implement this to do your drawing. 13040 * 13041 * @param canvas the canvas on which the background will be drawn 13042 */ 13043 protected void onDraw(Canvas canvas) { 13044 } 13045 13046 /* 13047 * Caller is responsible for calling requestLayout if necessary. 13048 * (This allows addViewInLayout to not request a new layout.) 13049 */ 13050 void assignParent(ViewParent parent) { 13051 if (mParent == null) { 13052 mParent = parent; 13053 } else if (parent == null) { 13054 mParent = null; 13055 } else { 13056 throw new RuntimeException("view " + this + " being added, but" 13057 + " it already has a parent"); 13058 } 13059 } 13060 13061 /** 13062 * This is called when the view is attached to a window. At this point it 13063 * has a Surface and will start drawing. Note that this function is 13064 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 13065 * however it may be called any time before the first onDraw -- including 13066 * before or after {@link #onMeasure(int, int)}. 13067 * 13068 * @see #onDetachedFromWindow() 13069 */ 13070 protected void onAttachedToWindow() { 13071 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 13072 mParent.requestTransparentRegion(this); 13073 } 13074 13075 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 13076 initialAwakenScrollBars(); 13077 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 13078 } 13079 13080 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13081 13082 jumpDrawablesToCurrentState(); 13083 13084 resetSubtreeAccessibilityStateChanged(); 13085 13086 // rebuild, since Outline not maintained while View is detached 13087 rebuildOutline(); 13088 13089 if (isFocused()) { 13090 InputMethodManager imm = InputMethodManager.peekInstance(); 13091 imm.focusIn(this); 13092 } 13093 } 13094 13095 /** 13096 * Resolve all RTL related properties. 13097 * 13098 * @return true if resolution of RTL properties has been done 13099 * 13100 * @hide 13101 */ 13102 public boolean resolveRtlPropertiesIfNeeded() { 13103 if (!needRtlPropertiesResolution()) return false; 13104 13105 // Order is important here: LayoutDirection MUST be resolved first 13106 if (!isLayoutDirectionResolved()) { 13107 resolveLayoutDirection(); 13108 resolveLayoutParams(); 13109 } 13110 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 13111 if (!isTextDirectionResolved()) { 13112 resolveTextDirection(); 13113 } 13114 if (!isTextAlignmentResolved()) { 13115 resolveTextAlignment(); 13116 } 13117 // Should resolve Drawables before Padding because we need the layout direction of the 13118 // Drawable to correctly resolve Padding. 13119 if (!areDrawablesResolved()) { 13120 resolveDrawables(); 13121 } 13122 if (!isPaddingResolved()) { 13123 resolvePadding(); 13124 } 13125 onRtlPropertiesChanged(getLayoutDirection()); 13126 return true; 13127 } 13128 13129 /** 13130 * Reset resolution of all RTL related properties. 13131 * 13132 * @hide 13133 */ 13134 public void resetRtlProperties() { 13135 resetResolvedLayoutDirection(); 13136 resetResolvedTextDirection(); 13137 resetResolvedTextAlignment(); 13138 resetResolvedPadding(); 13139 resetResolvedDrawables(); 13140 } 13141 13142 /** 13143 * @see #onScreenStateChanged(int) 13144 */ 13145 void dispatchScreenStateChanged(int screenState) { 13146 onScreenStateChanged(screenState); 13147 } 13148 13149 /** 13150 * This method is called whenever the state of the screen this view is 13151 * attached to changes. A state change will usually occurs when the screen 13152 * turns on or off (whether it happens automatically or the user does it 13153 * manually.) 13154 * 13155 * @param screenState The new state of the screen. Can be either 13156 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 13157 */ 13158 public void onScreenStateChanged(int screenState) { 13159 } 13160 13161 /** 13162 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 13163 */ 13164 private boolean hasRtlSupport() { 13165 return mContext.getApplicationInfo().hasRtlSupport(); 13166 } 13167 13168 /** 13169 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 13170 * RTL not supported) 13171 */ 13172 private boolean isRtlCompatibilityMode() { 13173 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 13174 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 13175 } 13176 13177 /** 13178 * @return true if RTL properties need resolution. 13179 * 13180 */ 13181 private boolean needRtlPropertiesResolution() { 13182 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 13183 } 13184 13185 /** 13186 * Called when any RTL property (layout direction or text direction or text alignment) has 13187 * been changed. 13188 * 13189 * Subclasses need to override this method to take care of cached information that depends on the 13190 * resolved layout direction, or to inform child views that inherit their layout direction. 13191 * 13192 * The default implementation does nothing. 13193 * 13194 * @param layoutDirection the direction of the layout 13195 * 13196 * @see #LAYOUT_DIRECTION_LTR 13197 * @see #LAYOUT_DIRECTION_RTL 13198 */ 13199 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 13200 } 13201 13202 /** 13203 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 13204 * that the parent directionality can and will be resolved before its children. 13205 * 13206 * @return true if resolution has been done, false otherwise. 13207 * 13208 * @hide 13209 */ 13210 public boolean resolveLayoutDirection() { 13211 // Clear any previous layout direction resolution 13212 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13213 13214 if (hasRtlSupport()) { 13215 // Set resolved depending on layout direction 13216 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 13217 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 13218 case LAYOUT_DIRECTION_INHERIT: 13219 // We cannot resolve yet. LTR is by default and let the resolution happen again 13220 // later to get the correct resolved value 13221 if (!canResolveLayoutDirection()) return false; 13222 13223 // Parent has not yet resolved, LTR is still the default 13224 try { 13225 if (!mParent.isLayoutDirectionResolved()) return false; 13226 13227 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13228 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13229 } 13230 } catch (AbstractMethodError e) { 13231 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13232 " does not fully implement ViewParent", e); 13233 } 13234 break; 13235 case LAYOUT_DIRECTION_RTL: 13236 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13237 break; 13238 case LAYOUT_DIRECTION_LOCALE: 13239 if((LAYOUT_DIRECTION_RTL == 13240 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 13241 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13242 } 13243 break; 13244 default: 13245 // Nothing to do, LTR by default 13246 } 13247 } 13248 13249 // Set to resolved 13250 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13251 return true; 13252 } 13253 13254 /** 13255 * Check if layout direction resolution can be done. 13256 * 13257 * @return true if layout direction resolution can be done otherwise return false. 13258 */ 13259 public boolean canResolveLayoutDirection() { 13260 switch (getRawLayoutDirection()) { 13261 case LAYOUT_DIRECTION_INHERIT: 13262 if (mParent != null) { 13263 try { 13264 return mParent.canResolveLayoutDirection(); 13265 } catch (AbstractMethodError e) { 13266 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13267 " does not fully implement ViewParent", e); 13268 } 13269 } 13270 return false; 13271 13272 default: 13273 return true; 13274 } 13275 } 13276 13277 /** 13278 * Reset the resolved layout direction. Layout direction will be resolved during a call to 13279 * {@link #onMeasure(int, int)}. 13280 * 13281 * @hide 13282 */ 13283 public void resetResolvedLayoutDirection() { 13284 // Reset the current resolved bits 13285 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13286 } 13287 13288 /** 13289 * @return true if the layout direction is inherited. 13290 * 13291 * @hide 13292 */ 13293 public boolean isLayoutDirectionInherited() { 13294 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 13295 } 13296 13297 /** 13298 * @return true if layout direction has been resolved. 13299 */ 13300 public boolean isLayoutDirectionResolved() { 13301 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13302 } 13303 13304 /** 13305 * Return if padding has been resolved 13306 * 13307 * @hide 13308 */ 13309 boolean isPaddingResolved() { 13310 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 13311 } 13312 13313 /** 13314 * Resolves padding depending on layout direction, if applicable, and 13315 * recomputes internal padding values to adjust for scroll bars. 13316 * 13317 * @hide 13318 */ 13319 public void resolvePadding() { 13320 final int resolvedLayoutDirection = getLayoutDirection(); 13321 13322 if (!isRtlCompatibilityMode()) { 13323 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 13324 // If start / end padding are defined, they will be resolved (hence overriding) to 13325 // left / right or right / left depending on the resolved layout direction. 13326 // If start / end padding are not defined, use the left / right ones. 13327 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 13328 Rect padding = sThreadLocal.get(); 13329 if (padding == null) { 13330 padding = new Rect(); 13331 sThreadLocal.set(padding); 13332 } 13333 mBackground.getPadding(padding); 13334 if (!mLeftPaddingDefined) { 13335 mUserPaddingLeftInitial = padding.left; 13336 } 13337 if (!mRightPaddingDefined) { 13338 mUserPaddingRightInitial = padding.right; 13339 } 13340 } 13341 switch (resolvedLayoutDirection) { 13342 case LAYOUT_DIRECTION_RTL: 13343 if (mUserPaddingStart != UNDEFINED_PADDING) { 13344 mUserPaddingRight = mUserPaddingStart; 13345 } else { 13346 mUserPaddingRight = mUserPaddingRightInitial; 13347 } 13348 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13349 mUserPaddingLeft = mUserPaddingEnd; 13350 } else { 13351 mUserPaddingLeft = mUserPaddingLeftInitial; 13352 } 13353 break; 13354 case LAYOUT_DIRECTION_LTR: 13355 default: 13356 if (mUserPaddingStart != UNDEFINED_PADDING) { 13357 mUserPaddingLeft = mUserPaddingStart; 13358 } else { 13359 mUserPaddingLeft = mUserPaddingLeftInitial; 13360 } 13361 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13362 mUserPaddingRight = mUserPaddingEnd; 13363 } else { 13364 mUserPaddingRight = mUserPaddingRightInitial; 13365 } 13366 } 13367 13368 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 13369 } 13370 13371 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13372 onRtlPropertiesChanged(resolvedLayoutDirection); 13373 13374 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 13375 } 13376 13377 /** 13378 * Reset the resolved layout direction. 13379 * 13380 * @hide 13381 */ 13382 public void resetResolvedPadding() { 13383 resetResolvedPaddingInternal(); 13384 } 13385 13386 /** 13387 * Used when we only want to reset *this* view's padding and not trigger overrides 13388 * in ViewGroup that reset children too. 13389 */ 13390 void resetResolvedPaddingInternal() { 13391 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13392 } 13393 13394 /** 13395 * This is called when the view is detached from a window. At this point it 13396 * no longer has a surface for drawing. 13397 * 13398 * @see #onAttachedToWindow() 13399 */ 13400 protected void onDetachedFromWindow() { 13401 } 13402 13403 /** 13404 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13405 * after onDetachedFromWindow(). 13406 * 13407 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13408 * The super method should be called at the end of the overridden method to ensure 13409 * subclasses are destroyed first 13410 * 13411 * @hide 13412 */ 13413 protected void onDetachedFromWindowInternal() { 13414 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13415 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13416 13417 removeUnsetPressCallback(); 13418 removeLongPressCallback(); 13419 removePerformClickCallback(); 13420 removeSendViewScrolledAccessibilityEventCallback(); 13421 stopNestedScroll(); 13422 13423 // Anything that started animating right before detach should already 13424 // be in its final state when re-attached. 13425 jumpDrawablesToCurrentState(); 13426 13427 destroyDrawingCache(); 13428 13429 cleanupDraw(); 13430 mCurrentAnimation = null; 13431 } 13432 13433 private void cleanupDraw() { 13434 resetDisplayList(); 13435 if (mAttachInfo != null) { 13436 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13437 } 13438 } 13439 13440 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13441 } 13442 13443 /** 13444 * @return The number of times this view has been attached to a window 13445 */ 13446 protected int getWindowAttachCount() { 13447 return mWindowAttachCount; 13448 } 13449 13450 /** 13451 * Retrieve a unique token identifying the window this view is attached to. 13452 * @return Return the window's token for use in 13453 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13454 */ 13455 public IBinder getWindowToken() { 13456 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13457 } 13458 13459 /** 13460 * Retrieve the {@link WindowId} for the window this view is 13461 * currently attached to. 13462 */ 13463 public WindowId getWindowId() { 13464 if (mAttachInfo == null) { 13465 return null; 13466 } 13467 if (mAttachInfo.mWindowId == null) { 13468 try { 13469 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13470 mAttachInfo.mWindowToken); 13471 mAttachInfo.mWindowId = new WindowId( 13472 mAttachInfo.mIWindowId); 13473 } catch (RemoteException e) { 13474 } 13475 } 13476 return mAttachInfo.mWindowId; 13477 } 13478 13479 /** 13480 * Retrieve a unique token identifying the top-level "real" window of 13481 * the window that this view is attached to. That is, this is like 13482 * {@link #getWindowToken}, except if the window this view in is a panel 13483 * window (attached to another containing window), then the token of 13484 * the containing window is returned instead. 13485 * 13486 * @return Returns the associated window token, either 13487 * {@link #getWindowToken()} or the containing window's token. 13488 */ 13489 public IBinder getApplicationWindowToken() { 13490 AttachInfo ai = mAttachInfo; 13491 if (ai != null) { 13492 IBinder appWindowToken = ai.mPanelParentWindowToken; 13493 if (appWindowToken == null) { 13494 appWindowToken = ai.mWindowToken; 13495 } 13496 return appWindowToken; 13497 } 13498 return null; 13499 } 13500 13501 /** 13502 * Gets the logical display to which the view's window has been attached. 13503 * 13504 * @return The logical display, or null if the view is not currently attached to a window. 13505 */ 13506 public Display getDisplay() { 13507 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13508 } 13509 13510 /** 13511 * Retrieve private session object this view hierarchy is using to 13512 * communicate with the window manager. 13513 * @return the session object to communicate with the window manager 13514 */ 13515 /*package*/ IWindowSession getWindowSession() { 13516 return mAttachInfo != null ? mAttachInfo.mSession : null; 13517 } 13518 13519 /** 13520 * @param info the {@link android.view.View.AttachInfo} to associated with 13521 * this view 13522 */ 13523 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13524 //System.out.println("Attached! " + this); 13525 mAttachInfo = info; 13526 if (mOverlay != null) { 13527 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13528 } 13529 mWindowAttachCount++; 13530 // We will need to evaluate the drawable state at least once. 13531 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13532 if (mFloatingTreeObserver != null) { 13533 info.mTreeObserver.merge(mFloatingTreeObserver); 13534 mFloatingTreeObserver = null; 13535 } 13536 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13537 mAttachInfo.mScrollContainers.add(this); 13538 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13539 } 13540 performCollectViewAttributes(mAttachInfo, visibility); 13541 onAttachedToWindow(); 13542 13543 ListenerInfo li = mListenerInfo; 13544 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13545 li != null ? li.mOnAttachStateChangeListeners : null; 13546 if (listeners != null && listeners.size() > 0) { 13547 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13548 // perform the dispatching. The iterator is a safe guard against listeners that 13549 // could mutate the list by calling the various add/remove methods. This prevents 13550 // the array from being modified while we iterate it. 13551 for (OnAttachStateChangeListener listener : listeners) { 13552 listener.onViewAttachedToWindow(this); 13553 } 13554 } 13555 13556 int vis = info.mWindowVisibility; 13557 if (vis != GONE) { 13558 onWindowVisibilityChanged(vis); 13559 } 13560 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13561 // If nobody has evaluated the drawable state yet, then do it now. 13562 refreshDrawableState(); 13563 } 13564 needGlobalAttributesUpdate(false); 13565 } 13566 13567 void dispatchDetachedFromWindow() { 13568 AttachInfo info = mAttachInfo; 13569 if (info != null) { 13570 int vis = info.mWindowVisibility; 13571 if (vis != GONE) { 13572 onWindowVisibilityChanged(GONE); 13573 } 13574 } 13575 13576 onDetachedFromWindow(); 13577 onDetachedFromWindowInternal(); 13578 13579 ListenerInfo li = mListenerInfo; 13580 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13581 li != null ? li.mOnAttachStateChangeListeners : null; 13582 if (listeners != null && listeners.size() > 0) { 13583 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13584 // perform the dispatching. The iterator is a safe guard against listeners that 13585 // could mutate the list by calling the various add/remove methods. This prevents 13586 // the array from being modified while we iterate it. 13587 for (OnAttachStateChangeListener listener : listeners) { 13588 listener.onViewDetachedFromWindow(this); 13589 } 13590 } 13591 13592 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13593 mAttachInfo.mScrollContainers.remove(this); 13594 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13595 } 13596 13597 mAttachInfo = null; 13598 if (mOverlay != null) { 13599 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13600 } 13601 } 13602 13603 /** 13604 * Cancel any deferred high-level input events that were previously posted to the event queue. 13605 * 13606 * <p>Many views post high-level events such as click handlers to the event queue 13607 * to run deferred in order to preserve a desired user experience - clearing visible 13608 * pressed states before executing, etc. This method will abort any events of this nature 13609 * that are currently in flight.</p> 13610 * 13611 * <p>Custom views that generate their own high-level deferred input events should override 13612 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13613 * 13614 * <p>This will also cancel pending input events for any child views.</p> 13615 * 13616 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13617 * This will not impact newer events posted after this call that may occur as a result of 13618 * lower-level input events still waiting in the queue. If you are trying to prevent 13619 * double-submitted events for the duration of some sort of asynchronous transaction 13620 * you should also take other steps to protect against unexpected double inputs e.g. calling 13621 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13622 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13623 */ 13624 public final void cancelPendingInputEvents() { 13625 dispatchCancelPendingInputEvents(); 13626 } 13627 13628 /** 13629 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13630 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13631 */ 13632 void dispatchCancelPendingInputEvents() { 13633 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13634 onCancelPendingInputEvents(); 13635 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13636 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13637 " did not call through to super.onCancelPendingInputEvents()"); 13638 } 13639 } 13640 13641 /** 13642 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13643 * a parent view. 13644 * 13645 * <p>This method is responsible for removing any pending high-level input events that were 13646 * posted to the event queue to run later. Custom view classes that post their own deferred 13647 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13648 * {@link android.os.Handler} should override this method, call 13649 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13650 * </p> 13651 */ 13652 public void onCancelPendingInputEvents() { 13653 removePerformClickCallback(); 13654 cancelLongPress(); 13655 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13656 } 13657 13658 /** 13659 * Store this view hierarchy's frozen state into the given container. 13660 * 13661 * @param container The SparseArray in which to save the view's state. 13662 * 13663 * @see #restoreHierarchyState(android.util.SparseArray) 13664 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13665 * @see #onSaveInstanceState() 13666 */ 13667 public void saveHierarchyState(SparseArray<Parcelable> container) { 13668 dispatchSaveInstanceState(container); 13669 } 13670 13671 /** 13672 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13673 * this view and its children. May be overridden to modify how freezing happens to a 13674 * view's children; for example, some views may want to not store state for their children. 13675 * 13676 * @param container The SparseArray in which to save the view's state. 13677 * 13678 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13679 * @see #saveHierarchyState(android.util.SparseArray) 13680 * @see #onSaveInstanceState() 13681 */ 13682 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13683 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13684 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13685 Parcelable state = onSaveInstanceState(); 13686 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13687 throw new IllegalStateException( 13688 "Derived class did not call super.onSaveInstanceState()"); 13689 } 13690 if (state != null) { 13691 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13692 // + ": " + state); 13693 container.put(mID, state); 13694 } 13695 } 13696 } 13697 13698 /** 13699 * Hook allowing a view to generate a representation of its internal state 13700 * that can later be used to create a new instance with that same state. 13701 * This state should only contain information that is not persistent or can 13702 * not be reconstructed later. For example, you will never store your 13703 * current position on screen because that will be computed again when a 13704 * new instance of the view is placed in its view hierarchy. 13705 * <p> 13706 * Some examples of things you may store here: the current cursor position 13707 * in a text view (but usually not the text itself since that is stored in a 13708 * content provider or other persistent storage), the currently selected 13709 * item in a list view. 13710 * 13711 * @return Returns a Parcelable object containing the view's current dynamic 13712 * state, or null if there is nothing interesting to save. The 13713 * default implementation returns null. 13714 * @see #onRestoreInstanceState(android.os.Parcelable) 13715 * @see #saveHierarchyState(android.util.SparseArray) 13716 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13717 * @see #setSaveEnabled(boolean) 13718 */ 13719 protected Parcelable onSaveInstanceState() { 13720 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13721 return BaseSavedState.EMPTY_STATE; 13722 } 13723 13724 /** 13725 * Restore this view hierarchy's frozen state from the given container. 13726 * 13727 * @param container The SparseArray which holds previously frozen states. 13728 * 13729 * @see #saveHierarchyState(android.util.SparseArray) 13730 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13731 * @see #onRestoreInstanceState(android.os.Parcelable) 13732 */ 13733 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13734 dispatchRestoreInstanceState(container); 13735 } 13736 13737 /** 13738 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13739 * state for this view and its children. May be overridden to modify how restoring 13740 * happens to a view's children; for example, some views may want to not store state 13741 * for their children. 13742 * 13743 * @param container The SparseArray which holds previously saved state. 13744 * 13745 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13746 * @see #restoreHierarchyState(android.util.SparseArray) 13747 * @see #onRestoreInstanceState(android.os.Parcelable) 13748 */ 13749 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13750 if (mID != NO_ID) { 13751 Parcelable state = container.get(mID); 13752 if (state != null) { 13753 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13754 // + ": " + state); 13755 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13756 onRestoreInstanceState(state); 13757 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13758 throw new IllegalStateException( 13759 "Derived class did not call super.onRestoreInstanceState()"); 13760 } 13761 } 13762 } 13763 } 13764 13765 /** 13766 * Hook allowing a view to re-apply a representation of its internal state that had previously 13767 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13768 * null state. 13769 * 13770 * @param state The frozen state that had previously been returned by 13771 * {@link #onSaveInstanceState}. 13772 * 13773 * @see #onSaveInstanceState() 13774 * @see #restoreHierarchyState(android.util.SparseArray) 13775 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13776 */ 13777 protected void onRestoreInstanceState(Parcelable state) { 13778 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13779 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13780 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13781 + "received " + state.getClass().toString() + " instead. This usually happens " 13782 + "when two views of different type have the same id in the same hierarchy. " 13783 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13784 + "other views do not use the same id."); 13785 } 13786 } 13787 13788 /** 13789 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13790 * 13791 * @return the drawing start time in milliseconds 13792 */ 13793 public long getDrawingTime() { 13794 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13795 } 13796 13797 /** 13798 * <p>Enables or disables the duplication of the parent's state into this view. When 13799 * duplication is enabled, this view gets its drawable state from its parent rather 13800 * than from its own internal properties.</p> 13801 * 13802 * <p>Note: in the current implementation, setting this property to true after the 13803 * view was added to a ViewGroup might have no effect at all. This property should 13804 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13805 * 13806 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13807 * property is enabled, an exception will be thrown.</p> 13808 * 13809 * <p>Note: if the child view uses and updates additional states which are unknown to the 13810 * parent, these states should not be affected by this method.</p> 13811 * 13812 * @param enabled True to enable duplication of the parent's drawable state, false 13813 * to disable it. 13814 * 13815 * @see #getDrawableState() 13816 * @see #isDuplicateParentStateEnabled() 13817 */ 13818 public void setDuplicateParentStateEnabled(boolean enabled) { 13819 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13820 } 13821 13822 /** 13823 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13824 * 13825 * @return True if this view's drawable state is duplicated from the parent, 13826 * false otherwise 13827 * 13828 * @see #getDrawableState() 13829 * @see #setDuplicateParentStateEnabled(boolean) 13830 */ 13831 public boolean isDuplicateParentStateEnabled() { 13832 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13833 } 13834 13835 /** 13836 * <p>Specifies the type of layer backing this view. The layer can be 13837 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13838 * {@link #LAYER_TYPE_HARDWARE}.</p> 13839 * 13840 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13841 * instance that controls how the layer is composed on screen. The following 13842 * properties of the paint are taken into account when composing the layer:</p> 13843 * <ul> 13844 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13845 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13846 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13847 * </ul> 13848 * 13849 * <p>If this view has an alpha value set to < 1.0 by calling 13850 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 13851 * by this view's alpha value.</p> 13852 * 13853 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13854 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13855 * for more information on when and how to use layers.</p> 13856 * 13857 * @param layerType The type of layer to use with this view, must be one of 13858 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13859 * {@link #LAYER_TYPE_HARDWARE} 13860 * @param paint The paint used to compose the layer. This argument is optional 13861 * and can be null. It is ignored when the layer type is 13862 * {@link #LAYER_TYPE_NONE} 13863 * 13864 * @see #getLayerType() 13865 * @see #LAYER_TYPE_NONE 13866 * @see #LAYER_TYPE_SOFTWARE 13867 * @see #LAYER_TYPE_HARDWARE 13868 * @see #setAlpha(float) 13869 * 13870 * @attr ref android.R.styleable#View_layerType 13871 */ 13872 public void setLayerType(int layerType, Paint paint) { 13873 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13874 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13875 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13876 } 13877 13878 boolean typeChanged = mRenderNode.setLayerType(layerType); 13879 13880 if (!typeChanged) { 13881 setLayerPaint(paint); 13882 return; 13883 } 13884 13885 // Destroy any previous software drawing cache if needed 13886 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13887 destroyDrawingCache(); 13888 } 13889 13890 mLayerType = layerType; 13891 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13892 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13893 mRenderNode.setLayerPaint(mLayerPaint); 13894 13895 // draw() behaves differently if we are on a layer, so we need to 13896 // invalidate() here 13897 invalidateParentCaches(); 13898 invalidate(true); 13899 } 13900 13901 /** 13902 * Updates the {@link Paint} object used with the current layer (used only if the current 13903 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13904 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13905 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13906 * ensure that the view gets redrawn immediately. 13907 * 13908 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13909 * instance that controls how the layer is composed on screen. The following 13910 * properties of the paint are taken into account when composing the layer:</p> 13911 * <ul> 13912 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13913 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13914 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13915 * </ul> 13916 * 13917 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13918 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 13919 * 13920 * @param paint The paint used to compose the layer. This argument is optional 13921 * and can be null. It is ignored when the layer type is 13922 * {@link #LAYER_TYPE_NONE} 13923 * 13924 * @see #setLayerType(int, android.graphics.Paint) 13925 */ 13926 public void setLayerPaint(Paint paint) { 13927 int layerType = getLayerType(); 13928 if (layerType != LAYER_TYPE_NONE) { 13929 mLayerPaint = paint == null ? new Paint() : paint; 13930 if (layerType == LAYER_TYPE_HARDWARE) { 13931 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13932 invalidateViewProperty(false, false); 13933 } 13934 } else { 13935 invalidate(); 13936 } 13937 } 13938 } 13939 13940 /** 13941 * Indicates whether this view has a static layer. A view with layer type 13942 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13943 * dynamic. 13944 */ 13945 boolean hasStaticLayer() { 13946 return true; 13947 } 13948 13949 /** 13950 * Indicates what type of layer is currently associated with this view. By default 13951 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13952 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13953 * for more information on the different types of layers. 13954 * 13955 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13956 * {@link #LAYER_TYPE_HARDWARE} 13957 * 13958 * @see #setLayerType(int, android.graphics.Paint) 13959 * @see #buildLayer() 13960 * @see #LAYER_TYPE_NONE 13961 * @see #LAYER_TYPE_SOFTWARE 13962 * @see #LAYER_TYPE_HARDWARE 13963 */ 13964 public int getLayerType() { 13965 return mLayerType; 13966 } 13967 13968 /** 13969 * Forces this view's layer to be created and this view to be rendered 13970 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13971 * invoking this method will have no effect. 13972 * 13973 * This method can for instance be used to render a view into its layer before 13974 * starting an animation. If this view is complex, rendering into the layer 13975 * before starting the animation will avoid skipping frames. 13976 * 13977 * @throws IllegalStateException If this view is not attached to a window 13978 * 13979 * @see #setLayerType(int, android.graphics.Paint) 13980 */ 13981 public void buildLayer() { 13982 if (mLayerType == LAYER_TYPE_NONE) return; 13983 13984 final AttachInfo attachInfo = mAttachInfo; 13985 if (attachInfo == null) { 13986 throw new IllegalStateException("This view must be attached to a window first"); 13987 } 13988 13989 if (getWidth() == 0 || getHeight() == 0) { 13990 return; 13991 } 13992 13993 switch (mLayerType) { 13994 case LAYER_TYPE_HARDWARE: 13995 updateDisplayListIfDirty(); 13996 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 13997 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 13998 } 13999 break; 14000 case LAYER_TYPE_SOFTWARE: 14001 buildDrawingCache(true); 14002 break; 14003 } 14004 } 14005 14006 /** 14007 * If this View draws with a HardwareLayer, returns it. 14008 * Otherwise returns null 14009 * 14010 * TODO: Only TextureView uses this, can we eliminate it? 14011 */ 14012 HardwareLayer getHardwareLayer() { 14013 return null; 14014 } 14015 14016 /** 14017 * Destroys all hardware rendering resources. This method is invoked 14018 * when the system needs to reclaim resources. Upon execution of this 14019 * method, you should free any OpenGL resources created by the view. 14020 * 14021 * Note: you <strong>must</strong> call 14022 * <code>super.destroyHardwareResources()</code> when overriding 14023 * this method. 14024 * 14025 * @hide 14026 */ 14027 protected void destroyHardwareResources() { 14028 // Although the Layer will be destroyed by RenderNode, we want to release 14029 // the staging display list, which is also a signal to RenderNode that it's 14030 // safe to free its copy of the display list as it knows that we will 14031 // push an updated DisplayList if we try to draw again 14032 resetDisplayList(); 14033 } 14034 14035 /** 14036 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 14037 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 14038 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 14039 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 14040 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 14041 * null.</p> 14042 * 14043 * <p>Enabling the drawing cache is similar to 14044 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 14045 * acceleration is turned off. When hardware acceleration is turned on, enabling the 14046 * drawing cache has no effect on rendering because the system uses a different mechanism 14047 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 14048 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 14049 * for information on how to enable software and hardware layers.</p> 14050 * 14051 * <p>This API can be used to manually generate 14052 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 14053 * {@link #getDrawingCache()}.</p> 14054 * 14055 * @param enabled true to enable the drawing cache, false otherwise 14056 * 14057 * @see #isDrawingCacheEnabled() 14058 * @see #getDrawingCache() 14059 * @see #buildDrawingCache() 14060 * @see #setLayerType(int, android.graphics.Paint) 14061 */ 14062 public void setDrawingCacheEnabled(boolean enabled) { 14063 mCachingFailed = false; 14064 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 14065 } 14066 14067 /** 14068 * <p>Indicates whether the drawing cache is enabled for this view.</p> 14069 * 14070 * @return true if the drawing cache is enabled 14071 * 14072 * @see #setDrawingCacheEnabled(boolean) 14073 * @see #getDrawingCache() 14074 */ 14075 @ViewDebug.ExportedProperty(category = "drawing") 14076 public boolean isDrawingCacheEnabled() { 14077 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 14078 } 14079 14080 /** 14081 * Debugging utility which recursively outputs the dirty state of a view and its 14082 * descendants. 14083 * 14084 * @hide 14085 */ 14086 @SuppressWarnings({"UnusedDeclaration"}) 14087 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 14088 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 14089 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 14090 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 14091 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 14092 if (clear) { 14093 mPrivateFlags &= clearMask; 14094 } 14095 if (this instanceof ViewGroup) { 14096 ViewGroup parent = (ViewGroup) this; 14097 final int count = parent.getChildCount(); 14098 for (int i = 0; i < count; i++) { 14099 final View child = parent.getChildAt(i); 14100 child.outputDirtyFlags(indent + " ", clear, clearMask); 14101 } 14102 } 14103 } 14104 14105 /** 14106 * This method is used by ViewGroup to cause its children to restore or recreate their 14107 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 14108 * to recreate its own display list, which would happen if it went through the normal 14109 * draw/dispatchDraw mechanisms. 14110 * 14111 * @hide 14112 */ 14113 protected void dispatchGetDisplayList() {} 14114 14115 /** 14116 * A view that is not attached or hardware accelerated cannot create a display list. 14117 * This method checks these conditions and returns the appropriate result. 14118 * 14119 * @return true if view has the ability to create a display list, false otherwise. 14120 * 14121 * @hide 14122 */ 14123 public boolean canHaveDisplayList() { 14124 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 14125 } 14126 14127 private void updateDisplayListIfDirty() { 14128 final RenderNode renderNode = mRenderNode; 14129 if (!canHaveDisplayList()) { 14130 // can't populate RenderNode, don't try 14131 return; 14132 } 14133 14134 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 14135 || !renderNode.isValid() 14136 || (mRecreateDisplayList)) { 14137 // Don't need to recreate the display list, just need to tell our 14138 // children to restore/recreate theirs 14139 if (renderNode.isValid() 14140 && !mRecreateDisplayList) { 14141 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14142 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14143 dispatchGetDisplayList(); 14144 14145 return; // no work needed 14146 } 14147 14148 // If we got here, we're recreating it. Mark it as such to ensure that 14149 // we copy in child display lists into ours in drawChild() 14150 mRecreateDisplayList = true; 14151 14152 int width = mRight - mLeft; 14153 int height = mBottom - mTop; 14154 int layerType = getLayerType(); 14155 14156 final HardwareCanvas canvas = renderNode.start(width, height); 14157 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 14158 14159 try { 14160 final HardwareLayer layer = getHardwareLayer(); 14161 if (layer != null && layer.isValid()) { 14162 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 14163 } else if (layerType == LAYER_TYPE_SOFTWARE) { 14164 buildDrawingCache(true); 14165 Bitmap cache = getDrawingCache(true); 14166 if (cache != null) { 14167 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 14168 } 14169 } else { 14170 computeScroll(); 14171 14172 canvas.translate(-mScrollX, -mScrollY); 14173 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14174 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14175 14176 // Fast path for layouts with no backgrounds 14177 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14178 dispatchDraw(canvas); 14179 if (mOverlay != null && !mOverlay.isEmpty()) { 14180 mOverlay.getOverlayView().draw(canvas); 14181 } 14182 } else { 14183 draw(canvas); 14184 } 14185 } 14186 } finally { 14187 renderNode.end(canvas); 14188 setDisplayListProperties(renderNode); 14189 } 14190 } else { 14191 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14192 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14193 } 14194 } 14195 14196 /** 14197 * Returns a RenderNode with View draw content recorded, which can be 14198 * used to draw this view again without executing its draw method. 14199 * 14200 * @return A RenderNode ready to replay, or null if caching is not enabled. 14201 * 14202 * @hide 14203 */ 14204 public RenderNode getDisplayList() { 14205 updateDisplayListIfDirty(); 14206 return mRenderNode; 14207 } 14208 14209 private void resetDisplayList() { 14210 if (mRenderNode.isValid()) { 14211 mRenderNode.destroyDisplayListData(); 14212 } 14213 14214 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 14215 mBackgroundRenderNode.destroyDisplayListData(); 14216 } 14217 } 14218 14219 /** 14220 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 14221 * 14222 * @return A non-scaled bitmap representing this view or null if cache is disabled. 14223 * 14224 * @see #getDrawingCache(boolean) 14225 */ 14226 public Bitmap getDrawingCache() { 14227 return getDrawingCache(false); 14228 } 14229 14230 /** 14231 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 14232 * is null when caching is disabled. If caching is enabled and the cache is not ready, 14233 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 14234 * draw from the cache when the cache is enabled. To benefit from the cache, you must 14235 * request the drawing cache by calling this method and draw it on screen if the 14236 * returned bitmap is not null.</p> 14237 * 14238 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14239 * this method will create a bitmap of the same size as this view. Because this bitmap 14240 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14241 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14242 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14243 * size than the view. This implies that your application must be able to handle this 14244 * size.</p> 14245 * 14246 * @param autoScale Indicates whether the generated bitmap should be scaled based on 14247 * the current density of the screen when the application is in compatibility 14248 * mode. 14249 * 14250 * @return A bitmap representing this view or null if cache is disabled. 14251 * 14252 * @see #setDrawingCacheEnabled(boolean) 14253 * @see #isDrawingCacheEnabled() 14254 * @see #buildDrawingCache(boolean) 14255 * @see #destroyDrawingCache() 14256 */ 14257 public Bitmap getDrawingCache(boolean autoScale) { 14258 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14259 return null; 14260 } 14261 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14262 buildDrawingCache(autoScale); 14263 } 14264 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14265 } 14266 14267 /** 14268 * <p>Frees the resources used by the drawing cache. If you call 14269 * {@link #buildDrawingCache()} manually without calling 14270 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14271 * should cleanup the cache with this method afterwards.</p> 14272 * 14273 * @see #setDrawingCacheEnabled(boolean) 14274 * @see #buildDrawingCache() 14275 * @see #getDrawingCache() 14276 */ 14277 public void destroyDrawingCache() { 14278 if (mDrawingCache != null) { 14279 mDrawingCache.recycle(); 14280 mDrawingCache = null; 14281 } 14282 if (mUnscaledDrawingCache != null) { 14283 mUnscaledDrawingCache.recycle(); 14284 mUnscaledDrawingCache = null; 14285 } 14286 } 14287 14288 /** 14289 * Setting a solid background color for the drawing cache's bitmaps will improve 14290 * performance and memory usage. Note, though that this should only be used if this 14291 * view will always be drawn on top of a solid color. 14292 * 14293 * @param color The background color to use for the drawing cache's bitmap 14294 * 14295 * @see #setDrawingCacheEnabled(boolean) 14296 * @see #buildDrawingCache() 14297 * @see #getDrawingCache() 14298 */ 14299 public void setDrawingCacheBackgroundColor(int color) { 14300 if (color != mDrawingCacheBackgroundColor) { 14301 mDrawingCacheBackgroundColor = color; 14302 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14303 } 14304 } 14305 14306 /** 14307 * @see #setDrawingCacheBackgroundColor(int) 14308 * 14309 * @return The background color to used for the drawing cache's bitmap 14310 */ 14311 public int getDrawingCacheBackgroundColor() { 14312 return mDrawingCacheBackgroundColor; 14313 } 14314 14315 /** 14316 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14317 * 14318 * @see #buildDrawingCache(boolean) 14319 */ 14320 public void buildDrawingCache() { 14321 buildDrawingCache(false); 14322 } 14323 14324 /** 14325 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14326 * 14327 * <p>If you call {@link #buildDrawingCache()} manually without calling 14328 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14329 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14330 * 14331 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14332 * this method will create a bitmap of the same size as this view. Because this bitmap 14333 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14334 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14335 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14336 * size than the view. This implies that your application must be able to handle this 14337 * size.</p> 14338 * 14339 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14340 * you do not need the drawing cache bitmap, calling this method will increase memory 14341 * usage and cause the view to be rendered in software once, thus negatively impacting 14342 * performance.</p> 14343 * 14344 * @see #getDrawingCache() 14345 * @see #destroyDrawingCache() 14346 */ 14347 public void buildDrawingCache(boolean autoScale) { 14348 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14349 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14350 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 14351 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 14352 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 14353 } 14354 try { 14355 buildDrawingCacheImpl(autoScale); 14356 } finally { 14357 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 14358 } 14359 } 14360 } 14361 14362 /** 14363 * private, internal implementation of buildDrawingCache, used to enable tracing 14364 */ 14365 private void buildDrawingCacheImpl(boolean autoScale) { 14366 mCachingFailed = false; 14367 14368 int width = mRight - mLeft; 14369 int height = mBottom - mTop; 14370 14371 final AttachInfo attachInfo = mAttachInfo; 14372 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14373 14374 if (autoScale && scalingRequired) { 14375 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14376 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14377 } 14378 14379 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14380 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14381 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14382 14383 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14384 final long drawingCacheSize = 14385 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14386 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14387 if (width > 0 && height > 0) { 14388 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14389 + projectedBitmapSize + " bytes, only " 14390 + drawingCacheSize + " available"); 14391 } 14392 destroyDrawingCache(); 14393 mCachingFailed = true; 14394 return; 14395 } 14396 14397 boolean clear = true; 14398 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14399 14400 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14401 Bitmap.Config quality; 14402 if (!opaque) { 14403 // Never pick ARGB_4444 because it looks awful 14404 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14405 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14406 case DRAWING_CACHE_QUALITY_AUTO: 14407 case DRAWING_CACHE_QUALITY_LOW: 14408 case DRAWING_CACHE_QUALITY_HIGH: 14409 default: 14410 quality = Bitmap.Config.ARGB_8888; 14411 break; 14412 } 14413 } else { 14414 // Optimization for translucent windows 14415 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14416 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14417 } 14418 14419 // Try to cleanup memory 14420 if (bitmap != null) bitmap.recycle(); 14421 14422 try { 14423 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14424 width, height, quality); 14425 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14426 if (autoScale) { 14427 mDrawingCache = bitmap; 14428 } else { 14429 mUnscaledDrawingCache = bitmap; 14430 } 14431 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14432 } catch (OutOfMemoryError e) { 14433 // If there is not enough memory to create the bitmap cache, just 14434 // ignore the issue as bitmap caches are not required to draw the 14435 // view hierarchy 14436 if (autoScale) { 14437 mDrawingCache = null; 14438 } else { 14439 mUnscaledDrawingCache = null; 14440 } 14441 mCachingFailed = true; 14442 return; 14443 } 14444 14445 clear = drawingCacheBackgroundColor != 0; 14446 } 14447 14448 Canvas canvas; 14449 if (attachInfo != null) { 14450 canvas = attachInfo.mCanvas; 14451 if (canvas == null) { 14452 canvas = new Canvas(); 14453 } 14454 canvas.setBitmap(bitmap); 14455 // Temporarily clobber the cached Canvas in case one of our children 14456 // is also using a drawing cache. Without this, the children would 14457 // steal the canvas by attaching their own bitmap to it and bad, bad 14458 // thing would happen (invisible views, corrupted drawings, etc.) 14459 attachInfo.mCanvas = null; 14460 } else { 14461 // This case should hopefully never or seldom happen 14462 canvas = new Canvas(bitmap); 14463 } 14464 14465 if (clear) { 14466 bitmap.eraseColor(drawingCacheBackgroundColor); 14467 } 14468 14469 computeScroll(); 14470 final int restoreCount = canvas.save(); 14471 14472 if (autoScale && scalingRequired) { 14473 final float scale = attachInfo.mApplicationScale; 14474 canvas.scale(scale, scale); 14475 } 14476 14477 canvas.translate(-mScrollX, -mScrollY); 14478 14479 mPrivateFlags |= PFLAG_DRAWN; 14480 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14481 mLayerType != LAYER_TYPE_NONE) { 14482 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14483 } 14484 14485 // Fast path for layouts with no backgrounds 14486 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14487 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14488 dispatchDraw(canvas); 14489 if (mOverlay != null && !mOverlay.isEmpty()) { 14490 mOverlay.getOverlayView().draw(canvas); 14491 } 14492 } else { 14493 draw(canvas); 14494 } 14495 14496 canvas.restoreToCount(restoreCount); 14497 canvas.setBitmap(null); 14498 14499 if (attachInfo != null) { 14500 // Restore the cached Canvas for our siblings 14501 attachInfo.mCanvas = canvas; 14502 } 14503 } 14504 14505 /** 14506 * Create a snapshot of the view into a bitmap. We should probably make 14507 * some form of this public, but should think about the API. 14508 */ 14509 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14510 int width = mRight - mLeft; 14511 int height = mBottom - mTop; 14512 14513 final AttachInfo attachInfo = mAttachInfo; 14514 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14515 width = (int) ((width * scale) + 0.5f); 14516 height = (int) ((height * scale) + 0.5f); 14517 14518 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14519 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14520 if (bitmap == null) { 14521 throw new OutOfMemoryError(); 14522 } 14523 14524 Resources resources = getResources(); 14525 if (resources != null) { 14526 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14527 } 14528 14529 Canvas canvas; 14530 if (attachInfo != null) { 14531 canvas = attachInfo.mCanvas; 14532 if (canvas == null) { 14533 canvas = new Canvas(); 14534 } 14535 canvas.setBitmap(bitmap); 14536 // Temporarily clobber the cached Canvas in case one of our children 14537 // is also using a drawing cache. Without this, the children would 14538 // steal the canvas by attaching their own bitmap to it and bad, bad 14539 // things would happen (invisible views, corrupted drawings, etc.) 14540 attachInfo.mCanvas = null; 14541 } else { 14542 // This case should hopefully never or seldom happen 14543 canvas = new Canvas(bitmap); 14544 } 14545 14546 if ((backgroundColor & 0xff000000) != 0) { 14547 bitmap.eraseColor(backgroundColor); 14548 } 14549 14550 computeScroll(); 14551 final int restoreCount = canvas.save(); 14552 canvas.scale(scale, scale); 14553 canvas.translate(-mScrollX, -mScrollY); 14554 14555 // Temporarily remove the dirty mask 14556 int flags = mPrivateFlags; 14557 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14558 14559 // Fast path for layouts with no backgrounds 14560 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14561 dispatchDraw(canvas); 14562 if (mOverlay != null && !mOverlay.isEmpty()) { 14563 mOverlay.getOverlayView().draw(canvas); 14564 } 14565 } else { 14566 draw(canvas); 14567 } 14568 14569 mPrivateFlags = flags; 14570 14571 canvas.restoreToCount(restoreCount); 14572 canvas.setBitmap(null); 14573 14574 if (attachInfo != null) { 14575 // Restore the cached Canvas for our siblings 14576 attachInfo.mCanvas = canvas; 14577 } 14578 14579 return bitmap; 14580 } 14581 14582 /** 14583 * Indicates whether this View is currently in edit mode. A View is usually 14584 * in edit mode when displayed within a developer tool. For instance, if 14585 * this View is being drawn by a visual user interface builder, this method 14586 * should return true. 14587 * 14588 * Subclasses should check the return value of this method to provide 14589 * different behaviors if their normal behavior might interfere with the 14590 * host environment. For instance: the class spawns a thread in its 14591 * constructor, the drawing code relies on device-specific features, etc. 14592 * 14593 * This method is usually checked in the drawing code of custom widgets. 14594 * 14595 * @return True if this View is in edit mode, false otherwise. 14596 */ 14597 public boolean isInEditMode() { 14598 return false; 14599 } 14600 14601 /** 14602 * If the View draws content inside its padding and enables fading edges, 14603 * it needs to support padding offsets. Padding offsets are added to the 14604 * fading edges to extend the length of the fade so that it covers pixels 14605 * drawn inside the padding. 14606 * 14607 * Subclasses of this class should override this method if they need 14608 * to draw content inside the padding. 14609 * 14610 * @return True if padding offset must be applied, false otherwise. 14611 * 14612 * @see #getLeftPaddingOffset() 14613 * @see #getRightPaddingOffset() 14614 * @see #getTopPaddingOffset() 14615 * @see #getBottomPaddingOffset() 14616 * 14617 * @since CURRENT 14618 */ 14619 protected boolean isPaddingOffsetRequired() { 14620 return false; 14621 } 14622 14623 /** 14624 * Amount by which to extend the left fading region. Called only when 14625 * {@link #isPaddingOffsetRequired()} returns true. 14626 * 14627 * @return The left padding offset in pixels. 14628 * 14629 * @see #isPaddingOffsetRequired() 14630 * 14631 * @since CURRENT 14632 */ 14633 protected int getLeftPaddingOffset() { 14634 return 0; 14635 } 14636 14637 /** 14638 * Amount by which to extend the right fading region. Called only when 14639 * {@link #isPaddingOffsetRequired()} returns true. 14640 * 14641 * @return The right padding offset in pixels. 14642 * 14643 * @see #isPaddingOffsetRequired() 14644 * 14645 * @since CURRENT 14646 */ 14647 protected int getRightPaddingOffset() { 14648 return 0; 14649 } 14650 14651 /** 14652 * Amount by which to extend the top fading region. Called only when 14653 * {@link #isPaddingOffsetRequired()} returns true. 14654 * 14655 * @return The top padding offset in pixels. 14656 * 14657 * @see #isPaddingOffsetRequired() 14658 * 14659 * @since CURRENT 14660 */ 14661 protected int getTopPaddingOffset() { 14662 return 0; 14663 } 14664 14665 /** 14666 * Amount by which to extend the bottom fading region. Called only when 14667 * {@link #isPaddingOffsetRequired()} returns true. 14668 * 14669 * @return The bottom padding offset in pixels. 14670 * 14671 * @see #isPaddingOffsetRequired() 14672 * 14673 * @since CURRENT 14674 */ 14675 protected int getBottomPaddingOffset() { 14676 return 0; 14677 } 14678 14679 /** 14680 * @hide 14681 * @param offsetRequired 14682 */ 14683 protected int getFadeTop(boolean offsetRequired) { 14684 int top = mPaddingTop; 14685 if (offsetRequired) top += getTopPaddingOffset(); 14686 return top; 14687 } 14688 14689 /** 14690 * @hide 14691 * @param offsetRequired 14692 */ 14693 protected int getFadeHeight(boolean offsetRequired) { 14694 int padding = mPaddingTop; 14695 if (offsetRequired) padding += getTopPaddingOffset(); 14696 return mBottom - mTop - mPaddingBottom - padding; 14697 } 14698 14699 /** 14700 * <p>Indicates whether this view is attached to a hardware accelerated 14701 * window or not.</p> 14702 * 14703 * <p>Even if this method returns true, it does not mean that every call 14704 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14705 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14706 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14707 * window is hardware accelerated, 14708 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14709 * return false, and this method will return true.</p> 14710 * 14711 * @return True if the view is attached to a window and the window is 14712 * hardware accelerated; false in any other case. 14713 */ 14714 @ViewDebug.ExportedProperty(category = "drawing") 14715 public boolean isHardwareAccelerated() { 14716 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14717 } 14718 14719 /** 14720 * Sets a rectangular area on this view to which the view will be clipped 14721 * when it is drawn. Setting the value to null will remove the clip bounds 14722 * and the view will draw normally, using its full bounds. 14723 * 14724 * @param clipBounds The rectangular area, in the local coordinates of 14725 * this view, to which future drawing operations will be clipped. 14726 */ 14727 public void setClipBounds(Rect clipBounds) { 14728 if (clipBounds == mClipBounds 14729 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 14730 return; 14731 } 14732 if (clipBounds != null) { 14733 if (mClipBounds == null) { 14734 mClipBounds = new Rect(clipBounds); 14735 } else { 14736 mClipBounds.set(clipBounds); 14737 } 14738 } else { 14739 mClipBounds = null; 14740 } 14741 mRenderNode.setClipBounds(mClipBounds); 14742 invalidateViewProperty(false, false); 14743 } 14744 14745 /** 14746 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14747 * 14748 * @return A copy of the current clip bounds if clip bounds are set, 14749 * otherwise null. 14750 */ 14751 public Rect getClipBounds() { 14752 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14753 } 14754 14755 /** 14756 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14757 * case of an active Animation being run on the view. 14758 */ 14759 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14760 Animation a, boolean scalingRequired) { 14761 Transformation invalidationTransform; 14762 final int flags = parent.mGroupFlags; 14763 final boolean initialized = a.isInitialized(); 14764 if (!initialized) { 14765 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14766 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14767 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14768 onAnimationStart(); 14769 } 14770 14771 final Transformation t = parent.getChildTransformation(); 14772 boolean more = a.getTransformation(drawingTime, t, 1f); 14773 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14774 if (parent.mInvalidationTransformation == null) { 14775 parent.mInvalidationTransformation = new Transformation(); 14776 } 14777 invalidationTransform = parent.mInvalidationTransformation; 14778 a.getTransformation(drawingTime, invalidationTransform, 1f); 14779 } else { 14780 invalidationTransform = t; 14781 } 14782 14783 if (more) { 14784 if (!a.willChangeBounds()) { 14785 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14786 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14787 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14788 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14789 // The child need to draw an animation, potentially offscreen, so 14790 // make sure we do not cancel invalidate requests 14791 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14792 parent.invalidate(mLeft, mTop, mRight, mBottom); 14793 } 14794 } else { 14795 if (parent.mInvalidateRegion == null) { 14796 parent.mInvalidateRegion = new RectF(); 14797 } 14798 final RectF region = parent.mInvalidateRegion; 14799 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14800 invalidationTransform); 14801 14802 // The child need to draw an animation, potentially offscreen, so 14803 // make sure we do not cancel invalidate requests 14804 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14805 14806 final int left = mLeft + (int) region.left; 14807 final int top = mTop + (int) region.top; 14808 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14809 top + (int) (region.height() + .5f)); 14810 } 14811 } 14812 return more; 14813 } 14814 14815 /** 14816 * This method is called by getDisplayList() when a display list is recorded for a View. 14817 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14818 */ 14819 void setDisplayListProperties(RenderNode renderNode) { 14820 if (renderNode != null) { 14821 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14822 renderNode.setClipToBounds(mParent instanceof ViewGroup 14823 && ((ViewGroup) mParent).getClipChildren()); 14824 14825 float alpha = 1; 14826 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14827 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14828 ViewGroup parentVG = (ViewGroup) mParent; 14829 final Transformation t = parentVG.getChildTransformation(); 14830 if (parentVG.getChildStaticTransformation(this, t)) { 14831 final int transformType = t.getTransformationType(); 14832 if (transformType != Transformation.TYPE_IDENTITY) { 14833 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14834 alpha = t.getAlpha(); 14835 } 14836 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14837 renderNode.setStaticMatrix(t.getMatrix()); 14838 } 14839 } 14840 } 14841 } 14842 if (mTransformationInfo != null) { 14843 alpha *= getFinalAlpha(); 14844 if (alpha < 1) { 14845 final int multipliedAlpha = (int) (255 * alpha); 14846 if (onSetAlpha(multipliedAlpha)) { 14847 alpha = 1; 14848 } 14849 } 14850 renderNode.setAlpha(alpha); 14851 } else if (alpha < 1) { 14852 renderNode.setAlpha(alpha); 14853 } 14854 } 14855 } 14856 14857 /** 14858 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14859 * This draw() method is an implementation detail and is not intended to be overridden or 14860 * to be called from anywhere else other than ViewGroup.drawChild(). 14861 */ 14862 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14863 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14864 boolean more = false; 14865 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14866 final int flags = parent.mGroupFlags; 14867 14868 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14869 parent.getChildTransformation().clear(); 14870 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14871 } 14872 14873 Transformation transformToApply = null; 14874 boolean concatMatrix = false; 14875 14876 boolean scalingRequired = false; 14877 boolean caching; 14878 int layerType = getLayerType(); 14879 14880 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14881 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14882 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14883 caching = true; 14884 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14885 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14886 } else { 14887 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14888 } 14889 14890 final Animation a = getAnimation(); 14891 if (a != null) { 14892 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14893 concatMatrix = a.willChangeTransformationMatrix(); 14894 if (concatMatrix) { 14895 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14896 } 14897 transformToApply = parent.getChildTransformation(); 14898 } else { 14899 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14900 // No longer animating: clear out old animation matrix 14901 mRenderNode.setAnimationMatrix(null); 14902 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14903 } 14904 if (!usingRenderNodeProperties && 14905 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14906 final Transformation t = parent.getChildTransformation(); 14907 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14908 if (hasTransform) { 14909 final int transformType = t.getTransformationType(); 14910 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14911 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14912 } 14913 } 14914 } 14915 14916 concatMatrix |= !childHasIdentityMatrix; 14917 14918 // Sets the flag as early as possible to allow draw() implementations 14919 // to call invalidate() successfully when doing animations 14920 mPrivateFlags |= PFLAG_DRAWN; 14921 14922 if (!concatMatrix && 14923 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14924 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14925 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14926 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14927 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14928 return more; 14929 } 14930 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14931 14932 if (hardwareAccelerated) { 14933 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14934 // retain the flag's value temporarily in the mRecreateDisplayList flag 14935 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14936 mPrivateFlags &= ~PFLAG_INVALIDATED; 14937 } 14938 14939 RenderNode renderNode = null; 14940 Bitmap cache = null; 14941 boolean hasDisplayList = false; 14942 if (caching) { 14943 if (!hardwareAccelerated) { 14944 if (layerType != LAYER_TYPE_NONE) { 14945 layerType = LAYER_TYPE_SOFTWARE; 14946 buildDrawingCache(true); 14947 } 14948 cache = getDrawingCache(true); 14949 } else { 14950 switch (layerType) { 14951 case LAYER_TYPE_SOFTWARE: 14952 if (usingRenderNodeProperties) { 14953 hasDisplayList = canHaveDisplayList(); 14954 } else { 14955 buildDrawingCache(true); 14956 cache = getDrawingCache(true); 14957 } 14958 break; 14959 case LAYER_TYPE_HARDWARE: 14960 if (usingRenderNodeProperties) { 14961 hasDisplayList = canHaveDisplayList(); 14962 } 14963 break; 14964 case LAYER_TYPE_NONE: 14965 // Delay getting the display list until animation-driven alpha values are 14966 // set up and possibly passed on to the view 14967 hasDisplayList = canHaveDisplayList(); 14968 break; 14969 } 14970 } 14971 } 14972 usingRenderNodeProperties &= hasDisplayList; 14973 if (usingRenderNodeProperties) { 14974 renderNode = getDisplayList(); 14975 if (!renderNode.isValid()) { 14976 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14977 // to getDisplayList(), the display list will be marked invalid and we should not 14978 // try to use it again. 14979 renderNode = null; 14980 hasDisplayList = false; 14981 usingRenderNodeProperties = false; 14982 } 14983 } 14984 14985 int sx = 0; 14986 int sy = 0; 14987 if (!hasDisplayList) { 14988 computeScroll(); 14989 sx = mScrollX; 14990 sy = mScrollY; 14991 } 14992 14993 final boolean hasNoCache = cache == null || hasDisplayList; 14994 final boolean offsetForScroll = cache == null && !hasDisplayList && 14995 layerType != LAYER_TYPE_HARDWARE; 14996 14997 int restoreTo = -1; 14998 if (!usingRenderNodeProperties || transformToApply != null) { 14999 restoreTo = canvas.save(); 15000 } 15001 if (offsetForScroll) { 15002 canvas.translate(mLeft - sx, mTop - sy); 15003 } else { 15004 if (!usingRenderNodeProperties) { 15005 canvas.translate(mLeft, mTop); 15006 } 15007 if (scalingRequired) { 15008 if (usingRenderNodeProperties) { 15009 // TODO: Might not need this if we put everything inside the DL 15010 restoreTo = canvas.save(); 15011 } 15012 // mAttachInfo cannot be null, otherwise scalingRequired == false 15013 final float scale = 1.0f / mAttachInfo.mApplicationScale; 15014 canvas.scale(scale, scale); 15015 } 15016 } 15017 15018 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 15019 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 15020 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15021 if (transformToApply != null || !childHasIdentityMatrix) { 15022 int transX = 0; 15023 int transY = 0; 15024 15025 if (offsetForScroll) { 15026 transX = -sx; 15027 transY = -sy; 15028 } 15029 15030 if (transformToApply != null) { 15031 if (concatMatrix) { 15032 if (usingRenderNodeProperties) { 15033 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 15034 } else { 15035 // Undo the scroll translation, apply the transformation matrix, 15036 // then redo the scroll translate to get the correct result. 15037 canvas.translate(-transX, -transY); 15038 canvas.concat(transformToApply.getMatrix()); 15039 canvas.translate(transX, transY); 15040 } 15041 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15042 } 15043 15044 float transformAlpha = transformToApply.getAlpha(); 15045 if (transformAlpha < 1) { 15046 alpha *= transformAlpha; 15047 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15048 } 15049 } 15050 15051 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 15052 canvas.translate(-transX, -transY); 15053 canvas.concat(getMatrix()); 15054 canvas.translate(transX, transY); 15055 } 15056 } 15057 15058 // Deal with alpha if it is or used to be <1 15059 if (alpha < 1 || 15060 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 15061 if (alpha < 1) { 15062 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15063 } else { 15064 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 15065 } 15066 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15067 if (hasNoCache) { 15068 final int multipliedAlpha = (int) (255 * alpha); 15069 if (!onSetAlpha(multipliedAlpha)) { 15070 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15071 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 15072 layerType != LAYER_TYPE_NONE) { 15073 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 15074 } 15075 if (usingRenderNodeProperties) { 15076 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 15077 } else if (layerType == LAYER_TYPE_NONE) { 15078 final int scrollX = hasDisplayList ? 0 : sx; 15079 final int scrollY = hasDisplayList ? 0 : sy; 15080 canvas.saveLayerAlpha(scrollX, scrollY, 15081 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 15082 multipliedAlpha, layerFlags); 15083 } 15084 } else { 15085 // Alpha is handled by the child directly, clobber the layer's alpha 15086 mPrivateFlags |= PFLAG_ALPHA_SET; 15087 } 15088 } 15089 } 15090 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15091 onSetAlpha(255); 15092 mPrivateFlags &= ~PFLAG_ALPHA_SET; 15093 } 15094 15095 if (!usingRenderNodeProperties) { 15096 // apply clips directly, since RenderNode won't do it for this draw 15097 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 15098 && cache == null) { 15099 if (offsetForScroll) { 15100 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 15101 } else { 15102 if (!scalingRequired || cache == null) { 15103 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 15104 } else { 15105 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 15106 } 15107 } 15108 } 15109 15110 if (mClipBounds != null) { 15111 // clip bounds ignore scroll 15112 canvas.clipRect(mClipBounds); 15113 } 15114 } 15115 15116 15117 15118 if (!usingRenderNodeProperties && hasDisplayList) { 15119 renderNode = getDisplayList(); 15120 if (!renderNode.isValid()) { 15121 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15122 // to getDisplayList(), the display list will be marked invalid and we should not 15123 // try to use it again. 15124 renderNode = null; 15125 hasDisplayList = false; 15126 } 15127 } 15128 15129 if (hasNoCache) { 15130 boolean layerRendered = false; 15131 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 15132 final HardwareLayer layer = getHardwareLayer(); 15133 if (layer != null && layer.isValid()) { 15134 int restoreAlpha = mLayerPaint.getAlpha(); 15135 mLayerPaint.setAlpha((int) (alpha * 255)); 15136 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 15137 mLayerPaint.setAlpha(restoreAlpha); 15138 layerRendered = true; 15139 } else { 15140 final int scrollX = hasDisplayList ? 0 : sx; 15141 final int scrollY = hasDisplayList ? 0 : sy; 15142 canvas.saveLayer(scrollX, scrollY, 15143 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 15144 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 15145 } 15146 } 15147 15148 if (!layerRendered) { 15149 if (!hasDisplayList) { 15150 // Fast path for layouts with no backgrounds 15151 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15152 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15153 dispatchDraw(canvas); 15154 } else { 15155 draw(canvas); 15156 } 15157 } else { 15158 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15159 ((HardwareCanvas) canvas).drawRenderNode(renderNode, flags); 15160 } 15161 } 15162 } else if (cache != null) { 15163 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15164 Paint cachePaint; 15165 int restoreAlpha = 0; 15166 15167 if (layerType == LAYER_TYPE_NONE) { 15168 cachePaint = parent.mCachePaint; 15169 if (cachePaint == null) { 15170 cachePaint = new Paint(); 15171 cachePaint.setDither(false); 15172 parent.mCachePaint = cachePaint; 15173 } 15174 } else { 15175 cachePaint = mLayerPaint; 15176 restoreAlpha = mLayerPaint.getAlpha(); 15177 } 15178 cachePaint.setAlpha((int) (alpha * 255)); 15179 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 15180 cachePaint.setAlpha(restoreAlpha); 15181 } 15182 15183 if (restoreTo >= 0) { 15184 canvas.restoreToCount(restoreTo); 15185 } 15186 15187 if (a != null && !more) { 15188 if (!hardwareAccelerated && !a.getFillAfter()) { 15189 onSetAlpha(255); 15190 } 15191 parent.finishAnimatingView(this, a); 15192 } 15193 15194 if (more && hardwareAccelerated) { 15195 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15196 // alpha animations should cause the child to recreate its display list 15197 invalidate(true); 15198 } 15199 } 15200 15201 mRecreateDisplayList = false; 15202 15203 return more; 15204 } 15205 15206 /** 15207 * Manually render this view (and all of its children) to the given Canvas. 15208 * The view must have already done a full layout before this function is 15209 * called. When implementing a view, implement 15210 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 15211 * If you do need to override this method, call the superclass version. 15212 * 15213 * @param canvas The Canvas to which the View is rendered. 15214 */ 15215 public void draw(Canvas canvas) { 15216 final int privateFlags = mPrivateFlags; 15217 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 15218 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 15219 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 15220 15221 /* 15222 * Draw traversal performs several drawing steps which must be executed 15223 * in the appropriate order: 15224 * 15225 * 1. Draw the background 15226 * 2. If necessary, save the canvas' layers to prepare for fading 15227 * 3. Draw view's content 15228 * 4. Draw children 15229 * 5. If necessary, draw the fading edges and restore layers 15230 * 6. Draw decorations (scrollbars for instance) 15231 */ 15232 15233 // Step 1, draw the background, if needed 15234 int saveCount; 15235 15236 if (!dirtyOpaque) { 15237 drawBackground(canvas); 15238 } 15239 15240 // skip step 2 & 5 if possible (common case) 15241 final int viewFlags = mViewFlags; 15242 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 15243 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 15244 if (!verticalEdges && !horizontalEdges) { 15245 // Step 3, draw the content 15246 if (!dirtyOpaque) onDraw(canvas); 15247 15248 // Step 4, draw the children 15249 dispatchDraw(canvas); 15250 15251 // Step 6, draw decorations (scrollbars) 15252 onDrawScrollBars(canvas); 15253 15254 if (mOverlay != null && !mOverlay.isEmpty()) { 15255 mOverlay.getOverlayView().dispatchDraw(canvas); 15256 } 15257 15258 // we're done... 15259 return; 15260 } 15261 15262 /* 15263 * Here we do the full fledged routine... 15264 * (this is an uncommon case where speed matters less, 15265 * this is why we repeat some of the tests that have been 15266 * done above) 15267 */ 15268 15269 boolean drawTop = false; 15270 boolean drawBottom = false; 15271 boolean drawLeft = false; 15272 boolean drawRight = false; 15273 15274 float topFadeStrength = 0.0f; 15275 float bottomFadeStrength = 0.0f; 15276 float leftFadeStrength = 0.0f; 15277 float rightFadeStrength = 0.0f; 15278 15279 // Step 2, save the canvas' layers 15280 int paddingLeft = mPaddingLeft; 15281 15282 final boolean offsetRequired = isPaddingOffsetRequired(); 15283 if (offsetRequired) { 15284 paddingLeft += getLeftPaddingOffset(); 15285 } 15286 15287 int left = mScrollX + paddingLeft; 15288 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15289 int top = mScrollY + getFadeTop(offsetRequired); 15290 int bottom = top + getFadeHeight(offsetRequired); 15291 15292 if (offsetRequired) { 15293 right += getRightPaddingOffset(); 15294 bottom += getBottomPaddingOffset(); 15295 } 15296 15297 final ScrollabilityCache scrollabilityCache = mScrollCache; 15298 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15299 int length = (int) fadeHeight; 15300 15301 // clip the fade length if top and bottom fades overlap 15302 // overlapping fades produce odd-looking artifacts 15303 if (verticalEdges && (top + length > bottom - length)) { 15304 length = (bottom - top) / 2; 15305 } 15306 15307 // also clip horizontal fades if necessary 15308 if (horizontalEdges && (left + length > right - length)) { 15309 length = (right - left) / 2; 15310 } 15311 15312 if (verticalEdges) { 15313 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15314 drawTop = topFadeStrength * fadeHeight > 1.0f; 15315 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15316 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15317 } 15318 15319 if (horizontalEdges) { 15320 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15321 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15322 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15323 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15324 } 15325 15326 saveCount = canvas.getSaveCount(); 15327 15328 int solidColor = getSolidColor(); 15329 if (solidColor == 0) { 15330 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15331 15332 if (drawTop) { 15333 canvas.saveLayer(left, top, right, top + length, null, flags); 15334 } 15335 15336 if (drawBottom) { 15337 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15338 } 15339 15340 if (drawLeft) { 15341 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15342 } 15343 15344 if (drawRight) { 15345 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15346 } 15347 } else { 15348 scrollabilityCache.setFadeColor(solidColor); 15349 } 15350 15351 // Step 3, draw the content 15352 if (!dirtyOpaque) onDraw(canvas); 15353 15354 // Step 4, draw the children 15355 dispatchDraw(canvas); 15356 15357 // Step 5, draw the fade effect and restore layers 15358 final Paint p = scrollabilityCache.paint; 15359 final Matrix matrix = scrollabilityCache.matrix; 15360 final Shader fade = scrollabilityCache.shader; 15361 15362 if (drawTop) { 15363 matrix.setScale(1, fadeHeight * topFadeStrength); 15364 matrix.postTranslate(left, top); 15365 fade.setLocalMatrix(matrix); 15366 p.setShader(fade); 15367 canvas.drawRect(left, top, right, top + length, p); 15368 } 15369 15370 if (drawBottom) { 15371 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15372 matrix.postRotate(180); 15373 matrix.postTranslate(left, bottom); 15374 fade.setLocalMatrix(matrix); 15375 p.setShader(fade); 15376 canvas.drawRect(left, bottom - length, right, bottom, p); 15377 } 15378 15379 if (drawLeft) { 15380 matrix.setScale(1, fadeHeight * leftFadeStrength); 15381 matrix.postRotate(-90); 15382 matrix.postTranslate(left, top); 15383 fade.setLocalMatrix(matrix); 15384 p.setShader(fade); 15385 canvas.drawRect(left, top, left + length, bottom, p); 15386 } 15387 15388 if (drawRight) { 15389 matrix.setScale(1, fadeHeight * rightFadeStrength); 15390 matrix.postRotate(90); 15391 matrix.postTranslate(right, top); 15392 fade.setLocalMatrix(matrix); 15393 p.setShader(fade); 15394 canvas.drawRect(right - length, top, right, bottom, p); 15395 } 15396 15397 canvas.restoreToCount(saveCount); 15398 15399 // Step 6, draw decorations (scrollbars) 15400 onDrawScrollBars(canvas); 15401 15402 if (mOverlay != null && !mOverlay.isEmpty()) { 15403 mOverlay.getOverlayView().dispatchDraw(canvas); 15404 } 15405 } 15406 15407 /** 15408 * Draws the background onto the specified canvas. 15409 * 15410 * @param canvas Canvas on which to draw the background 15411 */ 15412 private void drawBackground(Canvas canvas) { 15413 final Drawable background = mBackground; 15414 if (background == null) { 15415 return; 15416 } 15417 15418 if (mBackgroundSizeChanged) { 15419 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15420 mBackgroundSizeChanged = false; 15421 rebuildOutline(); 15422 } 15423 15424 // Attempt to use a display list if requested. 15425 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15426 && mAttachInfo.mHardwareRenderer != null) { 15427 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15428 15429 final RenderNode renderNode = mBackgroundRenderNode; 15430 if (renderNode != null && renderNode.isValid()) { 15431 setBackgroundRenderNodeProperties(renderNode); 15432 ((HardwareCanvas) canvas).drawRenderNode(renderNode); 15433 return; 15434 } 15435 } 15436 15437 final int scrollX = mScrollX; 15438 final int scrollY = mScrollY; 15439 if ((scrollX | scrollY) == 0) { 15440 background.draw(canvas); 15441 } else { 15442 canvas.translate(scrollX, scrollY); 15443 background.draw(canvas); 15444 canvas.translate(-scrollX, -scrollY); 15445 } 15446 } 15447 15448 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 15449 renderNode.setTranslationX(mScrollX); 15450 renderNode.setTranslationY(mScrollY); 15451 } 15452 15453 /** 15454 * Creates a new display list or updates the existing display list for the 15455 * specified Drawable. 15456 * 15457 * @param drawable Drawable for which to create a display list 15458 * @param renderNode Existing RenderNode, or {@code null} 15459 * @return A valid display list for the specified drawable 15460 */ 15461 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15462 if (renderNode == null) { 15463 renderNode = RenderNode.create(drawable.getClass().getName(), this); 15464 } 15465 15466 final Rect bounds = drawable.getBounds(); 15467 final int width = bounds.width(); 15468 final int height = bounds.height(); 15469 final HardwareCanvas canvas = renderNode.start(width, height); 15470 15471 // Reverse left/top translation done by drawable canvas, which will 15472 // instead be applied by rendernode's LTRB bounds below. This way, the 15473 // drawable's bounds match with its rendernode bounds and its content 15474 // will lie within those bounds in the rendernode tree. 15475 canvas.translate(-bounds.left, -bounds.top); 15476 15477 try { 15478 drawable.draw(canvas); 15479 } finally { 15480 renderNode.end(canvas); 15481 } 15482 15483 // Set up drawable properties that are view-independent. 15484 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15485 renderNode.setProjectBackwards(drawable.isProjected()); 15486 renderNode.setProjectionReceiver(true); 15487 renderNode.setClipToBounds(false); 15488 return renderNode; 15489 } 15490 15491 /** 15492 * Returns the overlay for this view, creating it if it does not yet exist. 15493 * Adding drawables to the overlay will cause them to be displayed whenever 15494 * the view itself is redrawn. Objects in the overlay should be actively 15495 * managed: remove them when they should not be displayed anymore. The 15496 * overlay will always have the same size as its host view. 15497 * 15498 * <p>Note: Overlays do not currently work correctly with {@link 15499 * SurfaceView} or {@link TextureView}; contents in overlays for these 15500 * types of views may not display correctly.</p> 15501 * 15502 * @return The ViewOverlay object for this view. 15503 * @see ViewOverlay 15504 */ 15505 public ViewOverlay getOverlay() { 15506 if (mOverlay == null) { 15507 mOverlay = new ViewOverlay(mContext, this); 15508 } 15509 return mOverlay; 15510 } 15511 15512 /** 15513 * Override this if your view is known to always be drawn on top of a solid color background, 15514 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15515 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15516 * should be set to 0xFF. 15517 * 15518 * @see #setVerticalFadingEdgeEnabled(boolean) 15519 * @see #setHorizontalFadingEdgeEnabled(boolean) 15520 * 15521 * @return The known solid color background for this view, or 0 if the color may vary 15522 */ 15523 @ViewDebug.ExportedProperty(category = "drawing") 15524 public int getSolidColor() { 15525 return 0; 15526 } 15527 15528 /** 15529 * Build a human readable string representation of the specified view flags. 15530 * 15531 * @param flags the view flags to convert to a string 15532 * @return a String representing the supplied flags 15533 */ 15534 private static String printFlags(int flags) { 15535 String output = ""; 15536 int numFlags = 0; 15537 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15538 output += "TAKES_FOCUS"; 15539 numFlags++; 15540 } 15541 15542 switch (flags & VISIBILITY_MASK) { 15543 case INVISIBLE: 15544 if (numFlags > 0) { 15545 output += " "; 15546 } 15547 output += "INVISIBLE"; 15548 // USELESS HERE numFlags++; 15549 break; 15550 case GONE: 15551 if (numFlags > 0) { 15552 output += " "; 15553 } 15554 output += "GONE"; 15555 // USELESS HERE numFlags++; 15556 break; 15557 default: 15558 break; 15559 } 15560 return output; 15561 } 15562 15563 /** 15564 * Build a human readable string representation of the specified private 15565 * view flags. 15566 * 15567 * @param privateFlags the private view flags to convert to a string 15568 * @return a String representing the supplied flags 15569 */ 15570 private static String printPrivateFlags(int privateFlags) { 15571 String output = ""; 15572 int numFlags = 0; 15573 15574 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15575 output += "WANTS_FOCUS"; 15576 numFlags++; 15577 } 15578 15579 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15580 if (numFlags > 0) { 15581 output += " "; 15582 } 15583 output += "FOCUSED"; 15584 numFlags++; 15585 } 15586 15587 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15588 if (numFlags > 0) { 15589 output += " "; 15590 } 15591 output += "SELECTED"; 15592 numFlags++; 15593 } 15594 15595 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15596 if (numFlags > 0) { 15597 output += " "; 15598 } 15599 output += "IS_ROOT_NAMESPACE"; 15600 numFlags++; 15601 } 15602 15603 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15604 if (numFlags > 0) { 15605 output += " "; 15606 } 15607 output += "HAS_BOUNDS"; 15608 numFlags++; 15609 } 15610 15611 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15612 if (numFlags > 0) { 15613 output += " "; 15614 } 15615 output += "DRAWN"; 15616 // USELESS HERE numFlags++; 15617 } 15618 return output; 15619 } 15620 15621 /** 15622 * <p>Indicates whether or not this view's layout will be requested during 15623 * the next hierarchy layout pass.</p> 15624 * 15625 * @return true if the layout will be forced during next layout pass 15626 */ 15627 public boolean isLayoutRequested() { 15628 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15629 } 15630 15631 /** 15632 * Return true if o is a ViewGroup that is laying out using optical bounds. 15633 * @hide 15634 */ 15635 public static boolean isLayoutModeOptical(Object o) { 15636 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15637 } 15638 15639 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15640 Insets parentInsets = mParent instanceof View ? 15641 ((View) mParent).getOpticalInsets() : Insets.NONE; 15642 Insets childInsets = getOpticalInsets(); 15643 return setFrame( 15644 left + parentInsets.left - childInsets.left, 15645 top + parentInsets.top - childInsets.top, 15646 right + parentInsets.left + childInsets.right, 15647 bottom + parentInsets.top + childInsets.bottom); 15648 } 15649 15650 /** 15651 * Assign a size and position to a view and all of its 15652 * descendants 15653 * 15654 * <p>This is the second phase of the layout mechanism. 15655 * (The first is measuring). In this phase, each parent calls 15656 * layout on all of its children to position them. 15657 * This is typically done using the child measurements 15658 * that were stored in the measure pass().</p> 15659 * 15660 * <p>Derived classes should not override this method. 15661 * Derived classes with children should override 15662 * onLayout. In that method, they should 15663 * call layout on each of their children.</p> 15664 * 15665 * @param l Left position, relative to parent 15666 * @param t Top position, relative to parent 15667 * @param r Right position, relative to parent 15668 * @param b Bottom position, relative to parent 15669 */ 15670 @SuppressWarnings({"unchecked"}) 15671 public void layout(int l, int t, int r, int b) { 15672 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15673 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15674 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15675 } 15676 15677 int oldL = mLeft; 15678 int oldT = mTop; 15679 int oldB = mBottom; 15680 int oldR = mRight; 15681 15682 boolean changed = isLayoutModeOptical(mParent) ? 15683 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15684 15685 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15686 onLayout(changed, l, t, r, b); 15687 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15688 15689 ListenerInfo li = mListenerInfo; 15690 if (li != null && li.mOnLayoutChangeListeners != null) { 15691 ArrayList<OnLayoutChangeListener> listenersCopy = 15692 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15693 int numListeners = listenersCopy.size(); 15694 for (int i = 0; i < numListeners; ++i) { 15695 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15696 } 15697 } 15698 } 15699 15700 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15701 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15702 } 15703 15704 /** 15705 * Called from layout when this view should 15706 * assign a size and position to each of its children. 15707 * 15708 * Derived classes with children should override 15709 * this method and call layout on each of 15710 * their children. 15711 * @param changed This is a new size or position for this view 15712 * @param left Left position, relative to parent 15713 * @param top Top position, relative to parent 15714 * @param right Right position, relative to parent 15715 * @param bottom Bottom position, relative to parent 15716 */ 15717 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15718 } 15719 15720 /** 15721 * Assign a size and position to this view. 15722 * 15723 * This is called from layout. 15724 * 15725 * @param left Left position, relative to parent 15726 * @param top Top position, relative to parent 15727 * @param right Right position, relative to parent 15728 * @param bottom Bottom position, relative to parent 15729 * @return true if the new size and position are different than the 15730 * previous ones 15731 * {@hide} 15732 */ 15733 protected boolean setFrame(int left, int top, int right, int bottom) { 15734 boolean changed = false; 15735 15736 if (DBG) { 15737 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15738 + right + "," + bottom + ")"); 15739 } 15740 15741 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15742 changed = true; 15743 15744 // Remember our drawn bit 15745 int drawn = mPrivateFlags & PFLAG_DRAWN; 15746 15747 int oldWidth = mRight - mLeft; 15748 int oldHeight = mBottom - mTop; 15749 int newWidth = right - left; 15750 int newHeight = bottom - top; 15751 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15752 15753 // Invalidate our old position 15754 invalidate(sizeChanged); 15755 15756 mLeft = left; 15757 mTop = top; 15758 mRight = right; 15759 mBottom = bottom; 15760 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15761 15762 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15763 15764 15765 if (sizeChanged) { 15766 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15767 } 15768 15769 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 15770 // If we are visible, force the DRAWN bit to on so that 15771 // this invalidate will go through (at least to our parent). 15772 // This is because someone may have invalidated this view 15773 // before this call to setFrame came in, thereby clearing 15774 // the DRAWN bit. 15775 mPrivateFlags |= PFLAG_DRAWN; 15776 invalidate(sizeChanged); 15777 // parent display list may need to be recreated based on a change in the bounds 15778 // of any child 15779 invalidateParentCaches(); 15780 } 15781 15782 // Reset drawn bit to original value (invalidate turns it off) 15783 mPrivateFlags |= drawn; 15784 15785 mBackgroundSizeChanged = true; 15786 15787 notifySubtreeAccessibilityStateChangedIfNeeded(); 15788 } 15789 return changed; 15790 } 15791 15792 /** 15793 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 15794 * @hide 15795 */ 15796 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 15797 setFrame(left, top, right, bottom); 15798 } 15799 15800 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15801 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15802 if (mOverlay != null) { 15803 mOverlay.getOverlayView().setRight(newWidth); 15804 mOverlay.getOverlayView().setBottom(newHeight); 15805 } 15806 rebuildOutline(); 15807 } 15808 15809 /** 15810 * Finalize inflating a view from XML. This is called as the last phase 15811 * of inflation, after all child views have been added. 15812 * 15813 * <p>Even if the subclass overrides onFinishInflate, they should always be 15814 * sure to call the super method, so that we get called. 15815 */ 15816 protected void onFinishInflate() { 15817 } 15818 15819 /** 15820 * Returns the resources associated with this view. 15821 * 15822 * @return Resources object. 15823 */ 15824 public Resources getResources() { 15825 return mResources; 15826 } 15827 15828 /** 15829 * Invalidates the specified Drawable. 15830 * 15831 * @param drawable the drawable to invalidate 15832 */ 15833 @Override 15834 public void invalidateDrawable(@NonNull Drawable drawable) { 15835 if (verifyDrawable(drawable)) { 15836 final Rect dirty = drawable.getDirtyBounds(); 15837 final int scrollX = mScrollX; 15838 final int scrollY = mScrollY; 15839 15840 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15841 dirty.right + scrollX, dirty.bottom + scrollY); 15842 rebuildOutline(); 15843 } 15844 } 15845 15846 /** 15847 * Schedules an action on a drawable to occur at a specified time. 15848 * 15849 * @param who the recipient of the action 15850 * @param what the action to run on the drawable 15851 * @param when the time at which the action must occur. Uses the 15852 * {@link SystemClock#uptimeMillis} timebase. 15853 */ 15854 @Override 15855 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15856 if (verifyDrawable(who) && what != null) { 15857 final long delay = when - SystemClock.uptimeMillis(); 15858 if (mAttachInfo != null) { 15859 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15860 Choreographer.CALLBACK_ANIMATION, what, who, 15861 Choreographer.subtractFrameDelay(delay)); 15862 } else { 15863 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15864 } 15865 } 15866 } 15867 15868 /** 15869 * Cancels a scheduled action on a drawable. 15870 * 15871 * @param who the recipient of the action 15872 * @param what the action to cancel 15873 */ 15874 @Override 15875 public void unscheduleDrawable(Drawable who, Runnable what) { 15876 if (verifyDrawable(who) && what != null) { 15877 if (mAttachInfo != null) { 15878 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15879 Choreographer.CALLBACK_ANIMATION, what, who); 15880 } 15881 ViewRootImpl.getRunQueue().removeCallbacks(what); 15882 } 15883 } 15884 15885 /** 15886 * Unschedule any events associated with the given Drawable. This can be 15887 * used when selecting a new Drawable into a view, so that the previous 15888 * one is completely unscheduled. 15889 * 15890 * @param who The Drawable to unschedule. 15891 * 15892 * @see #drawableStateChanged 15893 */ 15894 public void unscheduleDrawable(Drawable who) { 15895 if (mAttachInfo != null && who != null) { 15896 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15897 Choreographer.CALLBACK_ANIMATION, null, who); 15898 } 15899 } 15900 15901 /** 15902 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15903 * that the View directionality can and will be resolved before its Drawables. 15904 * 15905 * Will call {@link View#onResolveDrawables} when resolution is done. 15906 * 15907 * @hide 15908 */ 15909 protected void resolveDrawables() { 15910 // Drawables resolution may need to happen before resolving the layout direction (which is 15911 // done only during the measure() call). 15912 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15913 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15914 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15915 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15916 // direction to be resolved as its resolved value will be the same as its raw value. 15917 if (!isLayoutDirectionResolved() && 15918 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15919 return; 15920 } 15921 15922 final int layoutDirection = isLayoutDirectionResolved() ? 15923 getLayoutDirection() : getRawLayoutDirection(); 15924 15925 if (mBackground != null) { 15926 mBackground.setLayoutDirection(layoutDirection); 15927 } 15928 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15929 onResolveDrawables(layoutDirection); 15930 } 15931 15932 boolean areDrawablesResolved() { 15933 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15934 } 15935 15936 /** 15937 * Called when layout direction has been resolved. 15938 * 15939 * The default implementation does nothing. 15940 * 15941 * @param layoutDirection The resolved layout direction. 15942 * 15943 * @see #LAYOUT_DIRECTION_LTR 15944 * @see #LAYOUT_DIRECTION_RTL 15945 * 15946 * @hide 15947 */ 15948 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15949 } 15950 15951 /** 15952 * @hide 15953 */ 15954 protected void resetResolvedDrawables() { 15955 resetResolvedDrawablesInternal(); 15956 } 15957 15958 void resetResolvedDrawablesInternal() { 15959 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15960 } 15961 15962 /** 15963 * If your view subclass is displaying its own Drawable objects, it should 15964 * override this function and return true for any Drawable it is 15965 * displaying. This allows animations for those drawables to be 15966 * scheduled. 15967 * 15968 * <p>Be sure to call through to the super class when overriding this 15969 * function. 15970 * 15971 * @param who The Drawable to verify. Return true if it is one you are 15972 * displaying, else return the result of calling through to the 15973 * super class. 15974 * 15975 * @return boolean If true than the Drawable is being displayed in the 15976 * view; else false and it is not allowed to animate. 15977 * 15978 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15979 * @see #drawableStateChanged() 15980 */ 15981 protected boolean verifyDrawable(Drawable who) { 15982 return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who); 15983 } 15984 15985 /** 15986 * This function is called whenever the state of the view changes in such 15987 * a way that it impacts the state of drawables being shown. 15988 * <p> 15989 * If the View has a StateListAnimator, it will also be called to run necessary state 15990 * change animations. 15991 * <p> 15992 * Be sure to call through to the superclass when overriding this function. 15993 * 15994 * @see Drawable#setState(int[]) 15995 */ 15996 protected void drawableStateChanged() { 15997 final int[] state = getDrawableState(); 15998 15999 final Drawable d = mBackground; 16000 if (d != null && d.isStateful()) { 16001 d.setState(state); 16002 } 16003 16004 if (mScrollCache != null) { 16005 final Drawable scrollBar = mScrollCache.scrollBar; 16006 if (scrollBar != null && scrollBar.isStateful()) { 16007 scrollBar.setState(state); 16008 } 16009 } 16010 16011 if (mStateListAnimator != null) { 16012 mStateListAnimator.setState(state); 16013 } 16014 } 16015 16016 /** 16017 * This function is called whenever the view hotspot changes and needs to 16018 * be propagated to drawables or child views managed by the view. 16019 * <p> 16020 * Dispatching to child views is handled by 16021 * {@link #dispatchDrawableHotspotChanged(float, float)}. 16022 * <p> 16023 * Be sure to call through to the superclass when overriding this function. 16024 * 16025 * @param x hotspot x coordinate 16026 * @param y hotspot y coordinate 16027 */ 16028 public void drawableHotspotChanged(float x, float y) { 16029 if (mBackground != null) { 16030 mBackground.setHotspot(x, y); 16031 } 16032 16033 dispatchDrawableHotspotChanged(x, y); 16034 } 16035 16036 /** 16037 * Dispatches drawableHotspotChanged to all of this View's children. 16038 * 16039 * @param x hotspot x coordinate 16040 * @param y hotspot y coordinate 16041 * @see #drawableHotspotChanged(float, float) 16042 */ 16043 public void dispatchDrawableHotspotChanged(float x, float y) { 16044 } 16045 16046 /** 16047 * Call this to force a view to update its drawable state. This will cause 16048 * drawableStateChanged to be called on this view. Views that are interested 16049 * in the new state should call getDrawableState. 16050 * 16051 * @see #drawableStateChanged 16052 * @see #getDrawableState 16053 */ 16054 public void refreshDrawableState() { 16055 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16056 drawableStateChanged(); 16057 16058 ViewParent parent = mParent; 16059 if (parent != null) { 16060 parent.childDrawableStateChanged(this); 16061 } 16062 } 16063 16064 /** 16065 * Return an array of resource IDs of the drawable states representing the 16066 * current state of the view. 16067 * 16068 * @return The current drawable state 16069 * 16070 * @see Drawable#setState(int[]) 16071 * @see #drawableStateChanged() 16072 * @see #onCreateDrawableState(int) 16073 */ 16074 public final int[] getDrawableState() { 16075 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 16076 return mDrawableState; 16077 } else { 16078 mDrawableState = onCreateDrawableState(0); 16079 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 16080 return mDrawableState; 16081 } 16082 } 16083 16084 /** 16085 * Generate the new {@link android.graphics.drawable.Drawable} state for 16086 * this view. This is called by the view 16087 * system when the cached Drawable state is determined to be invalid. To 16088 * retrieve the current state, you should use {@link #getDrawableState}. 16089 * 16090 * @param extraSpace if non-zero, this is the number of extra entries you 16091 * would like in the returned array in which you can place your own 16092 * states. 16093 * 16094 * @return Returns an array holding the current {@link Drawable} state of 16095 * the view. 16096 * 16097 * @see #mergeDrawableStates(int[], int[]) 16098 */ 16099 protected int[] onCreateDrawableState(int extraSpace) { 16100 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 16101 mParent instanceof View) { 16102 return ((View) mParent).onCreateDrawableState(extraSpace); 16103 } 16104 16105 int[] drawableState; 16106 16107 int privateFlags = mPrivateFlags; 16108 16109 int viewStateIndex = 0; 16110 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 16111 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 16112 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 16113 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 16114 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 16115 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 16116 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 16117 HardwareRenderer.isAvailable()) { 16118 // This is set if HW acceleration is requested, even if the current 16119 // process doesn't allow it. This is just to allow app preview 16120 // windows to better match their app. 16121 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 16122 } 16123 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 16124 16125 final int privateFlags2 = mPrivateFlags2; 16126 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 16127 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 16128 } 16129 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 16130 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 16131 } 16132 16133 drawableState = StateSet.get(viewStateIndex); 16134 16135 //noinspection ConstantIfStatement 16136 if (false) { 16137 Log.i("View", "drawableStateIndex=" + viewStateIndex); 16138 Log.i("View", toString() 16139 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 16140 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 16141 + " fo=" + hasFocus() 16142 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 16143 + " wf=" + hasWindowFocus() 16144 + ": " + Arrays.toString(drawableState)); 16145 } 16146 16147 if (extraSpace == 0) { 16148 return drawableState; 16149 } 16150 16151 final int[] fullState; 16152 if (drawableState != null) { 16153 fullState = new int[drawableState.length + extraSpace]; 16154 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 16155 } else { 16156 fullState = new int[extraSpace]; 16157 } 16158 16159 return fullState; 16160 } 16161 16162 /** 16163 * Merge your own state values in <var>additionalState</var> into the base 16164 * state values <var>baseState</var> that were returned by 16165 * {@link #onCreateDrawableState(int)}. 16166 * 16167 * @param baseState The base state values returned by 16168 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 16169 * own additional state values. 16170 * 16171 * @param additionalState The additional state values you would like 16172 * added to <var>baseState</var>; this array is not modified. 16173 * 16174 * @return As a convenience, the <var>baseState</var> array you originally 16175 * passed into the function is returned. 16176 * 16177 * @see #onCreateDrawableState(int) 16178 */ 16179 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 16180 final int N = baseState.length; 16181 int i = N - 1; 16182 while (i >= 0 && baseState[i] == 0) { 16183 i--; 16184 } 16185 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 16186 return baseState; 16187 } 16188 16189 /** 16190 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 16191 * on all Drawable objects associated with this view. 16192 * <p> 16193 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 16194 * attached to this view. 16195 */ 16196 public void jumpDrawablesToCurrentState() { 16197 if (mBackground != null) { 16198 mBackground.jumpToCurrentState(); 16199 } 16200 if (mStateListAnimator != null) { 16201 mStateListAnimator.jumpToCurrentState(); 16202 } 16203 } 16204 16205 /** 16206 * Sets the background color for this view. 16207 * @param color the color of the background 16208 */ 16209 @RemotableViewMethod 16210 public void setBackgroundColor(int color) { 16211 if (mBackground instanceof ColorDrawable) { 16212 ((ColorDrawable) mBackground.mutate()).setColor(color); 16213 computeOpaqueFlags(); 16214 mBackgroundResource = 0; 16215 } else { 16216 setBackground(new ColorDrawable(color)); 16217 } 16218 } 16219 16220 /** 16221 * If the view has a ColorDrawable background, returns the color of that 16222 * drawable. 16223 * 16224 * @return The color of the ColorDrawable background, if set, otherwise 0. 16225 */ 16226 public int getBackgroundColor() { 16227 if (mBackground instanceof ColorDrawable) { 16228 return ((ColorDrawable) mBackground).getColor(); 16229 } 16230 return 0; 16231 } 16232 16233 /** 16234 * Set the background to a given resource. The resource should refer to 16235 * a Drawable object or 0 to remove the background. 16236 * @param resid The identifier of the resource. 16237 * 16238 * @attr ref android.R.styleable#View_background 16239 */ 16240 @RemotableViewMethod 16241 public void setBackgroundResource(int resid) { 16242 if (resid != 0 && resid == mBackgroundResource) { 16243 return; 16244 } 16245 16246 Drawable d = null; 16247 if (resid != 0) { 16248 d = mContext.getDrawable(resid); 16249 } 16250 setBackground(d); 16251 16252 mBackgroundResource = resid; 16253 } 16254 16255 /** 16256 * Set the background to a given Drawable, or remove the background. If the 16257 * background has padding, this View's padding is set to the background's 16258 * padding. However, when a background is removed, this View's padding isn't 16259 * touched. If setting the padding is desired, please use 16260 * {@link #setPadding(int, int, int, int)}. 16261 * 16262 * @param background The Drawable to use as the background, or null to remove the 16263 * background 16264 */ 16265 public void setBackground(Drawable background) { 16266 //noinspection deprecation 16267 setBackgroundDrawable(background); 16268 } 16269 16270 /** 16271 * @deprecated use {@link #setBackground(Drawable)} instead 16272 */ 16273 @Deprecated 16274 public void setBackgroundDrawable(Drawable background) { 16275 computeOpaqueFlags(); 16276 16277 if (background == mBackground) { 16278 return; 16279 } 16280 16281 boolean requestLayout = false; 16282 16283 mBackgroundResource = 0; 16284 16285 /* 16286 * Regardless of whether we're setting a new background or not, we want 16287 * to clear the previous drawable. 16288 */ 16289 if (mBackground != null) { 16290 mBackground.setCallback(null); 16291 unscheduleDrawable(mBackground); 16292 } 16293 16294 if (background != null) { 16295 Rect padding = sThreadLocal.get(); 16296 if (padding == null) { 16297 padding = new Rect(); 16298 sThreadLocal.set(padding); 16299 } 16300 resetResolvedDrawablesInternal(); 16301 background.setLayoutDirection(getLayoutDirection()); 16302 if (background.getPadding(padding)) { 16303 resetResolvedPaddingInternal(); 16304 switch (background.getLayoutDirection()) { 16305 case LAYOUT_DIRECTION_RTL: 16306 mUserPaddingLeftInitial = padding.right; 16307 mUserPaddingRightInitial = padding.left; 16308 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 16309 break; 16310 case LAYOUT_DIRECTION_LTR: 16311 default: 16312 mUserPaddingLeftInitial = padding.left; 16313 mUserPaddingRightInitial = padding.right; 16314 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 16315 } 16316 mLeftPaddingDefined = false; 16317 mRightPaddingDefined = false; 16318 } 16319 16320 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 16321 // if it has a different minimum size, we should layout again 16322 if (mBackground == null 16323 || mBackground.getMinimumHeight() != background.getMinimumHeight() 16324 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16325 requestLayout = true; 16326 } 16327 16328 background.setCallback(this); 16329 if (background.isStateful()) { 16330 background.setState(getDrawableState()); 16331 } 16332 background.setVisible(getVisibility() == VISIBLE, false); 16333 mBackground = background; 16334 16335 applyBackgroundTint(); 16336 16337 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16338 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16339 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16340 requestLayout = true; 16341 } 16342 } else { 16343 /* Remove the background */ 16344 mBackground = null; 16345 16346 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16347 /* 16348 * This view ONLY drew the background before and we're removing 16349 * the background, so now it won't draw anything 16350 * (hence we SKIP_DRAW) 16351 */ 16352 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16353 mPrivateFlags |= PFLAG_SKIP_DRAW; 16354 } 16355 16356 /* 16357 * When the background is set, we try to apply its padding to this 16358 * View. When the background is removed, we don't touch this View's 16359 * padding. This is noted in the Javadocs. Hence, we don't need to 16360 * requestLayout(), the invalidate() below is sufficient. 16361 */ 16362 16363 // The old background's minimum size could have affected this 16364 // View's layout, so let's requestLayout 16365 requestLayout = true; 16366 } 16367 16368 computeOpaqueFlags(); 16369 16370 if (requestLayout) { 16371 requestLayout(); 16372 } 16373 16374 mBackgroundSizeChanged = true; 16375 invalidate(true); 16376 } 16377 16378 /** 16379 * Gets the background drawable 16380 * 16381 * @return The drawable used as the background for this view, if any. 16382 * 16383 * @see #setBackground(Drawable) 16384 * 16385 * @attr ref android.R.styleable#View_background 16386 */ 16387 public Drawable getBackground() { 16388 return mBackground; 16389 } 16390 16391 /** 16392 * Applies a tint to the background drawable. Does not modify the current tint 16393 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 16394 * <p> 16395 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 16396 * mutate the drawable and apply the specified tint and tint mode using 16397 * {@link Drawable#setTintList(ColorStateList)}. 16398 * 16399 * @param tint the tint to apply, may be {@code null} to clear tint 16400 * 16401 * @attr ref android.R.styleable#View_backgroundTint 16402 * @see #getBackgroundTintList() 16403 * @see Drawable#setTintList(ColorStateList) 16404 */ 16405 public void setBackgroundTintList(@Nullable ColorStateList tint) { 16406 if (mBackgroundTint == null) { 16407 mBackgroundTint = new TintInfo(); 16408 } 16409 mBackgroundTint.mTintList = tint; 16410 mBackgroundTint.mHasTintList = true; 16411 16412 applyBackgroundTint(); 16413 } 16414 16415 /** 16416 * Return the tint applied to the background drawable, if specified. 16417 * 16418 * @return the tint applied to the background drawable 16419 * @attr ref android.R.styleable#View_backgroundTint 16420 * @see #setBackgroundTintList(ColorStateList) 16421 */ 16422 @Nullable 16423 public ColorStateList getBackgroundTintList() { 16424 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 16425 } 16426 16427 /** 16428 * Specifies the blending mode used to apply the tint specified by 16429 * {@link #setBackgroundTintList(ColorStateList)}} to the background 16430 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 16431 * 16432 * @param tintMode the blending mode used to apply the tint, may be 16433 * {@code null} to clear tint 16434 * @attr ref android.R.styleable#View_backgroundTintMode 16435 * @see #getBackgroundTintMode() 16436 * @see Drawable#setTintMode(PorterDuff.Mode) 16437 */ 16438 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 16439 if (mBackgroundTint == null) { 16440 mBackgroundTint = new TintInfo(); 16441 } 16442 mBackgroundTint.mTintMode = tintMode; 16443 mBackgroundTint.mHasTintMode = true; 16444 16445 applyBackgroundTint(); 16446 } 16447 16448 /** 16449 * Return the blending mode used to apply the tint to the background 16450 * drawable, if specified. 16451 * 16452 * @return the blending mode used to apply the tint to the background 16453 * drawable 16454 * @attr ref android.R.styleable#View_backgroundTintMode 16455 * @see #setBackgroundTintMode(PorterDuff.Mode) 16456 */ 16457 @Nullable 16458 public PorterDuff.Mode getBackgroundTintMode() { 16459 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 16460 } 16461 16462 private void applyBackgroundTint() { 16463 if (mBackground != null && mBackgroundTint != null) { 16464 final TintInfo tintInfo = mBackgroundTint; 16465 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 16466 mBackground = mBackground.mutate(); 16467 16468 if (tintInfo.mHasTintList) { 16469 mBackground.setTintList(tintInfo.mTintList); 16470 } 16471 16472 if (tintInfo.mHasTintMode) { 16473 mBackground.setTintMode(tintInfo.mTintMode); 16474 } 16475 16476 // The drawable (or one of its children) may not have been 16477 // stateful before applying the tint, so let's try again. 16478 if (mBackground.isStateful()) { 16479 mBackground.setState(getDrawableState()); 16480 } 16481 } 16482 } 16483 } 16484 16485 /** 16486 * Sets the padding. The view may add on the space required to display 16487 * the scrollbars, depending on the style and visibility of the scrollbars. 16488 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16489 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16490 * from the values set in this call. 16491 * 16492 * @attr ref android.R.styleable#View_padding 16493 * @attr ref android.R.styleable#View_paddingBottom 16494 * @attr ref android.R.styleable#View_paddingLeft 16495 * @attr ref android.R.styleable#View_paddingRight 16496 * @attr ref android.R.styleable#View_paddingTop 16497 * @param left the left padding in pixels 16498 * @param top the top padding in pixels 16499 * @param right the right padding in pixels 16500 * @param bottom the bottom padding in pixels 16501 */ 16502 public void setPadding(int left, int top, int right, int bottom) { 16503 resetResolvedPaddingInternal(); 16504 16505 mUserPaddingStart = UNDEFINED_PADDING; 16506 mUserPaddingEnd = UNDEFINED_PADDING; 16507 16508 mUserPaddingLeftInitial = left; 16509 mUserPaddingRightInitial = right; 16510 16511 mLeftPaddingDefined = true; 16512 mRightPaddingDefined = true; 16513 16514 internalSetPadding(left, top, right, bottom); 16515 } 16516 16517 /** 16518 * @hide 16519 */ 16520 protected void internalSetPadding(int left, int top, int right, int bottom) { 16521 mUserPaddingLeft = left; 16522 mUserPaddingRight = right; 16523 mUserPaddingBottom = bottom; 16524 16525 final int viewFlags = mViewFlags; 16526 boolean changed = false; 16527 16528 // Common case is there are no scroll bars. 16529 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16530 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16531 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16532 ? 0 : getVerticalScrollbarWidth(); 16533 switch (mVerticalScrollbarPosition) { 16534 case SCROLLBAR_POSITION_DEFAULT: 16535 if (isLayoutRtl()) { 16536 left += offset; 16537 } else { 16538 right += offset; 16539 } 16540 break; 16541 case SCROLLBAR_POSITION_RIGHT: 16542 right += offset; 16543 break; 16544 case SCROLLBAR_POSITION_LEFT: 16545 left += offset; 16546 break; 16547 } 16548 } 16549 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16550 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16551 ? 0 : getHorizontalScrollbarHeight(); 16552 } 16553 } 16554 16555 if (mPaddingLeft != left) { 16556 changed = true; 16557 mPaddingLeft = left; 16558 } 16559 if (mPaddingTop != top) { 16560 changed = true; 16561 mPaddingTop = top; 16562 } 16563 if (mPaddingRight != right) { 16564 changed = true; 16565 mPaddingRight = right; 16566 } 16567 if (mPaddingBottom != bottom) { 16568 changed = true; 16569 mPaddingBottom = bottom; 16570 } 16571 16572 if (changed) { 16573 requestLayout(); 16574 invalidateOutline(); 16575 } 16576 } 16577 16578 /** 16579 * Sets the relative padding. The view may add on the space required to display 16580 * the scrollbars, depending on the style and visibility of the scrollbars. 16581 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16582 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16583 * from the values set in this call. 16584 * 16585 * @attr ref android.R.styleable#View_padding 16586 * @attr ref android.R.styleable#View_paddingBottom 16587 * @attr ref android.R.styleable#View_paddingStart 16588 * @attr ref android.R.styleable#View_paddingEnd 16589 * @attr ref android.R.styleable#View_paddingTop 16590 * @param start the start padding in pixels 16591 * @param top the top padding in pixels 16592 * @param end the end padding in pixels 16593 * @param bottom the bottom padding in pixels 16594 */ 16595 public void setPaddingRelative(int start, int top, int end, int bottom) { 16596 resetResolvedPaddingInternal(); 16597 16598 mUserPaddingStart = start; 16599 mUserPaddingEnd = end; 16600 mLeftPaddingDefined = true; 16601 mRightPaddingDefined = true; 16602 16603 switch(getLayoutDirection()) { 16604 case LAYOUT_DIRECTION_RTL: 16605 mUserPaddingLeftInitial = end; 16606 mUserPaddingRightInitial = start; 16607 internalSetPadding(end, top, start, bottom); 16608 break; 16609 case LAYOUT_DIRECTION_LTR: 16610 default: 16611 mUserPaddingLeftInitial = start; 16612 mUserPaddingRightInitial = end; 16613 internalSetPadding(start, top, end, bottom); 16614 } 16615 } 16616 16617 /** 16618 * Returns the top padding of this view. 16619 * 16620 * @return the top padding in pixels 16621 */ 16622 public int getPaddingTop() { 16623 return mPaddingTop; 16624 } 16625 16626 /** 16627 * Returns the bottom padding of this view. If there are inset and enabled 16628 * scrollbars, this value may include the space required to display the 16629 * scrollbars as well. 16630 * 16631 * @return the bottom padding in pixels 16632 */ 16633 public int getPaddingBottom() { 16634 return mPaddingBottom; 16635 } 16636 16637 /** 16638 * Returns the left padding of this view. If there are inset and enabled 16639 * scrollbars, this value may include the space required to display the 16640 * scrollbars as well. 16641 * 16642 * @return the left padding in pixels 16643 */ 16644 public int getPaddingLeft() { 16645 if (!isPaddingResolved()) { 16646 resolvePadding(); 16647 } 16648 return mPaddingLeft; 16649 } 16650 16651 /** 16652 * Returns the start padding of this view depending on its resolved layout direction. 16653 * If there are inset and enabled scrollbars, this value may include the space 16654 * required to display the scrollbars as well. 16655 * 16656 * @return the start padding in pixels 16657 */ 16658 public int getPaddingStart() { 16659 if (!isPaddingResolved()) { 16660 resolvePadding(); 16661 } 16662 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16663 mPaddingRight : mPaddingLeft; 16664 } 16665 16666 /** 16667 * Returns the right padding of this view. If there are inset and enabled 16668 * scrollbars, this value may include the space required to display the 16669 * scrollbars as well. 16670 * 16671 * @return the right padding in pixels 16672 */ 16673 public int getPaddingRight() { 16674 if (!isPaddingResolved()) { 16675 resolvePadding(); 16676 } 16677 return mPaddingRight; 16678 } 16679 16680 /** 16681 * Returns the end padding of this view depending on its resolved layout direction. 16682 * If there are inset and enabled scrollbars, this value may include the space 16683 * required to display the scrollbars as well. 16684 * 16685 * @return the end padding in pixels 16686 */ 16687 public int getPaddingEnd() { 16688 if (!isPaddingResolved()) { 16689 resolvePadding(); 16690 } 16691 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16692 mPaddingLeft : mPaddingRight; 16693 } 16694 16695 /** 16696 * Return if the padding has been set through relative values 16697 * {@link #setPaddingRelative(int, int, int, int)} or through 16698 * @attr ref android.R.styleable#View_paddingStart or 16699 * @attr ref android.R.styleable#View_paddingEnd 16700 * 16701 * @return true if the padding is relative or false if it is not. 16702 */ 16703 public boolean isPaddingRelative() { 16704 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16705 } 16706 16707 Insets computeOpticalInsets() { 16708 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16709 } 16710 16711 /** 16712 * @hide 16713 */ 16714 public void resetPaddingToInitialValues() { 16715 if (isRtlCompatibilityMode()) { 16716 mPaddingLeft = mUserPaddingLeftInitial; 16717 mPaddingRight = mUserPaddingRightInitial; 16718 return; 16719 } 16720 if (isLayoutRtl()) { 16721 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16722 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16723 } else { 16724 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16725 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16726 } 16727 } 16728 16729 /** 16730 * @hide 16731 */ 16732 public Insets getOpticalInsets() { 16733 if (mLayoutInsets == null) { 16734 mLayoutInsets = computeOpticalInsets(); 16735 } 16736 return mLayoutInsets; 16737 } 16738 16739 /** 16740 * Set this view's optical insets. 16741 * 16742 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16743 * property. Views that compute their own optical insets should call it as part of measurement. 16744 * This method does not request layout. If you are setting optical insets outside of 16745 * measure/layout itself you will want to call requestLayout() yourself. 16746 * </p> 16747 * @hide 16748 */ 16749 public void setOpticalInsets(Insets insets) { 16750 mLayoutInsets = insets; 16751 } 16752 16753 /** 16754 * Changes the selection state of this view. A view can be selected or not. 16755 * Note that selection is not the same as focus. Views are typically 16756 * selected in the context of an AdapterView like ListView or GridView; 16757 * the selected view is the view that is highlighted. 16758 * 16759 * @param selected true if the view must be selected, false otherwise 16760 */ 16761 public void setSelected(boolean selected) { 16762 //noinspection DoubleNegation 16763 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16764 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16765 if (!selected) resetPressedState(); 16766 invalidate(true); 16767 refreshDrawableState(); 16768 dispatchSetSelected(selected); 16769 if (selected) { 16770 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 16771 } else { 16772 notifyViewAccessibilityStateChangedIfNeeded( 16773 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16774 } 16775 } 16776 } 16777 16778 /** 16779 * Dispatch setSelected to all of this View's children. 16780 * 16781 * @see #setSelected(boolean) 16782 * 16783 * @param selected The new selected state 16784 */ 16785 protected void dispatchSetSelected(boolean selected) { 16786 } 16787 16788 /** 16789 * Indicates the selection state of this view. 16790 * 16791 * @return true if the view is selected, false otherwise 16792 */ 16793 @ViewDebug.ExportedProperty 16794 public boolean isSelected() { 16795 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16796 } 16797 16798 /** 16799 * Changes the activated state of this view. A view can be activated or not. 16800 * Note that activation is not the same as selection. Selection is 16801 * a transient property, representing the view (hierarchy) the user is 16802 * currently interacting with. Activation is a longer-term state that the 16803 * user can move views in and out of. For example, in a list view with 16804 * single or multiple selection enabled, the views in the current selection 16805 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16806 * here.) The activated state is propagated down to children of the view it 16807 * is set on. 16808 * 16809 * @param activated true if the view must be activated, false otherwise 16810 */ 16811 public void setActivated(boolean activated) { 16812 //noinspection DoubleNegation 16813 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16814 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16815 invalidate(true); 16816 refreshDrawableState(); 16817 dispatchSetActivated(activated); 16818 } 16819 } 16820 16821 /** 16822 * Dispatch setActivated to all of this View's children. 16823 * 16824 * @see #setActivated(boolean) 16825 * 16826 * @param activated The new activated state 16827 */ 16828 protected void dispatchSetActivated(boolean activated) { 16829 } 16830 16831 /** 16832 * Indicates the activation state of this view. 16833 * 16834 * @return true if the view is activated, false otherwise 16835 */ 16836 @ViewDebug.ExportedProperty 16837 public boolean isActivated() { 16838 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16839 } 16840 16841 /** 16842 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16843 * observer can be used to get notifications when global events, like 16844 * layout, happen. 16845 * 16846 * The returned ViewTreeObserver observer is not guaranteed to remain 16847 * valid for the lifetime of this View. If the caller of this method keeps 16848 * a long-lived reference to ViewTreeObserver, it should always check for 16849 * the return value of {@link ViewTreeObserver#isAlive()}. 16850 * 16851 * @return The ViewTreeObserver for this view's hierarchy. 16852 */ 16853 public ViewTreeObserver getViewTreeObserver() { 16854 if (mAttachInfo != null) { 16855 return mAttachInfo.mTreeObserver; 16856 } 16857 if (mFloatingTreeObserver == null) { 16858 mFloatingTreeObserver = new ViewTreeObserver(); 16859 } 16860 return mFloatingTreeObserver; 16861 } 16862 16863 /** 16864 * <p>Finds the topmost view in the current view hierarchy.</p> 16865 * 16866 * @return the topmost view containing this view 16867 */ 16868 public View getRootView() { 16869 if (mAttachInfo != null) { 16870 final View v = mAttachInfo.mRootView; 16871 if (v != null) { 16872 return v; 16873 } 16874 } 16875 16876 View parent = this; 16877 16878 while (parent.mParent != null && parent.mParent instanceof View) { 16879 parent = (View) parent.mParent; 16880 } 16881 16882 return parent; 16883 } 16884 16885 /** 16886 * Transforms a motion event from view-local coordinates to on-screen 16887 * coordinates. 16888 * 16889 * @param ev the view-local motion event 16890 * @return false if the transformation could not be applied 16891 * @hide 16892 */ 16893 public boolean toGlobalMotionEvent(MotionEvent ev) { 16894 final AttachInfo info = mAttachInfo; 16895 if (info == null) { 16896 return false; 16897 } 16898 16899 final Matrix m = info.mTmpMatrix; 16900 m.set(Matrix.IDENTITY_MATRIX); 16901 transformMatrixToGlobal(m); 16902 ev.transform(m); 16903 return true; 16904 } 16905 16906 /** 16907 * Transforms a motion event from on-screen coordinates to view-local 16908 * coordinates. 16909 * 16910 * @param ev the on-screen motion event 16911 * @return false if the transformation could not be applied 16912 * @hide 16913 */ 16914 public boolean toLocalMotionEvent(MotionEvent ev) { 16915 final AttachInfo info = mAttachInfo; 16916 if (info == null) { 16917 return false; 16918 } 16919 16920 final Matrix m = info.mTmpMatrix; 16921 m.set(Matrix.IDENTITY_MATRIX); 16922 transformMatrixToLocal(m); 16923 ev.transform(m); 16924 return true; 16925 } 16926 16927 /** 16928 * Modifies the input matrix such that it maps view-local coordinates to 16929 * on-screen coordinates. 16930 * 16931 * @param m input matrix to modify 16932 * @hide 16933 */ 16934 public void transformMatrixToGlobal(Matrix m) { 16935 final ViewParent parent = mParent; 16936 if (parent instanceof View) { 16937 final View vp = (View) parent; 16938 vp.transformMatrixToGlobal(m); 16939 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 16940 } else if (parent instanceof ViewRootImpl) { 16941 final ViewRootImpl vr = (ViewRootImpl) parent; 16942 vr.transformMatrixToGlobal(m); 16943 m.preTranslate(0, -vr.mCurScrollY); 16944 } 16945 16946 m.preTranslate(mLeft, mTop); 16947 16948 if (!hasIdentityMatrix()) { 16949 m.preConcat(getMatrix()); 16950 } 16951 } 16952 16953 /** 16954 * Modifies the input matrix such that it maps on-screen coordinates to 16955 * view-local coordinates. 16956 * 16957 * @param m input matrix to modify 16958 * @hide 16959 */ 16960 public void transformMatrixToLocal(Matrix m) { 16961 final ViewParent parent = mParent; 16962 if (parent instanceof View) { 16963 final View vp = (View) parent; 16964 vp.transformMatrixToLocal(m); 16965 m.postTranslate(vp.mScrollX, vp.mScrollY); 16966 } else if (parent instanceof ViewRootImpl) { 16967 final ViewRootImpl vr = (ViewRootImpl) parent; 16968 vr.transformMatrixToLocal(m); 16969 m.postTranslate(0, vr.mCurScrollY); 16970 } 16971 16972 m.postTranslate(-mLeft, -mTop); 16973 16974 if (!hasIdentityMatrix()) { 16975 m.postConcat(getInverseMatrix()); 16976 } 16977 } 16978 16979 /** 16980 * @hide 16981 */ 16982 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 16983 @ViewDebug.IntToString(from = 0, to = "x"), 16984 @ViewDebug.IntToString(from = 1, to = "y") 16985 }) 16986 public int[] getLocationOnScreen() { 16987 int[] location = new int[2]; 16988 getLocationOnScreen(location); 16989 return location; 16990 } 16991 16992 /** 16993 * <p>Computes the coordinates of this view on the screen. The argument 16994 * must be an array of two integers. After the method returns, the array 16995 * contains the x and y location in that order.</p> 16996 * 16997 * @param location an array of two integers in which to hold the coordinates 16998 */ 16999 public void getLocationOnScreen(int[] location) { 17000 getLocationInWindow(location); 17001 17002 final AttachInfo info = mAttachInfo; 17003 if (info != null) { 17004 location[0] += info.mWindowLeft; 17005 location[1] += info.mWindowTop; 17006 } 17007 } 17008 17009 /** 17010 * <p>Computes the coordinates of this view in its window. The argument 17011 * must be an array of two integers. After the method returns, the array 17012 * contains the x and y location in that order.</p> 17013 * 17014 * @param location an array of two integers in which to hold the coordinates 17015 */ 17016 public void getLocationInWindow(int[] location) { 17017 if (location == null || location.length < 2) { 17018 throw new IllegalArgumentException("location must be an array of two integers"); 17019 } 17020 17021 if (mAttachInfo == null) { 17022 // When the view is not attached to a window, this method does not make sense 17023 location[0] = location[1] = 0; 17024 return; 17025 } 17026 17027 float[] position = mAttachInfo.mTmpTransformLocation; 17028 position[0] = position[1] = 0.0f; 17029 17030 if (!hasIdentityMatrix()) { 17031 getMatrix().mapPoints(position); 17032 } 17033 17034 position[0] += mLeft; 17035 position[1] += mTop; 17036 17037 ViewParent viewParent = mParent; 17038 while (viewParent instanceof View) { 17039 final View view = (View) viewParent; 17040 17041 position[0] -= view.mScrollX; 17042 position[1] -= view.mScrollY; 17043 17044 if (!view.hasIdentityMatrix()) { 17045 view.getMatrix().mapPoints(position); 17046 } 17047 17048 position[0] += view.mLeft; 17049 position[1] += view.mTop; 17050 17051 viewParent = view.mParent; 17052 } 17053 17054 if (viewParent instanceof ViewRootImpl) { 17055 // *cough* 17056 final ViewRootImpl vr = (ViewRootImpl) viewParent; 17057 position[1] -= vr.mCurScrollY; 17058 } 17059 17060 location[0] = (int) (position[0] + 0.5f); 17061 location[1] = (int) (position[1] + 0.5f); 17062 } 17063 17064 /** 17065 * {@hide} 17066 * @param id the id of the view to be found 17067 * @return the view of the specified id, null if cannot be found 17068 */ 17069 protected View findViewTraversal(int id) { 17070 if (id == mID) { 17071 return this; 17072 } 17073 return null; 17074 } 17075 17076 /** 17077 * {@hide} 17078 * @param tag the tag of the view to be found 17079 * @return the view of specified tag, null if cannot be found 17080 */ 17081 protected View findViewWithTagTraversal(Object tag) { 17082 if (tag != null && tag.equals(mTag)) { 17083 return this; 17084 } 17085 return null; 17086 } 17087 17088 /** 17089 * {@hide} 17090 * @param predicate The predicate to evaluate. 17091 * @param childToSkip If not null, ignores this child during the recursive traversal. 17092 * @return The first view that matches the predicate or null. 17093 */ 17094 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 17095 if (predicate.apply(this)) { 17096 return this; 17097 } 17098 return null; 17099 } 17100 17101 /** 17102 * Look for a child view with the given id. If this view has the given 17103 * id, return this view. 17104 * 17105 * @param id The id to search for. 17106 * @return The view that has the given id in the hierarchy or null 17107 */ 17108 public final View findViewById(int id) { 17109 if (id < 0) { 17110 return null; 17111 } 17112 return findViewTraversal(id); 17113 } 17114 17115 /** 17116 * Finds a view by its unuque and stable accessibility id. 17117 * 17118 * @param accessibilityId The searched accessibility id. 17119 * @return The found view. 17120 */ 17121 final View findViewByAccessibilityId(int accessibilityId) { 17122 if (accessibilityId < 0) { 17123 return null; 17124 } 17125 return findViewByAccessibilityIdTraversal(accessibilityId); 17126 } 17127 17128 /** 17129 * Performs the traversal to find a view by its unuque and stable accessibility id. 17130 * 17131 * <strong>Note:</strong>This method does not stop at the root namespace 17132 * boundary since the user can touch the screen at an arbitrary location 17133 * potentially crossing the root namespace bounday which will send an 17134 * accessibility event to accessibility services and they should be able 17135 * to obtain the event source. Also accessibility ids are guaranteed to be 17136 * unique in the window. 17137 * 17138 * @param accessibilityId The accessibility id. 17139 * @return The found view. 17140 * 17141 * @hide 17142 */ 17143 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 17144 if (getAccessibilityViewId() == accessibilityId) { 17145 return this; 17146 } 17147 return null; 17148 } 17149 17150 /** 17151 * Look for a child view with the given tag. If this view has the given 17152 * tag, return this view. 17153 * 17154 * @param tag The tag to search for, using "tag.equals(getTag())". 17155 * @return The View that has the given tag in the hierarchy or null 17156 */ 17157 public final View findViewWithTag(Object tag) { 17158 if (tag == null) { 17159 return null; 17160 } 17161 return findViewWithTagTraversal(tag); 17162 } 17163 17164 /** 17165 * {@hide} 17166 * Look for a child view that matches the specified predicate. 17167 * If this view matches the predicate, return this view. 17168 * 17169 * @param predicate The predicate to evaluate. 17170 * @return The first view that matches the predicate or null. 17171 */ 17172 public final View findViewByPredicate(Predicate<View> predicate) { 17173 return findViewByPredicateTraversal(predicate, null); 17174 } 17175 17176 /** 17177 * {@hide} 17178 * Look for a child view that matches the specified predicate, 17179 * starting with the specified view and its descendents and then 17180 * recusively searching the ancestors and siblings of that view 17181 * until this view is reached. 17182 * 17183 * This method is useful in cases where the predicate does not match 17184 * a single unique view (perhaps multiple views use the same id) 17185 * and we are trying to find the view that is "closest" in scope to the 17186 * starting view. 17187 * 17188 * @param start The view to start from. 17189 * @param predicate The predicate to evaluate. 17190 * @return The first view that matches the predicate or null. 17191 */ 17192 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 17193 View childToSkip = null; 17194 for (;;) { 17195 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 17196 if (view != null || start == this) { 17197 return view; 17198 } 17199 17200 ViewParent parent = start.getParent(); 17201 if (parent == null || !(parent instanceof View)) { 17202 return null; 17203 } 17204 17205 childToSkip = start; 17206 start = (View) parent; 17207 } 17208 } 17209 17210 /** 17211 * Sets the identifier for this view. The identifier does not have to be 17212 * unique in this view's hierarchy. The identifier should be a positive 17213 * number. 17214 * 17215 * @see #NO_ID 17216 * @see #getId() 17217 * @see #findViewById(int) 17218 * 17219 * @param id a number used to identify the view 17220 * 17221 * @attr ref android.R.styleable#View_id 17222 */ 17223 public void setId(int id) { 17224 mID = id; 17225 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 17226 mID = generateViewId(); 17227 } 17228 } 17229 17230 /** 17231 * {@hide} 17232 * 17233 * @param isRoot true if the view belongs to the root namespace, false 17234 * otherwise 17235 */ 17236 public void setIsRootNamespace(boolean isRoot) { 17237 if (isRoot) { 17238 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 17239 } else { 17240 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 17241 } 17242 } 17243 17244 /** 17245 * {@hide} 17246 * 17247 * @return true if the view belongs to the root namespace, false otherwise 17248 */ 17249 public boolean isRootNamespace() { 17250 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 17251 } 17252 17253 /** 17254 * Returns this view's identifier. 17255 * 17256 * @return a positive integer used to identify the view or {@link #NO_ID} 17257 * if the view has no ID 17258 * 17259 * @see #setId(int) 17260 * @see #findViewById(int) 17261 * @attr ref android.R.styleable#View_id 17262 */ 17263 @ViewDebug.CapturedViewProperty 17264 public int getId() { 17265 return mID; 17266 } 17267 17268 /** 17269 * Returns this view's tag. 17270 * 17271 * @return the Object stored in this view as a tag, or {@code null} if not 17272 * set 17273 * 17274 * @see #setTag(Object) 17275 * @see #getTag(int) 17276 */ 17277 @ViewDebug.ExportedProperty 17278 public Object getTag() { 17279 return mTag; 17280 } 17281 17282 /** 17283 * Sets the tag associated with this view. A tag can be used to mark 17284 * a view in its hierarchy and does not have to be unique within the 17285 * hierarchy. Tags can also be used to store data within a view without 17286 * resorting to another data structure. 17287 * 17288 * @param tag an Object to tag the view with 17289 * 17290 * @see #getTag() 17291 * @see #setTag(int, Object) 17292 */ 17293 public void setTag(final Object tag) { 17294 mTag = tag; 17295 } 17296 17297 /** 17298 * Returns the tag associated with this view and the specified key. 17299 * 17300 * @param key The key identifying the tag 17301 * 17302 * @return the Object stored in this view as a tag, or {@code null} if not 17303 * set 17304 * 17305 * @see #setTag(int, Object) 17306 * @see #getTag() 17307 */ 17308 public Object getTag(int key) { 17309 if (mKeyedTags != null) return mKeyedTags.get(key); 17310 return null; 17311 } 17312 17313 /** 17314 * Sets a tag associated with this view and a key. A tag can be used 17315 * to mark a view in its hierarchy and does not have to be unique within 17316 * the hierarchy. Tags can also be used to store data within a view 17317 * without resorting to another data structure. 17318 * 17319 * The specified key should be an id declared in the resources of the 17320 * application to ensure it is unique (see the <a 17321 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 17322 * Keys identified as belonging to 17323 * the Android framework or not associated with any package will cause 17324 * an {@link IllegalArgumentException} to be thrown. 17325 * 17326 * @param key The key identifying the tag 17327 * @param tag An Object to tag the view with 17328 * 17329 * @throws IllegalArgumentException If they specified key is not valid 17330 * 17331 * @see #setTag(Object) 17332 * @see #getTag(int) 17333 */ 17334 public void setTag(int key, final Object tag) { 17335 // If the package id is 0x00 or 0x01, it's either an undefined package 17336 // or a framework id 17337 if ((key >>> 24) < 2) { 17338 throw new IllegalArgumentException("The key must be an application-specific " 17339 + "resource id."); 17340 } 17341 17342 setKeyedTag(key, tag); 17343 } 17344 17345 /** 17346 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 17347 * framework id. 17348 * 17349 * @hide 17350 */ 17351 public void setTagInternal(int key, Object tag) { 17352 if ((key >>> 24) != 0x1) { 17353 throw new IllegalArgumentException("The key must be a framework-specific " 17354 + "resource id."); 17355 } 17356 17357 setKeyedTag(key, tag); 17358 } 17359 17360 private void setKeyedTag(int key, Object tag) { 17361 if (mKeyedTags == null) { 17362 mKeyedTags = new SparseArray<Object>(2); 17363 } 17364 17365 mKeyedTags.put(key, tag); 17366 } 17367 17368 /** 17369 * Prints information about this view in the log output, with the tag 17370 * {@link #VIEW_LOG_TAG}. 17371 * 17372 * @hide 17373 */ 17374 public void debug() { 17375 debug(0); 17376 } 17377 17378 /** 17379 * Prints information about this view in the log output, with the tag 17380 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 17381 * indentation defined by the <code>depth</code>. 17382 * 17383 * @param depth the indentation level 17384 * 17385 * @hide 17386 */ 17387 protected void debug(int depth) { 17388 String output = debugIndent(depth - 1); 17389 17390 output += "+ " + this; 17391 int id = getId(); 17392 if (id != -1) { 17393 output += " (id=" + id + ")"; 17394 } 17395 Object tag = getTag(); 17396 if (tag != null) { 17397 output += " (tag=" + tag + ")"; 17398 } 17399 Log.d(VIEW_LOG_TAG, output); 17400 17401 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 17402 output = debugIndent(depth) + " FOCUSED"; 17403 Log.d(VIEW_LOG_TAG, output); 17404 } 17405 17406 output = debugIndent(depth); 17407 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 17408 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 17409 + "} "; 17410 Log.d(VIEW_LOG_TAG, output); 17411 17412 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 17413 || mPaddingBottom != 0) { 17414 output = debugIndent(depth); 17415 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 17416 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 17417 Log.d(VIEW_LOG_TAG, output); 17418 } 17419 17420 output = debugIndent(depth); 17421 output += "mMeasureWidth=" + mMeasuredWidth + 17422 " mMeasureHeight=" + mMeasuredHeight; 17423 Log.d(VIEW_LOG_TAG, output); 17424 17425 output = debugIndent(depth); 17426 if (mLayoutParams == null) { 17427 output += "BAD! no layout params"; 17428 } else { 17429 output = mLayoutParams.debug(output); 17430 } 17431 Log.d(VIEW_LOG_TAG, output); 17432 17433 output = debugIndent(depth); 17434 output += "flags={"; 17435 output += View.printFlags(mViewFlags); 17436 output += "}"; 17437 Log.d(VIEW_LOG_TAG, output); 17438 17439 output = debugIndent(depth); 17440 output += "privateFlags={"; 17441 output += View.printPrivateFlags(mPrivateFlags); 17442 output += "}"; 17443 Log.d(VIEW_LOG_TAG, output); 17444 } 17445 17446 /** 17447 * Creates a string of whitespaces used for indentation. 17448 * 17449 * @param depth the indentation level 17450 * @return a String containing (depth * 2 + 3) * 2 white spaces 17451 * 17452 * @hide 17453 */ 17454 protected static String debugIndent(int depth) { 17455 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17456 for (int i = 0; i < (depth * 2) + 3; i++) { 17457 spaces.append(' ').append(' '); 17458 } 17459 return spaces.toString(); 17460 } 17461 17462 /** 17463 * <p>Return the offset of the widget's text baseline from the widget's top 17464 * boundary. If this widget does not support baseline alignment, this 17465 * method returns -1. </p> 17466 * 17467 * @return the offset of the baseline within the widget's bounds or -1 17468 * if baseline alignment is not supported 17469 */ 17470 @ViewDebug.ExportedProperty(category = "layout") 17471 public int getBaseline() { 17472 return -1; 17473 } 17474 17475 /** 17476 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17477 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17478 * a layout pass. 17479 * 17480 * @return whether the view hierarchy is currently undergoing a layout pass 17481 */ 17482 public boolean isInLayout() { 17483 ViewRootImpl viewRoot = getViewRootImpl(); 17484 return (viewRoot != null && viewRoot.isInLayout()); 17485 } 17486 17487 /** 17488 * Call this when something has changed which has invalidated the 17489 * layout of this view. This will schedule a layout pass of the view 17490 * tree. This should not be called while the view hierarchy is currently in a layout 17491 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17492 * end of the current layout pass (and then layout will run again) or after the current 17493 * frame is drawn and the next layout occurs. 17494 * 17495 * <p>Subclasses which override this method should call the superclass method to 17496 * handle possible request-during-layout errors correctly.</p> 17497 */ 17498 public void requestLayout() { 17499 if (mMeasureCache != null) mMeasureCache.clear(); 17500 17501 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17502 // Only trigger request-during-layout logic if this is the view requesting it, 17503 // not the views in its parent hierarchy 17504 ViewRootImpl viewRoot = getViewRootImpl(); 17505 if (viewRoot != null && viewRoot.isInLayout()) { 17506 if (!viewRoot.requestLayoutDuringLayout(this)) { 17507 return; 17508 } 17509 } 17510 mAttachInfo.mViewRequestingLayout = this; 17511 } 17512 17513 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17514 mPrivateFlags |= PFLAG_INVALIDATED; 17515 17516 if (mParent != null && !mParent.isLayoutRequested()) { 17517 mParent.requestLayout(); 17518 } 17519 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17520 mAttachInfo.mViewRequestingLayout = null; 17521 } 17522 } 17523 17524 /** 17525 * Forces this view to be laid out during the next layout pass. 17526 * This method does not call requestLayout() or forceLayout() 17527 * on the parent. 17528 */ 17529 public void forceLayout() { 17530 if (mMeasureCache != null) mMeasureCache.clear(); 17531 17532 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17533 mPrivateFlags |= PFLAG_INVALIDATED; 17534 } 17535 17536 /** 17537 * <p> 17538 * This is called to find out how big a view should be. The parent 17539 * supplies constraint information in the width and height parameters. 17540 * </p> 17541 * 17542 * <p> 17543 * The actual measurement work of a view is performed in 17544 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17545 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17546 * </p> 17547 * 17548 * 17549 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17550 * parent 17551 * @param heightMeasureSpec Vertical space requirements as imposed by the 17552 * parent 17553 * 17554 * @see #onMeasure(int, int) 17555 */ 17556 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17557 boolean optical = isLayoutModeOptical(this); 17558 if (optical != isLayoutModeOptical(mParent)) { 17559 Insets insets = getOpticalInsets(); 17560 int oWidth = insets.left + insets.right; 17561 int oHeight = insets.top + insets.bottom; 17562 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17563 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17564 } 17565 17566 // Suppress sign extension for the low bytes 17567 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17568 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17569 17570 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17571 final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && 17572 MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 17573 final boolean matchingSize = isExactly && 17574 getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) && 17575 getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 17576 if (forceLayout || !matchingSize && 17577 (widthMeasureSpec != mOldWidthMeasureSpec || 17578 heightMeasureSpec != mOldHeightMeasureSpec)) { 17579 17580 // first clears the measured dimension flag 17581 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17582 17583 resolveRtlPropertiesIfNeeded(); 17584 17585 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 17586 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17587 // measure ourselves, this should set the measured dimension flag back 17588 onMeasure(widthMeasureSpec, heightMeasureSpec); 17589 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17590 } else { 17591 long value = mMeasureCache.valueAt(cacheIndex); 17592 // Casting a long to int drops the high 32 bits, no mask needed 17593 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17594 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17595 } 17596 17597 // flag not set, setMeasuredDimension() was not invoked, we raise 17598 // an exception to warn the developer 17599 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17600 throw new IllegalStateException("onMeasure() did not set the" 17601 + " measured dimension by calling" 17602 + " setMeasuredDimension()"); 17603 } 17604 17605 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17606 } 17607 17608 mOldWidthMeasureSpec = widthMeasureSpec; 17609 mOldHeightMeasureSpec = heightMeasureSpec; 17610 17611 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17612 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17613 } 17614 17615 /** 17616 * <p> 17617 * Measure the view and its content to determine the measured width and the 17618 * measured height. This method is invoked by {@link #measure(int, int)} and 17619 * should be overridden by subclasses to provide accurate and efficient 17620 * measurement of their contents. 17621 * </p> 17622 * 17623 * <p> 17624 * <strong>CONTRACT:</strong> When overriding this method, you 17625 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17626 * measured width and height of this view. Failure to do so will trigger an 17627 * <code>IllegalStateException</code>, thrown by 17628 * {@link #measure(int, int)}. Calling the superclass' 17629 * {@link #onMeasure(int, int)} is a valid use. 17630 * </p> 17631 * 17632 * <p> 17633 * The base class implementation of measure defaults to the background size, 17634 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17635 * override {@link #onMeasure(int, int)} to provide better measurements of 17636 * their content. 17637 * </p> 17638 * 17639 * <p> 17640 * If this method is overridden, it is the subclass's responsibility to make 17641 * sure the measured height and width are at least the view's minimum height 17642 * and width ({@link #getSuggestedMinimumHeight()} and 17643 * {@link #getSuggestedMinimumWidth()}). 17644 * </p> 17645 * 17646 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17647 * The requirements are encoded with 17648 * {@link android.view.View.MeasureSpec}. 17649 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17650 * The requirements are encoded with 17651 * {@link android.view.View.MeasureSpec}. 17652 * 17653 * @see #getMeasuredWidth() 17654 * @see #getMeasuredHeight() 17655 * @see #setMeasuredDimension(int, int) 17656 * @see #getSuggestedMinimumHeight() 17657 * @see #getSuggestedMinimumWidth() 17658 * @see android.view.View.MeasureSpec#getMode(int) 17659 * @see android.view.View.MeasureSpec#getSize(int) 17660 */ 17661 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17662 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17663 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17664 } 17665 17666 /** 17667 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17668 * measured width and measured height. Failing to do so will trigger an 17669 * exception at measurement time.</p> 17670 * 17671 * @param measuredWidth The measured width of this view. May be a complex 17672 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17673 * {@link #MEASURED_STATE_TOO_SMALL}. 17674 * @param measuredHeight The measured height of this view. May be a complex 17675 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17676 * {@link #MEASURED_STATE_TOO_SMALL}. 17677 */ 17678 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17679 boolean optical = isLayoutModeOptical(this); 17680 if (optical != isLayoutModeOptical(mParent)) { 17681 Insets insets = getOpticalInsets(); 17682 int opticalWidth = insets.left + insets.right; 17683 int opticalHeight = insets.top + insets.bottom; 17684 17685 measuredWidth += optical ? opticalWidth : -opticalWidth; 17686 measuredHeight += optical ? opticalHeight : -opticalHeight; 17687 } 17688 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17689 } 17690 17691 /** 17692 * Sets the measured dimension without extra processing for things like optical bounds. 17693 * Useful for reapplying consistent values that have already been cooked with adjustments 17694 * for optical bounds, etc. such as those from the measurement cache. 17695 * 17696 * @param measuredWidth The measured width of this view. May be a complex 17697 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17698 * {@link #MEASURED_STATE_TOO_SMALL}. 17699 * @param measuredHeight The measured height of this view. May be a complex 17700 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17701 * {@link #MEASURED_STATE_TOO_SMALL}. 17702 */ 17703 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17704 mMeasuredWidth = measuredWidth; 17705 mMeasuredHeight = measuredHeight; 17706 17707 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17708 } 17709 17710 /** 17711 * Merge two states as returned by {@link #getMeasuredState()}. 17712 * @param curState The current state as returned from a view or the result 17713 * of combining multiple views. 17714 * @param newState The new view state to combine. 17715 * @return Returns a new integer reflecting the combination of the two 17716 * states. 17717 */ 17718 public static int combineMeasuredStates(int curState, int newState) { 17719 return curState | newState; 17720 } 17721 17722 /** 17723 * Version of {@link #resolveSizeAndState(int, int, int)} 17724 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17725 */ 17726 public static int resolveSize(int size, int measureSpec) { 17727 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17728 } 17729 17730 /** 17731 * Utility to reconcile a desired size and state, with constraints imposed 17732 * by a MeasureSpec. Will take the desired size, unless a different size 17733 * is imposed by the constraints. The returned value is a compound integer, 17734 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17735 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 17736 * resulting size is smaller than the size the view wants to be. 17737 * 17738 * @param size How big the view wants to be. 17739 * @param measureSpec Constraints imposed by the parent. 17740 * @param childMeasuredState Size information bit mask for the view's 17741 * children. 17742 * @return Size information bit mask as defined by 17743 * {@link #MEASURED_SIZE_MASK} and 17744 * {@link #MEASURED_STATE_TOO_SMALL}. 17745 */ 17746 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17747 final int specMode = MeasureSpec.getMode(measureSpec); 17748 final int specSize = MeasureSpec.getSize(measureSpec); 17749 final int result; 17750 switch (specMode) { 17751 case MeasureSpec.AT_MOST: 17752 if (specSize < size) { 17753 result = specSize | MEASURED_STATE_TOO_SMALL; 17754 } else { 17755 result = size; 17756 } 17757 break; 17758 case MeasureSpec.EXACTLY: 17759 result = specSize; 17760 break; 17761 case MeasureSpec.UNSPECIFIED: 17762 default: 17763 result = size; 17764 } 17765 return result | (childMeasuredState & MEASURED_STATE_MASK); 17766 } 17767 17768 /** 17769 * Utility to return a default size. Uses the supplied size if the 17770 * MeasureSpec imposed no constraints. Will get larger if allowed 17771 * by the MeasureSpec. 17772 * 17773 * @param size Default size for this view 17774 * @param measureSpec Constraints imposed by the parent 17775 * @return The size this view should be. 17776 */ 17777 public static int getDefaultSize(int size, int measureSpec) { 17778 int result = size; 17779 int specMode = MeasureSpec.getMode(measureSpec); 17780 int specSize = MeasureSpec.getSize(measureSpec); 17781 17782 switch (specMode) { 17783 case MeasureSpec.UNSPECIFIED: 17784 result = size; 17785 break; 17786 case MeasureSpec.AT_MOST: 17787 case MeasureSpec.EXACTLY: 17788 result = specSize; 17789 break; 17790 } 17791 return result; 17792 } 17793 17794 /** 17795 * Returns the suggested minimum height that the view should use. This 17796 * returns the maximum of the view's minimum height 17797 * and the background's minimum height 17798 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17799 * <p> 17800 * When being used in {@link #onMeasure(int, int)}, the caller should still 17801 * ensure the returned height is within the requirements of the parent. 17802 * 17803 * @return The suggested minimum height of the view. 17804 */ 17805 protected int getSuggestedMinimumHeight() { 17806 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17807 17808 } 17809 17810 /** 17811 * Returns the suggested minimum width that the view should use. This 17812 * returns the maximum of the view's minimum width) 17813 * and the background's minimum width 17814 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17815 * <p> 17816 * When being used in {@link #onMeasure(int, int)}, the caller should still 17817 * ensure the returned width is within the requirements of the parent. 17818 * 17819 * @return The suggested minimum width of the view. 17820 */ 17821 protected int getSuggestedMinimumWidth() { 17822 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17823 } 17824 17825 /** 17826 * Returns the minimum height of the view. 17827 * 17828 * @return the minimum height the view will try to be. 17829 * 17830 * @see #setMinimumHeight(int) 17831 * 17832 * @attr ref android.R.styleable#View_minHeight 17833 */ 17834 public int getMinimumHeight() { 17835 return mMinHeight; 17836 } 17837 17838 /** 17839 * Sets the minimum height of the view. It is not guaranteed the view will 17840 * be able to achieve this minimum height (for example, if its parent layout 17841 * constrains it with less available height). 17842 * 17843 * @param minHeight The minimum height the view will try to be. 17844 * 17845 * @see #getMinimumHeight() 17846 * 17847 * @attr ref android.R.styleable#View_minHeight 17848 */ 17849 public void setMinimumHeight(int minHeight) { 17850 mMinHeight = minHeight; 17851 requestLayout(); 17852 } 17853 17854 /** 17855 * Returns the minimum width of the view. 17856 * 17857 * @return the minimum width the view will try to be. 17858 * 17859 * @see #setMinimumWidth(int) 17860 * 17861 * @attr ref android.R.styleable#View_minWidth 17862 */ 17863 public int getMinimumWidth() { 17864 return mMinWidth; 17865 } 17866 17867 /** 17868 * Sets the minimum width of the view. It is not guaranteed the view will 17869 * be able to achieve this minimum width (for example, if its parent layout 17870 * constrains it with less available width). 17871 * 17872 * @param minWidth The minimum width the view will try to be. 17873 * 17874 * @see #getMinimumWidth() 17875 * 17876 * @attr ref android.R.styleable#View_minWidth 17877 */ 17878 public void setMinimumWidth(int minWidth) { 17879 mMinWidth = minWidth; 17880 requestLayout(); 17881 17882 } 17883 17884 /** 17885 * Get the animation currently associated with this view. 17886 * 17887 * @return The animation that is currently playing or 17888 * scheduled to play for this view. 17889 */ 17890 public Animation getAnimation() { 17891 return mCurrentAnimation; 17892 } 17893 17894 /** 17895 * Start the specified animation now. 17896 * 17897 * @param animation the animation to start now 17898 */ 17899 public void startAnimation(Animation animation) { 17900 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17901 setAnimation(animation); 17902 invalidateParentCaches(); 17903 invalidate(true); 17904 } 17905 17906 /** 17907 * Cancels any animations for this view. 17908 */ 17909 public void clearAnimation() { 17910 if (mCurrentAnimation != null) { 17911 mCurrentAnimation.detach(); 17912 } 17913 mCurrentAnimation = null; 17914 invalidateParentIfNeeded(); 17915 } 17916 17917 /** 17918 * Sets the next animation to play for this view. 17919 * If you want the animation to play immediately, use 17920 * {@link #startAnimation(android.view.animation.Animation)} instead. 17921 * This method provides allows fine-grained 17922 * control over the start time and invalidation, but you 17923 * must make sure that 1) the animation has a start time set, and 17924 * 2) the view's parent (which controls animations on its children) 17925 * will be invalidated when the animation is supposed to 17926 * start. 17927 * 17928 * @param animation The next animation, or null. 17929 */ 17930 public void setAnimation(Animation animation) { 17931 mCurrentAnimation = animation; 17932 17933 if (animation != null) { 17934 // If the screen is off assume the animation start time is now instead of 17935 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17936 // would cause the animation to start when the screen turns back on 17937 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17938 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17939 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17940 } 17941 animation.reset(); 17942 } 17943 } 17944 17945 /** 17946 * Invoked by a parent ViewGroup to notify the start of the animation 17947 * currently associated with this view. If you override this method, 17948 * always call super.onAnimationStart(); 17949 * 17950 * @see #setAnimation(android.view.animation.Animation) 17951 * @see #getAnimation() 17952 */ 17953 protected void onAnimationStart() { 17954 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17955 } 17956 17957 /** 17958 * Invoked by a parent ViewGroup to notify the end of the animation 17959 * currently associated with this view. If you override this method, 17960 * always call super.onAnimationEnd(); 17961 * 17962 * @see #setAnimation(android.view.animation.Animation) 17963 * @see #getAnimation() 17964 */ 17965 protected void onAnimationEnd() { 17966 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17967 } 17968 17969 /** 17970 * Invoked if there is a Transform that involves alpha. Subclass that can 17971 * draw themselves with the specified alpha should return true, and then 17972 * respect that alpha when their onDraw() is called. If this returns false 17973 * then the view may be redirected to draw into an offscreen buffer to 17974 * fulfill the request, which will look fine, but may be slower than if the 17975 * subclass handles it internally. The default implementation returns false. 17976 * 17977 * @param alpha The alpha (0..255) to apply to the view's drawing 17978 * @return true if the view can draw with the specified alpha. 17979 */ 17980 protected boolean onSetAlpha(int alpha) { 17981 return false; 17982 } 17983 17984 /** 17985 * This is used by the RootView to perform an optimization when 17986 * the view hierarchy contains one or several SurfaceView. 17987 * SurfaceView is always considered transparent, but its children are not, 17988 * therefore all View objects remove themselves from the global transparent 17989 * region (passed as a parameter to this function). 17990 * 17991 * @param region The transparent region for this ViewAncestor (window). 17992 * 17993 * @return Returns true if the effective visibility of the view at this 17994 * point is opaque, regardless of the transparent region; returns false 17995 * if it is possible for underlying windows to be seen behind the view. 17996 * 17997 * {@hide} 17998 */ 17999 public boolean gatherTransparentRegion(Region region) { 18000 final AttachInfo attachInfo = mAttachInfo; 18001 if (region != null && attachInfo != null) { 18002 final int pflags = mPrivateFlags; 18003 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 18004 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 18005 // remove it from the transparent region. 18006 final int[] location = attachInfo.mTransparentLocation; 18007 getLocationInWindow(location); 18008 region.op(location[0], location[1], location[0] + mRight - mLeft, 18009 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 18010 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 18011 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 18012 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 18013 // exists, so we remove the background drawable's non-transparent 18014 // parts from this transparent region. 18015 applyDrawableToTransparentRegion(mBackground, region); 18016 } 18017 } 18018 return true; 18019 } 18020 18021 /** 18022 * Play a sound effect for this view. 18023 * 18024 * <p>The framework will play sound effects for some built in actions, such as 18025 * clicking, but you may wish to play these effects in your widget, 18026 * for instance, for internal navigation. 18027 * 18028 * <p>The sound effect will only be played if sound effects are enabled by the user, and 18029 * {@link #isSoundEffectsEnabled()} is true. 18030 * 18031 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 18032 */ 18033 public void playSoundEffect(int soundConstant) { 18034 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 18035 return; 18036 } 18037 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 18038 } 18039 18040 /** 18041 * BZZZTT!!1! 18042 * 18043 * <p>Provide haptic feedback to the user for this view. 18044 * 18045 * <p>The framework will provide haptic feedback for some built in actions, 18046 * such as long presses, but you may wish to provide feedback for your 18047 * own widget. 18048 * 18049 * <p>The feedback will only be performed if 18050 * {@link #isHapticFeedbackEnabled()} is true. 18051 * 18052 * @param feedbackConstant One of the constants defined in 18053 * {@link HapticFeedbackConstants} 18054 */ 18055 public boolean performHapticFeedback(int feedbackConstant) { 18056 return performHapticFeedback(feedbackConstant, 0); 18057 } 18058 18059 /** 18060 * BZZZTT!!1! 18061 * 18062 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 18063 * 18064 * @param feedbackConstant One of the constants defined in 18065 * {@link HapticFeedbackConstants} 18066 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 18067 */ 18068 public boolean performHapticFeedback(int feedbackConstant, int flags) { 18069 if (mAttachInfo == null) { 18070 return false; 18071 } 18072 //noinspection SimplifiableIfStatement 18073 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 18074 && !isHapticFeedbackEnabled()) { 18075 return false; 18076 } 18077 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 18078 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 18079 } 18080 18081 /** 18082 * Request that the visibility of the status bar or other screen/window 18083 * decorations be changed. 18084 * 18085 * <p>This method is used to put the over device UI into temporary modes 18086 * where the user's attention is focused more on the application content, 18087 * by dimming or hiding surrounding system affordances. This is typically 18088 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 18089 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 18090 * to be placed behind the action bar (and with these flags other system 18091 * affordances) so that smooth transitions between hiding and showing them 18092 * can be done. 18093 * 18094 * <p>Two representative examples of the use of system UI visibility is 18095 * implementing a content browsing application (like a magazine reader) 18096 * and a video playing application. 18097 * 18098 * <p>The first code shows a typical implementation of a View in a content 18099 * browsing application. In this implementation, the application goes 18100 * into a content-oriented mode by hiding the status bar and action bar, 18101 * and putting the navigation elements into lights out mode. The user can 18102 * then interact with content while in this mode. Such an application should 18103 * provide an easy way for the user to toggle out of the mode (such as to 18104 * check information in the status bar or access notifications). In the 18105 * implementation here, this is done simply by tapping on the content. 18106 * 18107 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 18108 * content} 18109 * 18110 * <p>This second code sample shows a typical implementation of a View 18111 * in a video playing application. In this situation, while the video is 18112 * playing the application would like to go into a complete full-screen mode, 18113 * to use as much of the display as possible for the video. When in this state 18114 * the user can not interact with the application; the system intercepts 18115 * touching on the screen to pop the UI out of full screen mode. See 18116 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 18117 * 18118 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 18119 * content} 18120 * 18121 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18122 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18123 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18124 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18125 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18126 */ 18127 public void setSystemUiVisibility(int visibility) { 18128 if (visibility != mSystemUiVisibility) { 18129 mSystemUiVisibility = visibility; 18130 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18131 mParent.recomputeViewAttributes(this); 18132 } 18133 } 18134 } 18135 18136 /** 18137 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 18138 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 18139 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 18140 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 18141 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 18142 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 18143 */ 18144 public int getSystemUiVisibility() { 18145 return mSystemUiVisibility; 18146 } 18147 18148 /** 18149 * Returns the current system UI visibility that is currently set for 18150 * the entire window. This is the combination of the 18151 * {@link #setSystemUiVisibility(int)} values supplied by all of the 18152 * views in the window. 18153 */ 18154 public int getWindowSystemUiVisibility() { 18155 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 18156 } 18157 18158 /** 18159 * Override to find out when the window's requested system UI visibility 18160 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 18161 * This is different from the callbacks received through 18162 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 18163 * in that this is only telling you about the local request of the window, 18164 * not the actual values applied by the system. 18165 */ 18166 public void onWindowSystemUiVisibilityChanged(int visible) { 18167 } 18168 18169 /** 18170 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 18171 * the view hierarchy. 18172 */ 18173 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 18174 onWindowSystemUiVisibilityChanged(visible); 18175 } 18176 18177 /** 18178 * Set a listener to receive callbacks when the visibility of the system bar changes. 18179 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 18180 */ 18181 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 18182 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 18183 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18184 mParent.recomputeViewAttributes(this); 18185 } 18186 } 18187 18188 /** 18189 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 18190 * the view hierarchy. 18191 */ 18192 public void dispatchSystemUiVisibilityChanged(int visibility) { 18193 ListenerInfo li = mListenerInfo; 18194 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 18195 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 18196 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 18197 } 18198 } 18199 18200 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 18201 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 18202 if (val != mSystemUiVisibility) { 18203 setSystemUiVisibility(val); 18204 return true; 18205 } 18206 return false; 18207 } 18208 18209 /** @hide */ 18210 public void setDisabledSystemUiVisibility(int flags) { 18211 if (mAttachInfo != null) { 18212 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 18213 mAttachInfo.mDisabledSystemUiVisibility = flags; 18214 if (mParent != null) { 18215 mParent.recomputeViewAttributes(this); 18216 } 18217 } 18218 } 18219 } 18220 18221 /** 18222 * Creates an image that the system displays during the drag and drop 18223 * operation. This is called a "drag shadow". The default implementation 18224 * for a DragShadowBuilder based on a View returns an image that has exactly the same 18225 * appearance as the given View. The default also positions the center of the drag shadow 18226 * directly under the touch point. If no View is provided (the constructor with no parameters 18227 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 18228 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 18229 * default is an invisible drag shadow. 18230 * <p> 18231 * You are not required to use the View you provide to the constructor as the basis of the 18232 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 18233 * anything you want as the drag shadow. 18234 * </p> 18235 * <p> 18236 * You pass a DragShadowBuilder object to the system when you start the drag. The system 18237 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 18238 * size and position of the drag shadow. It uses this data to construct a 18239 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 18240 * so that your application can draw the shadow image in the Canvas. 18241 * </p> 18242 * 18243 * <div class="special reference"> 18244 * <h3>Developer Guides</h3> 18245 * <p>For a guide to implementing drag and drop features, read the 18246 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18247 * </div> 18248 */ 18249 public static class DragShadowBuilder { 18250 private final WeakReference<View> mView; 18251 18252 /** 18253 * Constructs a shadow image builder based on a View. By default, the resulting drag 18254 * shadow will have the same appearance and dimensions as the View, with the touch point 18255 * over the center of the View. 18256 * @param view A View. Any View in scope can be used. 18257 */ 18258 public DragShadowBuilder(View view) { 18259 mView = new WeakReference<View>(view); 18260 } 18261 18262 /** 18263 * Construct a shadow builder object with no associated View. This 18264 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 18265 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 18266 * to supply the drag shadow's dimensions and appearance without 18267 * reference to any View object. If they are not overridden, then the result is an 18268 * invisible drag shadow. 18269 */ 18270 public DragShadowBuilder() { 18271 mView = new WeakReference<View>(null); 18272 } 18273 18274 /** 18275 * Returns the View object that had been passed to the 18276 * {@link #View.DragShadowBuilder(View)} 18277 * constructor. If that View parameter was {@code null} or if the 18278 * {@link #View.DragShadowBuilder()} 18279 * constructor was used to instantiate the builder object, this method will return 18280 * null. 18281 * 18282 * @return The View object associate with this builder object. 18283 */ 18284 @SuppressWarnings({"JavadocReference"}) 18285 final public View getView() { 18286 return mView.get(); 18287 } 18288 18289 /** 18290 * Provides the metrics for the shadow image. These include the dimensions of 18291 * the shadow image, and the point within that shadow that should 18292 * be centered under the touch location while dragging. 18293 * <p> 18294 * The default implementation sets the dimensions of the shadow to be the 18295 * same as the dimensions of the View itself and centers the shadow under 18296 * the touch point. 18297 * </p> 18298 * 18299 * @param shadowSize A {@link android.graphics.Point} containing the width and height 18300 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 18301 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 18302 * image. 18303 * 18304 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 18305 * shadow image that should be underneath the touch point during the drag and drop 18306 * operation. Your application must set {@link android.graphics.Point#x} to the 18307 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 18308 */ 18309 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 18310 final View view = mView.get(); 18311 if (view != null) { 18312 shadowSize.set(view.getWidth(), view.getHeight()); 18313 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 18314 } else { 18315 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 18316 } 18317 } 18318 18319 /** 18320 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 18321 * based on the dimensions it received from the 18322 * {@link #onProvideShadowMetrics(Point, Point)} callback. 18323 * 18324 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 18325 */ 18326 public void onDrawShadow(Canvas canvas) { 18327 final View view = mView.get(); 18328 if (view != null) { 18329 view.draw(canvas); 18330 } else { 18331 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 18332 } 18333 } 18334 } 18335 18336 /** 18337 * Starts a drag and drop operation. When your application calls this method, it passes a 18338 * {@link android.view.View.DragShadowBuilder} object to the system. The 18339 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 18340 * to get metrics for the drag shadow, and then calls the object's 18341 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 18342 * <p> 18343 * Once the system has the drag shadow, it begins the drag and drop operation by sending 18344 * drag events to all the View objects in your application that are currently visible. It does 18345 * this either by calling the View object's drag listener (an implementation of 18346 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 18347 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 18348 * Both are passed a {@link android.view.DragEvent} object that has a 18349 * {@link android.view.DragEvent#getAction()} value of 18350 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 18351 * </p> 18352 * <p> 18353 * Your application can invoke startDrag() on any attached View object. The View object does not 18354 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 18355 * be related to the View the user selected for dragging. 18356 * </p> 18357 * @param data A {@link android.content.ClipData} object pointing to the data to be 18358 * transferred by the drag and drop operation. 18359 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 18360 * drag shadow. 18361 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 18362 * drop operation. This Object is put into every DragEvent object sent by the system during the 18363 * current drag. 18364 * <p> 18365 * myLocalState is a lightweight mechanism for the sending information from the dragged View 18366 * to the target Views. For example, it can contain flags that differentiate between a 18367 * a copy operation and a move operation. 18368 * </p> 18369 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 18370 * so the parameter should be set to 0. 18371 * @return {@code true} if the method completes successfully, or 18372 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 18373 * do a drag, and so no drag operation is in progress. 18374 */ 18375 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 18376 Object myLocalState, int flags) { 18377 if (ViewDebug.DEBUG_DRAG) { 18378 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 18379 } 18380 boolean okay = false; 18381 18382 Point shadowSize = new Point(); 18383 Point shadowTouchPoint = new Point(); 18384 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 18385 18386 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 18387 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 18388 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 18389 } 18390 18391 if (ViewDebug.DEBUG_DRAG) { 18392 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 18393 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 18394 } 18395 Surface surface = new Surface(); 18396 try { 18397 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 18398 flags, shadowSize.x, shadowSize.y, surface); 18399 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 18400 + " surface=" + surface); 18401 if (token != null) { 18402 Canvas canvas = surface.lockCanvas(null); 18403 try { 18404 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 18405 shadowBuilder.onDrawShadow(canvas); 18406 } finally { 18407 surface.unlockCanvasAndPost(canvas); 18408 } 18409 18410 final ViewRootImpl root = getViewRootImpl(); 18411 18412 // Cache the local state object for delivery with DragEvents 18413 root.setLocalDragState(myLocalState); 18414 18415 // repurpose 'shadowSize' for the last touch point 18416 root.getLastTouchPoint(shadowSize); 18417 18418 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 18419 shadowSize.x, shadowSize.y, 18420 shadowTouchPoint.x, shadowTouchPoint.y, data); 18421 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 18422 18423 // Off and running! Release our local surface instance; the drag 18424 // shadow surface is now managed by the system process. 18425 surface.release(); 18426 } 18427 } catch (Exception e) { 18428 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 18429 surface.destroy(); 18430 } 18431 18432 return okay; 18433 } 18434 18435 /** 18436 * Handles drag events sent by the system following a call to 18437 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 18438 *<p> 18439 * When the system calls this method, it passes a 18440 * {@link android.view.DragEvent} object. A call to 18441 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 18442 * in DragEvent. The method uses these to determine what is happening in the drag and drop 18443 * operation. 18444 * @param event The {@link android.view.DragEvent} sent by the system. 18445 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 18446 * in DragEvent, indicating the type of drag event represented by this object. 18447 * @return {@code true} if the method was successful, otherwise {@code false}. 18448 * <p> 18449 * The method should return {@code true} in response to an action type of 18450 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 18451 * operation. 18452 * </p> 18453 * <p> 18454 * The method should also return {@code true} in response to an action type of 18455 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 18456 * {@code false} if it didn't. 18457 * </p> 18458 */ 18459 public boolean onDragEvent(DragEvent event) { 18460 return false; 18461 } 18462 18463 /** 18464 * Detects if this View is enabled and has a drag event listener. 18465 * If both are true, then it calls the drag event listener with the 18466 * {@link android.view.DragEvent} it received. If the drag event listener returns 18467 * {@code true}, then dispatchDragEvent() returns {@code true}. 18468 * <p> 18469 * For all other cases, the method calls the 18470 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18471 * method and returns its result. 18472 * </p> 18473 * <p> 18474 * This ensures that a drag event is always consumed, even if the View does not have a drag 18475 * event listener. However, if the View has a listener and the listener returns true, then 18476 * onDragEvent() is not called. 18477 * </p> 18478 */ 18479 public boolean dispatchDragEvent(DragEvent event) { 18480 ListenerInfo li = mListenerInfo; 18481 //noinspection SimplifiableIfStatement 18482 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18483 && li.mOnDragListener.onDrag(this, event)) { 18484 return true; 18485 } 18486 return onDragEvent(event); 18487 } 18488 18489 boolean canAcceptDrag() { 18490 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18491 } 18492 18493 /** 18494 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18495 * it is ever exposed at all. 18496 * @hide 18497 */ 18498 public void onCloseSystemDialogs(String reason) { 18499 } 18500 18501 /** 18502 * Given a Drawable whose bounds have been set to draw into this view, 18503 * update a Region being computed for 18504 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18505 * that any non-transparent parts of the Drawable are removed from the 18506 * given transparent region. 18507 * 18508 * @param dr The Drawable whose transparency is to be applied to the region. 18509 * @param region A Region holding the current transparency information, 18510 * where any parts of the region that are set are considered to be 18511 * transparent. On return, this region will be modified to have the 18512 * transparency information reduced by the corresponding parts of the 18513 * Drawable that are not transparent. 18514 * {@hide} 18515 */ 18516 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18517 if (DBG) { 18518 Log.i("View", "Getting transparent region for: " + this); 18519 } 18520 final Region r = dr.getTransparentRegion(); 18521 final Rect db = dr.getBounds(); 18522 final AttachInfo attachInfo = mAttachInfo; 18523 if (r != null && attachInfo != null) { 18524 final int w = getRight()-getLeft(); 18525 final int h = getBottom()-getTop(); 18526 if (db.left > 0) { 18527 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18528 r.op(0, 0, db.left, h, Region.Op.UNION); 18529 } 18530 if (db.right < w) { 18531 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18532 r.op(db.right, 0, w, h, Region.Op.UNION); 18533 } 18534 if (db.top > 0) { 18535 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18536 r.op(0, 0, w, db.top, Region.Op.UNION); 18537 } 18538 if (db.bottom < h) { 18539 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18540 r.op(0, db.bottom, w, h, Region.Op.UNION); 18541 } 18542 final int[] location = attachInfo.mTransparentLocation; 18543 getLocationInWindow(location); 18544 r.translate(location[0], location[1]); 18545 region.op(r, Region.Op.INTERSECT); 18546 } else { 18547 region.op(db, Region.Op.DIFFERENCE); 18548 } 18549 } 18550 18551 private void checkForLongClick(int delayOffset) { 18552 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18553 mHasPerformedLongPress = false; 18554 18555 if (mPendingCheckForLongPress == null) { 18556 mPendingCheckForLongPress = new CheckForLongPress(); 18557 } 18558 mPendingCheckForLongPress.rememberWindowAttachCount(); 18559 postDelayed(mPendingCheckForLongPress, 18560 ViewConfiguration.getLongPressTimeout() - delayOffset); 18561 } 18562 } 18563 18564 /** 18565 * Inflate a view from an XML resource. This convenience method wraps the {@link 18566 * LayoutInflater} class, which provides a full range of options for view inflation. 18567 * 18568 * @param context The Context object for your activity or application. 18569 * @param resource The resource ID to inflate 18570 * @param root A view group that will be the parent. Used to properly inflate the 18571 * layout_* parameters. 18572 * @see LayoutInflater 18573 */ 18574 public static View inflate(Context context, int resource, ViewGroup root) { 18575 LayoutInflater factory = LayoutInflater.from(context); 18576 return factory.inflate(resource, root); 18577 } 18578 18579 /** 18580 * Scroll the view with standard behavior for scrolling beyond the normal 18581 * content boundaries. Views that call this method should override 18582 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18583 * results of an over-scroll operation. 18584 * 18585 * Views can use this method to handle any touch or fling-based scrolling. 18586 * 18587 * @param deltaX Change in X in pixels 18588 * @param deltaY Change in Y in pixels 18589 * @param scrollX Current X scroll value in pixels before applying deltaX 18590 * @param scrollY Current Y scroll value in pixels before applying deltaY 18591 * @param scrollRangeX Maximum content scroll range along the X axis 18592 * @param scrollRangeY Maximum content scroll range along the Y axis 18593 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18594 * along the X axis. 18595 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18596 * along the Y axis. 18597 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18598 * @return true if scrolling was clamped to an over-scroll boundary along either 18599 * axis, false otherwise. 18600 */ 18601 @SuppressWarnings({"UnusedParameters"}) 18602 protected boolean overScrollBy(int deltaX, int deltaY, 18603 int scrollX, int scrollY, 18604 int scrollRangeX, int scrollRangeY, 18605 int maxOverScrollX, int maxOverScrollY, 18606 boolean isTouchEvent) { 18607 final int overScrollMode = mOverScrollMode; 18608 final boolean canScrollHorizontal = 18609 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18610 final boolean canScrollVertical = 18611 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18612 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18613 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18614 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18615 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18616 18617 int newScrollX = scrollX + deltaX; 18618 if (!overScrollHorizontal) { 18619 maxOverScrollX = 0; 18620 } 18621 18622 int newScrollY = scrollY + deltaY; 18623 if (!overScrollVertical) { 18624 maxOverScrollY = 0; 18625 } 18626 18627 // Clamp values if at the limits and record 18628 final int left = -maxOverScrollX; 18629 final int right = maxOverScrollX + scrollRangeX; 18630 final int top = -maxOverScrollY; 18631 final int bottom = maxOverScrollY + scrollRangeY; 18632 18633 boolean clampedX = false; 18634 if (newScrollX > right) { 18635 newScrollX = right; 18636 clampedX = true; 18637 } else if (newScrollX < left) { 18638 newScrollX = left; 18639 clampedX = true; 18640 } 18641 18642 boolean clampedY = false; 18643 if (newScrollY > bottom) { 18644 newScrollY = bottom; 18645 clampedY = true; 18646 } else if (newScrollY < top) { 18647 newScrollY = top; 18648 clampedY = true; 18649 } 18650 18651 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18652 18653 return clampedX || clampedY; 18654 } 18655 18656 /** 18657 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18658 * respond to the results of an over-scroll operation. 18659 * 18660 * @param scrollX New X scroll value in pixels 18661 * @param scrollY New Y scroll value in pixels 18662 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18663 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18664 */ 18665 protected void onOverScrolled(int scrollX, int scrollY, 18666 boolean clampedX, boolean clampedY) { 18667 // Intentionally empty. 18668 } 18669 18670 /** 18671 * Returns the over-scroll mode for this view. The result will be 18672 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18673 * (allow over-scrolling only if the view content is larger than the container), 18674 * or {@link #OVER_SCROLL_NEVER}. 18675 * 18676 * @return This view's over-scroll mode. 18677 */ 18678 public int getOverScrollMode() { 18679 return mOverScrollMode; 18680 } 18681 18682 /** 18683 * Set the over-scroll mode for this view. Valid over-scroll modes are 18684 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18685 * (allow over-scrolling only if the view content is larger than the container), 18686 * or {@link #OVER_SCROLL_NEVER}. 18687 * 18688 * Setting the over-scroll mode of a view will have an effect only if the 18689 * view is capable of scrolling. 18690 * 18691 * @param overScrollMode The new over-scroll mode for this view. 18692 */ 18693 public void setOverScrollMode(int overScrollMode) { 18694 if (overScrollMode != OVER_SCROLL_ALWAYS && 18695 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18696 overScrollMode != OVER_SCROLL_NEVER) { 18697 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18698 } 18699 mOverScrollMode = overScrollMode; 18700 } 18701 18702 /** 18703 * Enable or disable nested scrolling for this view. 18704 * 18705 * <p>If this property is set to true the view will be permitted to initiate nested 18706 * scrolling operations with a compatible parent view in the current hierarchy. If this 18707 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18708 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18709 * the nested scroll.</p> 18710 * 18711 * @param enabled true to enable nested scrolling, false to disable 18712 * 18713 * @see #isNestedScrollingEnabled() 18714 */ 18715 public void setNestedScrollingEnabled(boolean enabled) { 18716 if (enabled) { 18717 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18718 } else { 18719 stopNestedScroll(); 18720 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18721 } 18722 } 18723 18724 /** 18725 * Returns true if nested scrolling is enabled for this view. 18726 * 18727 * <p>If nested scrolling is enabled and this View class implementation supports it, 18728 * this view will act as a nested scrolling child view when applicable, forwarding data 18729 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18730 * parent.</p> 18731 * 18732 * @return true if nested scrolling is enabled 18733 * 18734 * @see #setNestedScrollingEnabled(boolean) 18735 */ 18736 public boolean isNestedScrollingEnabled() { 18737 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18738 PFLAG3_NESTED_SCROLLING_ENABLED; 18739 } 18740 18741 /** 18742 * Begin a nestable scroll operation along the given axes. 18743 * 18744 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18745 * 18746 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18747 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18748 * In the case of touch scrolling the nested scroll will be terminated automatically in 18749 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18750 * In the event of programmatic scrolling the caller must explicitly call 18751 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18752 * 18753 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18754 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18755 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18756 * 18757 * <p>At each incremental step of the scroll the caller should invoke 18758 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18759 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18760 * parent at least partially consumed the scroll and the caller should adjust the amount it 18761 * scrolls by.</p> 18762 * 18763 * <p>After applying the remainder of the scroll delta the caller should invoke 18764 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18765 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18766 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18767 * </p> 18768 * 18769 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18770 * {@link #SCROLL_AXIS_VERTICAL}. 18771 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18772 * the current gesture. 18773 * 18774 * @see #stopNestedScroll() 18775 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18776 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18777 */ 18778 public boolean startNestedScroll(int axes) { 18779 if (hasNestedScrollingParent()) { 18780 // Already in progress 18781 return true; 18782 } 18783 if (isNestedScrollingEnabled()) { 18784 ViewParent p = getParent(); 18785 View child = this; 18786 while (p != null) { 18787 try { 18788 if (p.onStartNestedScroll(child, this, axes)) { 18789 mNestedScrollingParent = p; 18790 p.onNestedScrollAccepted(child, this, axes); 18791 return true; 18792 } 18793 } catch (AbstractMethodError e) { 18794 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18795 "method onStartNestedScroll", e); 18796 // Allow the search upward to continue 18797 } 18798 if (p instanceof View) { 18799 child = (View) p; 18800 } 18801 p = p.getParent(); 18802 } 18803 } 18804 return false; 18805 } 18806 18807 /** 18808 * Stop a nested scroll in progress. 18809 * 18810 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18811 * 18812 * @see #startNestedScroll(int) 18813 */ 18814 public void stopNestedScroll() { 18815 if (mNestedScrollingParent != null) { 18816 mNestedScrollingParent.onStopNestedScroll(this); 18817 mNestedScrollingParent = null; 18818 } 18819 } 18820 18821 /** 18822 * Returns true if this view has a nested scrolling parent. 18823 * 18824 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18825 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18826 * 18827 * @return whether this view has a nested scrolling parent 18828 */ 18829 public boolean hasNestedScrollingParent() { 18830 return mNestedScrollingParent != null; 18831 } 18832 18833 /** 18834 * Dispatch one step of a nested scroll in progress. 18835 * 18836 * <p>Implementations of views that support nested scrolling should call this to report 18837 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18838 * is not currently in progress or nested scrolling is not 18839 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18840 * 18841 * <p>Compatible View implementations should also call 18842 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18843 * consuming a component of the scroll event themselves.</p> 18844 * 18845 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18846 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18847 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18848 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18849 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18850 * in local view coordinates of this view from before this operation 18851 * to after it completes. View implementations may use this to adjust 18852 * expected input coordinate tracking. 18853 * @return true if the event was dispatched, false if it could not be dispatched. 18854 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18855 */ 18856 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18857 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18858 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18859 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18860 int startX = 0; 18861 int startY = 0; 18862 if (offsetInWindow != null) { 18863 getLocationInWindow(offsetInWindow); 18864 startX = offsetInWindow[0]; 18865 startY = offsetInWindow[1]; 18866 } 18867 18868 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18869 dxUnconsumed, dyUnconsumed); 18870 18871 if (offsetInWindow != null) { 18872 getLocationInWindow(offsetInWindow); 18873 offsetInWindow[0] -= startX; 18874 offsetInWindow[1] -= startY; 18875 } 18876 return true; 18877 } else if (offsetInWindow != null) { 18878 // No motion, no dispatch. Keep offsetInWindow up to date. 18879 offsetInWindow[0] = 0; 18880 offsetInWindow[1] = 0; 18881 } 18882 } 18883 return false; 18884 } 18885 18886 /** 18887 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18888 * 18889 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18890 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18891 * scrolling operation to consume some or all of the scroll operation before the child view 18892 * consumes it.</p> 18893 * 18894 * @param dx Horizontal scroll distance in pixels 18895 * @param dy Vertical scroll distance in pixels 18896 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18897 * and consumed[1] the consumed dy. 18898 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18899 * in local view coordinates of this view from before this operation 18900 * to after it completes. View implementations may use this to adjust 18901 * expected input coordinate tracking. 18902 * @return true if the parent consumed some or all of the scroll delta 18903 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18904 */ 18905 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18906 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18907 if (dx != 0 || dy != 0) { 18908 int startX = 0; 18909 int startY = 0; 18910 if (offsetInWindow != null) { 18911 getLocationInWindow(offsetInWindow); 18912 startX = offsetInWindow[0]; 18913 startY = offsetInWindow[1]; 18914 } 18915 18916 if (consumed == null) { 18917 if (mTempNestedScrollConsumed == null) { 18918 mTempNestedScrollConsumed = new int[2]; 18919 } 18920 consumed = mTempNestedScrollConsumed; 18921 } 18922 consumed[0] = 0; 18923 consumed[1] = 0; 18924 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18925 18926 if (offsetInWindow != null) { 18927 getLocationInWindow(offsetInWindow); 18928 offsetInWindow[0] -= startX; 18929 offsetInWindow[1] -= startY; 18930 } 18931 return consumed[0] != 0 || consumed[1] != 0; 18932 } else if (offsetInWindow != null) { 18933 offsetInWindow[0] = 0; 18934 offsetInWindow[1] = 0; 18935 } 18936 } 18937 return false; 18938 } 18939 18940 /** 18941 * Dispatch a fling to a nested scrolling parent. 18942 * 18943 * <p>This method should be used to indicate that a nested scrolling child has detected 18944 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18945 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18946 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18947 * along a scrollable axis.</p> 18948 * 18949 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18950 * its own content, it can use this method to delegate the fling to its nested scrolling 18951 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18952 * 18953 * @param velocityX Horizontal fling velocity in pixels per second 18954 * @param velocityY Vertical fling velocity in pixels per second 18955 * @param consumed true if the child consumed the fling, false otherwise 18956 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18957 */ 18958 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18959 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18960 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18961 } 18962 return false; 18963 } 18964 18965 /** 18966 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 18967 * 18968 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 18969 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 18970 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 18971 * before the child view consumes it. If this method returns <code>true</code>, a nested 18972 * parent view consumed the fling and this view should not scroll as a result.</p> 18973 * 18974 * <p>For a better user experience, only one view in a nested scrolling chain should consume 18975 * the fling at a time. If a parent view consumed the fling this method will return false. 18976 * Custom view implementations should account for this in two ways:</p> 18977 * 18978 * <ul> 18979 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 18980 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 18981 * position regardless.</li> 18982 * <li>If a nested parent does consume the fling, this view should not scroll at all, 18983 * even to settle back to a valid idle position.</li> 18984 * </ul> 18985 * 18986 * <p>Views should also not offer fling velocities to nested parent views along an axis 18987 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 18988 * should not offer a horizontal fling velocity to its parents since scrolling along that 18989 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 18990 * 18991 * @param velocityX Horizontal fling velocity in pixels per second 18992 * @param velocityY Vertical fling velocity in pixels per second 18993 * @return true if a nested scrolling parent consumed the fling 18994 */ 18995 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 18996 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18997 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 18998 } 18999 return false; 19000 } 19001 19002 /** 19003 * Gets a scale factor that determines the distance the view should scroll 19004 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 19005 * @return The vertical scroll scale factor. 19006 * @hide 19007 */ 19008 protected float getVerticalScrollFactor() { 19009 if (mVerticalScrollFactor == 0) { 19010 TypedValue outValue = new TypedValue(); 19011 if (!mContext.getTheme().resolveAttribute( 19012 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 19013 throw new IllegalStateException( 19014 "Expected theme to define listPreferredItemHeight."); 19015 } 19016 mVerticalScrollFactor = outValue.getDimension( 19017 mContext.getResources().getDisplayMetrics()); 19018 } 19019 return mVerticalScrollFactor; 19020 } 19021 19022 /** 19023 * Gets a scale factor that determines the distance the view should scroll 19024 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 19025 * @return The horizontal scroll scale factor. 19026 * @hide 19027 */ 19028 protected float getHorizontalScrollFactor() { 19029 // TODO: Should use something else. 19030 return getVerticalScrollFactor(); 19031 } 19032 19033 /** 19034 * Return the value specifying the text direction or policy that was set with 19035 * {@link #setTextDirection(int)}. 19036 * 19037 * @return the defined text direction. It can be one of: 19038 * 19039 * {@link #TEXT_DIRECTION_INHERIT}, 19040 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19041 * {@link #TEXT_DIRECTION_ANY_RTL}, 19042 * {@link #TEXT_DIRECTION_LTR}, 19043 * {@link #TEXT_DIRECTION_RTL}, 19044 * {@link #TEXT_DIRECTION_LOCALE} 19045 * 19046 * @attr ref android.R.styleable#View_textDirection 19047 * 19048 * @hide 19049 */ 19050 @ViewDebug.ExportedProperty(category = "text", mapping = { 19051 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19052 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19053 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19054 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19055 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19056 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19057 }) 19058 public int getRawTextDirection() { 19059 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 19060 } 19061 19062 /** 19063 * Set the text direction. 19064 * 19065 * @param textDirection the direction to set. Should be one of: 19066 * 19067 * {@link #TEXT_DIRECTION_INHERIT}, 19068 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19069 * {@link #TEXT_DIRECTION_ANY_RTL}, 19070 * {@link #TEXT_DIRECTION_LTR}, 19071 * {@link #TEXT_DIRECTION_RTL}, 19072 * {@link #TEXT_DIRECTION_LOCALE} 19073 * 19074 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 19075 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 19076 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 19077 * 19078 * @attr ref android.R.styleable#View_textDirection 19079 */ 19080 public void setTextDirection(int textDirection) { 19081 if (getRawTextDirection() != textDirection) { 19082 // Reset the current text direction and the resolved one 19083 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 19084 resetResolvedTextDirection(); 19085 // Set the new text direction 19086 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 19087 // Do resolution 19088 resolveTextDirection(); 19089 // Notify change 19090 onRtlPropertiesChanged(getLayoutDirection()); 19091 // Refresh 19092 requestLayout(); 19093 invalidate(true); 19094 } 19095 } 19096 19097 /** 19098 * Return the resolved text direction. 19099 * 19100 * @return the resolved text direction. Returns one of: 19101 * 19102 * {@link #TEXT_DIRECTION_FIRST_STRONG} 19103 * {@link #TEXT_DIRECTION_ANY_RTL}, 19104 * {@link #TEXT_DIRECTION_LTR}, 19105 * {@link #TEXT_DIRECTION_RTL}, 19106 * {@link #TEXT_DIRECTION_LOCALE} 19107 * 19108 * @attr ref android.R.styleable#View_textDirection 19109 */ 19110 @ViewDebug.ExportedProperty(category = "text", mapping = { 19111 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 19112 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 19113 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 19114 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 19115 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 19116 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 19117 }) 19118 public int getTextDirection() { 19119 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 19120 } 19121 19122 /** 19123 * Resolve the text direction. 19124 * 19125 * @return true if resolution has been done, false otherwise. 19126 * 19127 * @hide 19128 */ 19129 public boolean resolveTextDirection() { 19130 // Reset any previous text direction resolution 19131 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19132 19133 if (hasRtlSupport()) { 19134 // Set resolved text direction flag depending on text direction flag 19135 final int textDirection = getRawTextDirection(); 19136 switch(textDirection) { 19137 case TEXT_DIRECTION_INHERIT: 19138 if (!canResolveTextDirection()) { 19139 // We cannot do the resolution if there is no parent, so use the default one 19140 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19141 // Resolution will need to happen again later 19142 return false; 19143 } 19144 19145 // Parent has not yet resolved, so we still return the default 19146 try { 19147 if (!mParent.isTextDirectionResolved()) { 19148 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19149 // Resolution will need to happen again later 19150 return false; 19151 } 19152 } catch (AbstractMethodError e) { 19153 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19154 " does not fully implement ViewParent", e); 19155 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 19156 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19157 return true; 19158 } 19159 19160 // Set current resolved direction to the same value as the parent's one 19161 int parentResolvedDirection; 19162 try { 19163 parentResolvedDirection = mParent.getTextDirection(); 19164 } catch (AbstractMethodError e) { 19165 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19166 " does not fully implement ViewParent", e); 19167 parentResolvedDirection = TEXT_DIRECTION_LTR; 19168 } 19169 switch (parentResolvedDirection) { 19170 case TEXT_DIRECTION_FIRST_STRONG: 19171 case TEXT_DIRECTION_ANY_RTL: 19172 case TEXT_DIRECTION_LTR: 19173 case TEXT_DIRECTION_RTL: 19174 case TEXT_DIRECTION_LOCALE: 19175 mPrivateFlags2 |= 19176 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19177 break; 19178 default: 19179 // Default resolved direction is "first strong" heuristic 19180 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19181 } 19182 break; 19183 case TEXT_DIRECTION_FIRST_STRONG: 19184 case TEXT_DIRECTION_ANY_RTL: 19185 case TEXT_DIRECTION_LTR: 19186 case TEXT_DIRECTION_RTL: 19187 case TEXT_DIRECTION_LOCALE: 19188 // Resolved direction is the same as text direction 19189 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19190 break; 19191 default: 19192 // Default resolved direction is "first strong" heuristic 19193 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19194 } 19195 } else { 19196 // Default resolved direction is "first strong" heuristic 19197 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19198 } 19199 19200 // Set to resolved 19201 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 19202 return true; 19203 } 19204 19205 /** 19206 * Check if text direction resolution can be done. 19207 * 19208 * @return true if text direction resolution can be done otherwise return false. 19209 */ 19210 public boolean canResolveTextDirection() { 19211 switch (getRawTextDirection()) { 19212 case TEXT_DIRECTION_INHERIT: 19213 if (mParent != null) { 19214 try { 19215 return mParent.canResolveTextDirection(); 19216 } catch (AbstractMethodError e) { 19217 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19218 " does not fully implement ViewParent", e); 19219 } 19220 } 19221 return false; 19222 19223 default: 19224 return true; 19225 } 19226 } 19227 19228 /** 19229 * Reset resolved text direction. Text direction will be resolved during a call to 19230 * {@link #onMeasure(int, int)}. 19231 * 19232 * @hide 19233 */ 19234 public void resetResolvedTextDirection() { 19235 // Reset any previous text direction resolution 19236 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19237 // Set to default value 19238 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19239 } 19240 19241 /** 19242 * @return true if text direction is inherited. 19243 * 19244 * @hide 19245 */ 19246 public boolean isTextDirectionInherited() { 19247 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 19248 } 19249 19250 /** 19251 * @return true if text direction is resolved. 19252 */ 19253 public boolean isTextDirectionResolved() { 19254 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 19255 } 19256 19257 /** 19258 * Return the value specifying the text alignment or policy that was set with 19259 * {@link #setTextAlignment(int)}. 19260 * 19261 * @return the defined text alignment. It can be one of: 19262 * 19263 * {@link #TEXT_ALIGNMENT_INHERIT}, 19264 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19265 * {@link #TEXT_ALIGNMENT_CENTER}, 19266 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19267 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19268 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19269 * {@link #TEXT_ALIGNMENT_VIEW_END} 19270 * 19271 * @attr ref android.R.styleable#View_textAlignment 19272 * 19273 * @hide 19274 */ 19275 @ViewDebug.ExportedProperty(category = "text", mapping = { 19276 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19277 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19278 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19279 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19280 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19281 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19282 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19283 }) 19284 @TextAlignment 19285 public int getRawTextAlignment() { 19286 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 19287 } 19288 19289 /** 19290 * Set the text alignment. 19291 * 19292 * @param textAlignment The text alignment to set. Should be one of 19293 * 19294 * {@link #TEXT_ALIGNMENT_INHERIT}, 19295 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19296 * {@link #TEXT_ALIGNMENT_CENTER}, 19297 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19298 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19299 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19300 * {@link #TEXT_ALIGNMENT_VIEW_END} 19301 * 19302 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 19303 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 19304 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 19305 * 19306 * @attr ref android.R.styleable#View_textAlignment 19307 */ 19308 public void setTextAlignment(@TextAlignment int textAlignment) { 19309 if (textAlignment != getRawTextAlignment()) { 19310 // Reset the current and resolved text alignment 19311 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 19312 resetResolvedTextAlignment(); 19313 // Set the new text alignment 19314 mPrivateFlags2 |= 19315 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 19316 // Do resolution 19317 resolveTextAlignment(); 19318 // Notify change 19319 onRtlPropertiesChanged(getLayoutDirection()); 19320 // Refresh 19321 requestLayout(); 19322 invalidate(true); 19323 } 19324 } 19325 19326 /** 19327 * Return the resolved text alignment. 19328 * 19329 * @return the resolved text alignment. Returns one of: 19330 * 19331 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19332 * {@link #TEXT_ALIGNMENT_CENTER}, 19333 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19334 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19335 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19336 * {@link #TEXT_ALIGNMENT_VIEW_END} 19337 * 19338 * @attr ref android.R.styleable#View_textAlignment 19339 */ 19340 @ViewDebug.ExportedProperty(category = "text", mapping = { 19341 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19342 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19343 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19344 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19345 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19346 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19347 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19348 }) 19349 @TextAlignment 19350 public int getTextAlignment() { 19351 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 19352 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 19353 } 19354 19355 /** 19356 * Resolve the text alignment. 19357 * 19358 * @return true if resolution has been done, false otherwise. 19359 * 19360 * @hide 19361 */ 19362 public boolean resolveTextAlignment() { 19363 // Reset any previous text alignment resolution 19364 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19365 19366 if (hasRtlSupport()) { 19367 // Set resolved text alignment flag depending on text alignment flag 19368 final int textAlignment = getRawTextAlignment(); 19369 switch (textAlignment) { 19370 case TEXT_ALIGNMENT_INHERIT: 19371 // Check if we can resolve the text alignment 19372 if (!canResolveTextAlignment()) { 19373 // We cannot do the resolution if there is no parent so use the default 19374 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19375 // Resolution will need to happen again later 19376 return false; 19377 } 19378 19379 // Parent has not yet resolved, so we still return the default 19380 try { 19381 if (!mParent.isTextAlignmentResolved()) { 19382 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19383 // Resolution will need to happen again later 19384 return false; 19385 } 19386 } catch (AbstractMethodError e) { 19387 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19388 " does not fully implement ViewParent", e); 19389 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 19390 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19391 return true; 19392 } 19393 19394 int parentResolvedTextAlignment; 19395 try { 19396 parentResolvedTextAlignment = mParent.getTextAlignment(); 19397 } catch (AbstractMethodError e) { 19398 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19399 " does not fully implement ViewParent", e); 19400 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 19401 } 19402 switch (parentResolvedTextAlignment) { 19403 case TEXT_ALIGNMENT_GRAVITY: 19404 case TEXT_ALIGNMENT_TEXT_START: 19405 case TEXT_ALIGNMENT_TEXT_END: 19406 case TEXT_ALIGNMENT_CENTER: 19407 case TEXT_ALIGNMENT_VIEW_START: 19408 case TEXT_ALIGNMENT_VIEW_END: 19409 // Resolved text alignment is the same as the parent resolved 19410 // text alignment 19411 mPrivateFlags2 |= 19412 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19413 break; 19414 default: 19415 // Use default resolved text alignment 19416 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19417 } 19418 break; 19419 case TEXT_ALIGNMENT_GRAVITY: 19420 case TEXT_ALIGNMENT_TEXT_START: 19421 case TEXT_ALIGNMENT_TEXT_END: 19422 case TEXT_ALIGNMENT_CENTER: 19423 case TEXT_ALIGNMENT_VIEW_START: 19424 case TEXT_ALIGNMENT_VIEW_END: 19425 // Resolved text alignment is the same as text alignment 19426 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19427 break; 19428 default: 19429 // Use default resolved text alignment 19430 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19431 } 19432 } else { 19433 // Use default resolved text alignment 19434 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19435 } 19436 19437 // Set the resolved 19438 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19439 return true; 19440 } 19441 19442 /** 19443 * Check if text alignment resolution can be done. 19444 * 19445 * @return true if text alignment resolution can be done otherwise return false. 19446 */ 19447 public boolean canResolveTextAlignment() { 19448 switch (getRawTextAlignment()) { 19449 case TEXT_DIRECTION_INHERIT: 19450 if (mParent != null) { 19451 try { 19452 return mParent.canResolveTextAlignment(); 19453 } catch (AbstractMethodError e) { 19454 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19455 " does not fully implement ViewParent", e); 19456 } 19457 } 19458 return false; 19459 19460 default: 19461 return true; 19462 } 19463 } 19464 19465 /** 19466 * Reset resolved text alignment. Text alignment will be resolved during a call to 19467 * {@link #onMeasure(int, int)}. 19468 * 19469 * @hide 19470 */ 19471 public void resetResolvedTextAlignment() { 19472 // Reset any previous text alignment resolution 19473 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19474 // Set to default 19475 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19476 } 19477 19478 /** 19479 * @return true if text alignment is inherited. 19480 * 19481 * @hide 19482 */ 19483 public boolean isTextAlignmentInherited() { 19484 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 19485 } 19486 19487 /** 19488 * @return true if text alignment is resolved. 19489 */ 19490 public boolean isTextAlignmentResolved() { 19491 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19492 } 19493 19494 /** 19495 * Generate a value suitable for use in {@link #setId(int)}. 19496 * This value will not collide with ID values generated at build time by aapt for R.id. 19497 * 19498 * @return a generated ID value 19499 */ 19500 public static int generateViewId() { 19501 for (;;) { 19502 final int result = sNextGeneratedId.get(); 19503 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 19504 int newValue = result + 1; 19505 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 19506 if (sNextGeneratedId.compareAndSet(result, newValue)) { 19507 return result; 19508 } 19509 } 19510 } 19511 19512 /** 19513 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 19514 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 19515 * a normal View or a ViewGroup with 19516 * {@link android.view.ViewGroup#isTransitionGroup()} true. 19517 * @hide 19518 */ 19519 public void captureTransitioningViews(List<View> transitioningViews) { 19520 if (getVisibility() == View.VISIBLE) { 19521 transitioningViews.add(this); 19522 } 19523 } 19524 19525 /** 19526 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19527 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19528 * @hide 19529 */ 19530 public void findNamedViews(Map<String, View> namedElements) { 19531 if (getVisibility() == VISIBLE || mGhostView != null) { 19532 String transitionName = getTransitionName(); 19533 if (transitionName != null) { 19534 namedElements.put(transitionName, this); 19535 } 19536 } 19537 } 19538 19539 // 19540 // Properties 19541 // 19542 /** 19543 * A Property wrapper around the <code>alpha</code> functionality handled by the 19544 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19545 */ 19546 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19547 @Override 19548 public void setValue(View object, float value) { 19549 object.setAlpha(value); 19550 } 19551 19552 @Override 19553 public Float get(View object) { 19554 return object.getAlpha(); 19555 } 19556 }; 19557 19558 /** 19559 * A Property wrapper around the <code>translationX</code> functionality handled by the 19560 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19561 */ 19562 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19563 @Override 19564 public void setValue(View object, float value) { 19565 object.setTranslationX(value); 19566 } 19567 19568 @Override 19569 public Float get(View object) { 19570 return object.getTranslationX(); 19571 } 19572 }; 19573 19574 /** 19575 * A Property wrapper around the <code>translationY</code> functionality handled by the 19576 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19577 */ 19578 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19579 @Override 19580 public void setValue(View object, float value) { 19581 object.setTranslationY(value); 19582 } 19583 19584 @Override 19585 public Float get(View object) { 19586 return object.getTranslationY(); 19587 } 19588 }; 19589 19590 /** 19591 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19592 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19593 */ 19594 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19595 @Override 19596 public void setValue(View object, float value) { 19597 object.setTranslationZ(value); 19598 } 19599 19600 @Override 19601 public Float get(View object) { 19602 return object.getTranslationZ(); 19603 } 19604 }; 19605 19606 /** 19607 * A Property wrapper around the <code>x</code> functionality handled by the 19608 * {@link View#setX(float)} and {@link View#getX()} methods. 19609 */ 19610 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19611 @Override 19612 public void setValue(View object, float value) { 19613 object.setX(value); 19614 } 19615 19616 @Override 19617 public Float get(View object) { 19618 return object.getX(); 19619 } 19620 }; 19621 19622 /** 19623 * A Property wrapper around the <code>y</code> functionality handled by the 19624 * {@link View#setY(float)} and {@link View#getY()} methods. 19625 */ 19626 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19627 @Override 19628 public void setValue(View object, float value) { 19629 object.setY(value); 19630 } 19631 19632 @Override 19633 public Float get(View object) { 19634 return object.getY(); 19635 } 19636 }; 19637 19638 /** 19639 * A Property wrapper around the <code>z</code> functionality handled by the 19640 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19641 */ 19642 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19643 @Override 19644 public void setValue(View object, float value) { 19645 object.setZ(value); 19646 } 19647 19648 @Override 19649 public Float get(View object) { 19650 return object.getZ(); 19651 } 19652 }; 19653 19654 /** 19655 * A Property wrapper around the <code>rotation</code> functionality handled by the 19656 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19657 */ 19658 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19659 @Override 19660 public void setValue(View object, float value) { 19661 object.setRotation(value); 19662 } 19663 19664 @Override 19665 public Float get(View object) { 19666 return object.getRotation(); 19667 } 19668 }; 19669 19670 /** 19671 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19672 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19673 */ 19674 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19675 @Override 19676 public void setValue(View object, float value) { 19677 object.setRotationX(value); 19678 } 19679 19680 @Override 19681 public Float get(View object) { 19682 return object.getRotationX(); 19683 } 19684 }; 19685 19686 /** 19687 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19688 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19689 */ 19690 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19691 @Override 19692 public void setValue(View object, float value) { 19693 object.setRotationY(value); 19694 } 19695 19696 @Override 19697 public Float get(View object) { 19698 return object.getRotationY(); 19699 } 19700 }; 19701 19702 /** 19703 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19704 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19705 */ 19706 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19707 @Override 19708 public void setValue(View object, float value) { 19709 object.setScaleX(value); 19710 } 19711 19712 @Override 19713 public Float get(View object) { 19714 return object.getScaleX(); 19715 } 19716 }; 19717 19718 /** 19719 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19720 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19721 */ 19722 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19723 @Override 19724 public void setValue(View object, float value) { 19725 object.setScaleY(value); 19726 } 19727 19728 @Override 19729 public Float get(View object) { 19730 return object.getScaleY(); 19731 } 19732 }; 19733 19734 /** 19735 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19736 * Each MeasureSpec represents a requirement for either the width or the height. 19737 * A MeasureSpec is comprised of a size and a mode. There are three possible 19738 * modes: 19739 * <dl> 19740 * <dt>UNSPECIFIED</dt> 19741 * <dd> 19742 * The parent has not imposed any constraint on the child. It can be whatever size 19743 * it wants. 19744 * </dd> 19745 * 19746 * <dt>EXACTLY</dt> 19747 * <dd> 19748 * The parent has determined an exact size for the child. The child is going to be 19749 * given those bounds regardless of how big it wants to be. 19750 * </dd> 19751 * 19752 * <dt>AT_MOST</dt> 19753 * <dd> 19754 * The child can be as large as it wants up to the specified size. 19755 * </dd> 19756 * </dl> 19757 * 19758 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19759 * is provided to pack and unpack the <size, mode> tuple into the int. 19760 */ 19761 public static class MeasureSpec { 19762 private static final int MODE_SHIFT = 30; 19763 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19764 19765 /** 19766 * Measure specification mode: The parent has not imposed any constraint 19767 * on the child. It can be whatever size it wants. 19768 */ 19769 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19770 19771 /** 19772 * Measure specification mode: The parent has determined an exact size 19773 * for the child. The child is going to be given those bounds regardless 19774 * of how big it wants to be. 19775 */ 19776 public static final int EXACTLY = 1 << MODE_SHIFT; 19777 19778 /** 19779 * Measure specification mode: The child can be as large as it wants up 19780 * to the specified size. 19781 */ 19782 public static final int AT_MOST = 2 << MODE_SHIFT; 19783 19784 /** 19785 * Creates a measure specification based on the supplied size and mode. 19786 * 19787 * The mode must always be one of the following: 19788 * <ul> 19789 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19790 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19791 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19792 * </ul> 19793 * 19794 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19795 * implementation was such that the order of arguments did not matter 19796 * and overflow in either value could impact the resulting MeasureSpec. 19797 * {@link android.widget.RelativeLayout} was affected by this bug. 19798 * Apps targeting API levels greater than 17 will get the fixed, more strict 19799 * behavior.</p> 19800 * 19801 * @param size the size of the measure specification 19802 * @param mode the mode of the measure specification 19803 * @return the measure specification based on size and mode 19804 */ 19805 public static int makeMeasureSpec(int size, int mode) { 19806 if (sUseBrokenMakeMeasureSpec) { 19807 return size + mode; 19808 } else { 19809 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19810 } 19811 } 19812 19813 /** 19814 * Extracts the mode from the supplied measure specification. 19815 * 19816 * @param measureSpec the measure specification to extract the mode from 19817 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19818 * {@link android.view.View.MeasureSpec#AT_MOST} or 19819 * {@link android.view.View.MeasureSpec#EXACTLY} 19820 */ 19821 public static int getMode(int measureSpec) { 19822 return (measureSpec & MODE_MASK); 19823 } 19824 19825 /** 19826 * Extracts the size from the supplied measure specification. 19827 * 19828 * @param measureSpec the measure specification to extract the size from 19829 * @return the size in pixels defined in the supplied measure specification 19830 */ 19831 public static int getSize(int measureSpec) { 19832 return (measureSpec & ~MODE_MASK); 19833 } 19834 19835 static int adjust(int measureSpec, int delta) { 19836 final int mode = getMode(measureSpec); 19837 if (mode == UNSPECIFIED) { 19838 // No need to adjust size for UNSPECIFIED mode. 19839 return makeMeasureSpec(0, UNSPECIFIED); 19840 } 19841 int size = getSize(measureSpec) + delta; 19842 if (size < 0) { 19843 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19844 ") spec: " + toString(measureSpec) + " delta: " + delta); 19845 size = 0; 19846 } 19847 return makeMeasureSpec(size, mode); 19848 } 19849 19850 /** 19851 * Returns a String representation of the specified measure 19852 * specification. 19853 * 19854 * @param measureSpec the measure specification to convert to a String 19855 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19856 */ 19857 public static String toString(int measureSpec) { 19858 int mode = getMode(measureSpec); 19859 int size = getSize(measureSpec); 19860 19861 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19862 19863 if (mode == UNSPECIFIED) 19864 sb.append("UNSPECIFIED "); 19865 else if (mode == EXACTLY) 19866 sb.append("EXACTLY "); 19867 else if (mode == AT_MOST) 19868 sb.append("AT_MOST "); 19869 else 19870 sb.append(mode).append(" "); 19871 19872 sb.append(size); 19873 return sb.toString(); 19874 } 19875 } 19876 19877 private final class CheckForLongPress implements Runnable { 19878 private int mOriginalWindowAttachCount; 19879 19880 @Override 19881 public void run() { 19882 if (isPressed() && (mParent != null) 19883 && mOriginalWindowAttachCount == mWindowAttachCount) { 19884 if (performLongClick()) { 19885 mHasPerformedLongPress = true; 19886 } 19887 } 19888 } 19889 19890 public void rememberWindowAttachCount() { 19891 mOriginalWindowAttachCount = mWindowAttachCount; 19892 } 19893 } 19894 19895 private final class CheckForTap implements Runnable { 19896 public float x; 19897 public float y; 19898 19899 @Override 19900 public void run() { 19901 mPrivateFlags &= ~PFLAG_PREPRESSED; 19902 setPressed(true, x, y); 19903 checkForLongClick(ViewConfiguration.getTapTimeout()); 19904 } 19905 } 19906 19907 private final class PerformClick implements Runnable { 19908 @Override 19909 public void run() { 19910 performClick(); 19911 } 19912 } 19913 19914 /** @hide */ 19915 public void hackTurnOffWindowResizeAnim(boolean off) { 19916 mAttachInfo.mTurnOffWindowResizeAnim = off; 19917 } 19918 19919 /** 19920 * This method returns a ViewPropertyAnimator object, which can be used to animate 19921 * specific properties on this View. 19922 * 19923 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19924 */ 19925 public ViewPropertyAnimator animate() { 19926 if (mAnimator == null) { 19927 mAnimator = new ViewPropertyAnimator(this); 19928 } 19929 return mAnimator; 19930 } 19931 19932 /** 19933 * Sets the name of the View to be used to identify Views in Transitions. 19934 * Names should be unique in the View hierarchy. 19935 * 19936 * @param transitionName The name of the View to uniquely identify it for Transitions. 19937 */ 19938 public final void setTransitionName(String transitionName) { 19939 mTransitionName = transitionName; 19940 } 19941 19942 /** 19943 * Returns the name of the View to be used to identify Views in Transitions. 19944 * Names should be unique in the View hierarchy. 19945 * 19946 * <p>This returns null if the View has not been given a name.</p> 19947 * 19948 * @return The name used of the View to be used to identify Views in Transitions or null 19949 * if no name has been given. 19950 */ 19951 @ViewDebug.ExportedProperty 19952 public String getTransitionName() { 19953 return mTransitionName; 19954 } 19955 19956 /** 19957 * Interface definition for a callback to be invoked when a hardware key event is 19958 * dispatched to this view. The callback will be invoked before the key event is 19959 * given to the view. This is only useful for hardware keyboards; a software input 19960 * method has no obligation to trigger this listener. 19961 */ 19962 public interface OnKeyListener { 19963 /** 19964 * Called when a hardware key is dispatched to a view. This allows listeners to 19965 * get a chance to respond before the target view. 19966 * <p>Key presses in software keyboards will generally NOT trigger this method, 19967 * although some may elect to do so in some situations. Do not assume a 19968 * software input method has to be key-based; even if it is, it may use key presses 19969 * in a different way than you expect, so there is no way to reliably catch soft 19970 * input key presses. 19971 * 19972 * @param v The view the key has been dispatched to. 19973 * @param keyCode The code for the physical key that was pressed 19974 * @param event The KeyEvent object containing full information about 19975 * the event. 19976 * @return True if the listener has consumed the event, false otherwise. 19977 */ 19978 boolean onKey(View v, int keyCode, KeyEvent event); 19979 } 19980 19981 /** 19982 * Interface definition for a callback to be invoked when a touch event is 19983 * dispatched to this view. The callback will be invoked before the touch 19984 * event is given to the view. 19985 */ 19986 public interface OnTouchListener { 19987 /** 19988 * Called when a touch event is dispatched to a view. This allows listeners to 19989 * get a chance to respond before the target view. 19990 * 19991 * @param v The view the touch event has been dispatched to. 19992 * @param event The MotionEvent object containing full information about 19993 * the event. 19994 * @return True if the listener has consumed the event, false otherwise. 19995 */ 19996 boolean onTouch(View v, MotionEvent event); 19997 } 19998 19999 /** 20000 * Interface definition for a callback to be invoked when a hover event is 20001 * dispatched to this view. The callback will be invoked before the hover 20002 * event is given to the view. 20003 */ 20004 public interface OnHoverListener { 20005 /** 20006 * Called when a hover event is dispatched to a view. This allows listeners to 20007 * get a chance to respond before the target view. 20008 * 20009 * @param v The view the hover event has been dispatched to. 20010 * @param event The MotionEvent object containing full information about 20011 * the event. 20012 * @return True if the listener has consumed the event, false otherwise. 20013 */ 20014 boolean onHover(View v, MotionEvent event); 20015 } 20016 20017 /** 20018 * Interface definition for a callback to be invoked when a generic motion event is 20019 * dispatched to this view. The callback will be invoked before the generic motion 20020 * event is given to the view. 20021 */ 20022 public interface OnGenericMotionListener { 20023 /** 20024 * Called when a generic motion event is dispatched to a view. This allows listeners to 20025 * get a chance to respond before the target view. 20026 * 20027 * @param v The view the generic motion event has been dispatched to. 20028 * @param event The MotionEvent object containing full information about 20029 * the event. 20030 * @return True if the listener has consumed the event, false otherwise. 20031 */ 20032 boolean onGenericMotion(View v, MotionEvent event); 20033 } 20034 20035 /** 20036 * Interface definition for a callback to be invoked when a view has been clicked and held. 20037 */ 20038 public interface OnLongClickListener { 20039 /** 20040 * Called when a view has been clicked and held. 20041 * 20042 * @param v The view that was clicked and held. 20043 * 20044 * @return true if the callback consumed the long click, false otherwise. 20045 */ 20046 boolean onLongClick(View v); 20047 } 20048 20049 /** 20050 * Interface definition for a callback to be invoked when a drag is being dispatched 20051 * to this view. The callback will be invoked before the hosting view's own 20052 * onDrag(event) method. If the listener wants to fall back to the hosting view's 20053 * onDrag(event) behavior, it should return 'false' from this callback. 20054 * 20055 * <div class="special reference"> 20056 * <h3>Developer Guides</h3> 20057 * <p>For a guide to implementing drag and drop features, read the 20058 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20059 * </div> 20060 */ 20061 public interface OnDragListener { 20062 /** 20063 * Called when a drag event is dispatched to a view. This allows listeners 20064 * to get a chance to override base View behavior. 20065 * 20066 * @param v The View that received the drag event. 20067 * @param event The {@link android.view.DragEvent} object for the drag event. 20068 * @return {@code true} if the drag event was handled successfully, or {@code false} 20069 * if the drag event was not handled. Note that {@code false} will trigger the View 20070 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 20071 */ 20072 boolean onDrag(View v, DragEvent event); 20073 } 20074 20075 /** 20076 * Interface definition for a callback to be invoked when the focus state of 20077 * a view changed. 20078 */ 20079 public interface OnFocusChangeListener { 20080 /** 20081 * Called when the focus state of a view has changed. 20082 * 20083 * @param v The view whose state has changed. 20084 * @param hasFocus The new focus state of v. 20085 */ 20086 void onFocusChange(View v, boolean hasFocus); 20087 } 20088 20089 /** 20090 * Interface definition for a callback to be invoked when a view is clicked. 20091 */ 20092 public interface OnClickListener { 20093 /** 20094 * Called when a view has been clicked. 20095 * 20096 * @param v The view that was clicked. 20097 */ 20098 void onClick(View v); 20099 } 20100 20101 /** 20102 * Interface definition for a callback to be invoked when the context menu 20103 * for this view is being built. 20104 */ 20105 public interface OnCreateContextMenuListener { 20106 /** 20107 * Called when the context menu for this view is being built. It is not 20108 * safe to hold onto the menu after this method returns. 20109 * 20110 * @param menu The context menu that is being built 20111 * @param v The view for which the context menu is being built 20112 * @param menuInfo Extra information about the item for which the 20113 * context menu should be shown. This information will vary 20114 * depending on the class of v. 20115 */ 20116 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 20117 } 20118 20119 /** 20120 * Interface definition for a callback to be invoked when the status bar changes 20121 * visibility. This reports <strong>global</strong> changes to the system UI 20122 * state, not what the application is requesting. 20123 * 20124 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 20125 */ 20126 public interface OnSystemUiVisibilityChangeListener { 20127 /** 20128 * Called when the status bar changes visibility because of a call to 20129 * {@link View#setSystemUiVisibility(int)}. 20130 * 20131 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20132 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 20133 * This tells you the <strong>global</strong> state of these UI visibility 20134 * flags, not what your app is currently applying. 20135 */ 20136 public void onSystemUiVisibilityChange(int visibility); 20137 } 20138 20139 /** 20140 * Interface definition for a callback to be invoked when this view is attached 20141 * or detached from its window. 20142 */ 20143 public interface OnAttachStateChangeListener { 20144 /** 20145 * Called when the view is attached to a window. 20146 * @param v The view that was attached 20147 */ 20148 public void onViewAttachedToWindow(View v); 20149 /** 20150 * Called when the view is detached from a window. 20151 * @param v The view that was detached 20152 */ 20153 public void onViewDetachedFromWindow(View v); 20154 } 20155 20156 /** 20157 * Listener for applying window insets on a view in a custom way. 20158 * 20159 * <p>Apps may choose to implement this interface if they want to apply custom policy 20160 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 20161 * is set, its 20162 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 20163 * method will be called instead of the View's own 20164 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 20165 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 20166 * the View's normal behavior as part of its own.</p> 20167 */ 20168 public interface OnApplyWindowInsetsListener { 20169 /** 20170 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 20171 * on a View, this listener method will be called instead of the view's own 20172 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 20173 * 20174 * @param v The view applying window insets 20175 * @param insets The insets to apply 20176 * @return The insets supplied, minus any insets that were consumed 20177 */ 20178 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 20179 } 20180 20181 private final class UnsetPressedState implements Runnable { 20182 @Override 20183 public void run() { 20184 setPressed(false); 20185 } 20186 } 20187 20188 /** 20189 * Base class for derived classes that want to save and restore their own 20190 * state in {@link android.view.View#onSaveInstanceState()}. 20191 */ 20192 public static class BaseSavedState extends AbsSavedState { 20193 /** 20194 * Constructor used when reading from a parcel. Reads the state of the superclass. 20195 * 20196 * @param source 20197 */ 20198 public BaseSavedState(Parcel source) { 20199 super(source); 20200 } 20201 20202 /** 20203 * Constructor called by derived classes when creating their SavedState objects 20204 * 20205 * @param superState The state of the superclass of this view 20206 */ 20207 public BaseSavedState(Parcelable superState) { 20208 super(superState); 20209 } 20210 20211 public static final Parcelable.Creator<BaseSavedState> CREATOR = 20212 new Parcelable.Creator<BaseSavedState>() { 20213 public BaseSavedState createFromParcel(Parcel in) { 20214 return new BaseSavedState(in); 20215 } 20216 20217 public BaseSavedState[] newArray(int size) { 20218 return new BaseSavedState[size]; 20219 } 20220 }; 20221 } 20222 20223 /** 20224 * A set of information given to a view when it is attached to its parent 20225 * window. 20226 */ 20227 final static class AttachInfo { 20228 interface Callbacks { 20229 void playSoundEffect(int effectId); 20230 boolean performHapticFeedback(int effectId, boolean always); 20231 } 20232 20233 /** 20234 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 20235 * to a Handler. This class contains the target (View) to invalidate and 20236 * the coordinates of the dirty rectangle. 20237 * 20238 * For performance purposes, this class also implements a pool of up to 20239 * POOL_LIMIT objects that get reused. This reduces memory allocations 20240 * whenever possible. 20241 */ 20242 static class InvalidateInfo { 20243 private static final int POOL_LIMIT = 10; 20244 20245 private static final SynchronizedPool<InvalidateInfo> sPool = 20246 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 20247 20248 View target; 20249 20250 int left; 20251 int top; 20252 int right; 20253 int bottom; 20254 20255 public static InvalidateInfo obtain() { 20256 InvalidateInfo instance = sPool.acquire(); 20257 return (instance != null) ? instance : new InvalidateInfo(); 20258 } 20259 20260 public void recycle() { 20261 target = null; 20262 sPool.release(this); 20263 } 20264 } 20265 20266 final IWindowSession mSession; 20267 20268 final IWindow mWindow; 20269 20270 final IBinder mWindowToken; 20271 20272 final Display mDisplay; 20273 20274 final Callbacks mRootCallbacks; 20275 20276 IWindowId mIWindowId; 20277 WindowId mWindowId; 20278 20279 /** 20280 * The top view of the hierarchy. 20281 */ 20282 View mRootView; 20283 20284 IBinder mPanelParentWindowToken; 20285 20286 boolean mHardwareAccelerated; 20287 boolean mHardwareAccelerationRequested; 20288 HardwareRenderer mHardwareRenderer; 20289 List<RenderNode> mPendingAnimatingRenderNodes; 20290 20291 /** 20292 * The state of the display to which the window is attached, as reported 20293 * by {@link Display#getState()}. Note that the display state constants 20294 * declared by {@link Display} do not exactly line up with the screen state 20295 * constants declared by {@link View} (there are more display states than 20296 * screen states). 20297 */ 20298 int mDisplayState = Display.STATE_UNKNOWN; 20299 20300 /** 20301 * Scale factor used by the compatibility mode 20302 */ 20303 float mApplicationScale; 20304 20305 /** 20306 * Indicates whether the application is in compatibility mode 20307 */ 20308 boolean mScalingRequired; 20309 20310 /** 20311 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 20312 */ 20313 boolean mTurnOffWindowResizeAnim; 20314 20315 /** 20316 * Left position of this view's window 20317 */ 20318 int mWindowLeft; 20319 20320 /** 20321 * Top position of this view's window 20322 */ 20323 int mWindowTop; 20324 20325 /** 20326 * Indicates whether views need to use 32-bit drawing caches 20327 */ 20328 boolean mUse32BitDrawingCache; 20329 20330 /** 20331 * For windows that are full-screen but using insets to layout inside 20332 * of the screen areas, these are the current insets to appear inside 20333 * the overscan area of the display. 20334 */ 20335 final Rect mOverscanInsets = new Rect(); 20336 20337 /** 20338 * For windows that are full-screen but using insets to layout inside 20339 * of the screen decorations, these are the current insets for the 20340 * content of the window. 20341 */ 20342 final Rect mContentInsets = new Rect(); 20343 20344 /** 20345 * For windows that are full-screen but using insets to layout inside 20346 * of the screen decorations, these are the current insets for the 20347 * actual visible parts of the window. 20348 */ 20349 final Rect mVisibleInsets = new Rect(); 20350 20351 /** 20352 * For windows that are full-screen but using insets to layout inside 20353 * of the screen decorations, these are the current insets for the 20354 * stable system windows. 20355 */ 20356 final Rect mStableInsets = new Rect(); 20357 20358 /** 20359 * The internal insets given by this window. This value is 20360 * supplied by the client (through 20361 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 20362 * be given to the window manager when changed to be used in laying 20363 * out windows behind it. 20364 */ 20365 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 20366 = new ViewTreeObserver.InternalInsetsInfo(); 20367 20368 /** 20369 * Set to true when mGivenInternalInsets is non-empty. 20370 */ 20371 boolean mHasNonEmptyGivenInternalInsets; 20372 20373 /** 20374 * All views in the window's hierarchy that serve as scroll containers, 20375 * used to determine if the window can be resized or must be panned 20376 * to adjust for a soft input area. 20377 */ 20378 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 20379 20380 final KeyEvent.DispatcherState mKeyDispatchState 20381 = new KeyEvent.DispatcherState(); 20382 20383 /** 20384 * Indicates whether the view's window currently has the focus. 20385 */ 20386 boolean mHasWindowFocus; 20387 20388 /** 20389 * The current visibility of the window. 20390 */ 20391 int mWindowVisibility; 20392 20393 /** 20394 * Indicates the time at which drawing started to occur. 20395 */ 20396 long mDrawingTime; 20397 20398 /** 20399 * Indicates whether or not ignoring the DIRTY_MASK flags. 20400 */ 20401 boolean mIgnoreDirtyState; 20402 20403 /** 20404 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 20405 * to avoid clearing that flag prematurely. 20406 */ 20407 boolean mSetIgnoreDirtyState = false; 20408 20409 /** 20410 * Indicates whether the view's window is currently in touch mode. 20411 */ 20412 boolean mInTouchMode; 20413 20414 /** 20415 * Indicates whether the view has requested unbuffered input dispatching for the current 20416 * event stream. 20417 */ 20418 boolean mUnbufferedDispatchRequested; 20419 20420 /** 20421 * Indicates that ViewAncestor should trigger a global layout change 20422 * the next time it performs a traversal 20423 */ 20424 boolean mRecomputeGlobalAttributes; 20425 20426 /** 20427 * Always report new attributes at next traversal. 20428 */ 20429 boolean mForceReportNewAttributes; 20430 20431 /** 20432 * Set during a traveral if any views want to keep the screen on. 20433 */ 20434 boolean mKeepScreenOn; 20435 20436 /** 20437 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 20438 */ 20439 int mSystemUiVisibility; 20440 20441 /** 20442 * Hack to force certain system UI visibility flags to be cleared. 20443 */ 20444 int mDisabledSystemUiVisibility; 20445 20446 /** 20447 * Last global system UI visibility reported by the window manager. 20448 */ 20449 int mGlobalSystemUiVisibility; 20450 20451 /** 20452 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 20453 * attached. 20454 */ 20455 boolean mHasSystemUiListeners; 20456 20457 /** 20458 * Set if the window has requested to extend into the overscan region 20459 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 20460 */ 20461 boolean mOverscanRequested; 20462 20463 /** 20464 * Set if the visibility of any views has changed. 20465 */ 20466 boolean mViewVisibilityChanged; 20467 20468 /** 20469 * Set to true if a view has been scrolled. 20470 */ 20471 boolean mViewScrollChanged; 20472 20473 /** 20474 * Set to true if high contrast mode enabled 20475 */ 20476 boolean mHighContrastText; 20477 20478 /** 20479 * Global to the view hierarchy used as a temporary for dealing with 20480 * x/y points in the transparent region computations. 20481 */ 20482 final int[] mTransparentLocation = new int[2]; 20483 20484 /** 20485 * Global to the view hierarchy used as a temporary for dealing with 20486 * x/y points in the ViewGroup.invalidateChild implementation. 20487 */ 20488 final int[] mInvalidateChildLocation = new int[2]; 20489 20490 /** 20491 * Global to the view hierarchy used as a temporary for dealng with 20492 * computing absolute on-screen location. 20493 */ 20494 final int[] mTmpLocation = new int[2]; 20495 20496 /** 20497 * Global to the view hierarchy used as a temporary for dealing with 20498 * x/y location when view is transformed. 20499 */ 20500 final float[] mTmpTransformLocation = new float[2]; 20501 20502 /** 20503 * The view tree observer used to dispatch global events like 20504 * layout, pre-draw, touch mode change, etc. 20505 */ 20506 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 20507 20508 /** 20509 * A Canvas used by the view hierarchy to perform bitmap caching. 20510 */ 20511 Canvas mCanvas; 20512 20513 /** 20514 * The view root impl. 20515 */ 20516 final ViewRootImpl mViewRootImpl; 20517 20518 /** 20519 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 20520 * handler can be used to pump events in the UI events queue. 20521 */ 20522 final Handler mHandler; 20523 20524 /** 20525 * Temporary for use in computing invalidate rectangles while 20526 * calling up the hierarchy. 20527 */ 20528 final Rect mTmpInvalRect = new Rect(); 20529 20530 /** 20531 * Temporary for use in computing hit areas with transformed views 20532 */ 20533 final RectF mTmpTransformRect = new RectF(); 20534 20535 /** 20536 * Temporary for use in computing hit areas with transformed views 20537 */ 20538 final RectF mTmpTransformRect1 = new RectF(); 20539 20540 /** 20541 * Temporary list of rectanges. 20542 */ 20543 final List<RectF> mTmpRectList = new ArrayList<>(); 20544 20545 /** 20546 * Temporary for use in transforming invalidation rect 20547 */ 20548 final Matrix mTmpMatrix = new Matrix(); 20549 20550 /** 20551 * Temporary for use in transforming invalidation rect 20552 */ 20553 final Transformation mTmpTransformation = new Transformation(); 20554 20555 /** 20556 * Temporary for use in querying outlines from OutlineProviders 20557 */ 20558 final Outline mTmpOutline = new Outline(); 20559 20560 /** 20561 * Temporary list for use in collecting focusable descendents of a view. 20562 */ 20563 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20564 20565 /** 20566 * The id of the window for accessibility purposes. 20567 */ 20568 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20569 20570 /** 20571 * Flags related to accessibility processing. 20572 * 20573 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20574 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20575 */ 20576 int mAccessibilityFetchFlags; 20577 20578 /** 20579 * The drawable for highlighting accessibility focus. 20580 */ 20581 Drawable mAccessibilityFocusDrawable; 20582 20583 /** 20584 * Show where the margins, bounds and layout bounds are for each view. 20585 */ 20586 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20587 20588 /** 20589 * Point used to compute visible regions. 20590 */ 20591 final Point mPoint = new Point(); 20592 20593 /** 20594 * Used to track which View originated a requestLayout() call, used when 20595 * requestLayout() is called during layout. 20596 */ 20597 View mViewRequestingLayout; 20598 20599 /** 20600 * Creates a new set of attachment information with the specified 20601 * events handler and thread. 20602 * 20603 * @param handler the events handler the view must use 20604 */ 20605 AttachInfo(IWindowSession session, IWindow window, Display display, 20606 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20607 mSession = session; 20608 mWindow = window; 20609 mWindowToken = window.asBinder(); 20610 mDisplay = display; 20611 mViewRootImpl = viewRootImpl; 20612 mHandler = handler; 20613 mRootCallbacks = effectPlayer; 20614 } 20615 } 20616 20617 /** 20618 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20619 * is supported. This avoids keeping too many unused fields in most 20620 * instances of View.</p> 20621 */ 20622 private static class ScrollabilityCache implements Runnable { 20623 20624 /** 20625 * Scrollbars are not visible 20626 */ 20627 public static final int OFF = 0; 20628 20629 /** 20630 * Scrollbars are visible 20631 */ 20632 public static final int ON = 1; 20633 20634 /** 20635 * Scrollbars are fading away 20636 */ 20637 public static final int FADING = 2; 20638 20639 public boolean fadeScrollBars; 20640 20641 public int fadingEdgeLength; 20642 public int scrollBarDefaultDelayBeforeFade; 20643 public int scrollBarFadeDuration; 20644 20645 public int scrollBarSize; 20646 public ScrollBarDrawable scrollBar; 20647 public float[] interpolatorValues; 20648 public View host; 20649 20650 public final Paint paint; 20651 public final Matrix matrix; 20652 public Shader shader; 20653 20654 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20655 20656 private static final float[] OPAQUE = { 255 }; 20657 private static final float[] TRANSPARENT = { 0.0f }; 20658 20659 /** 20660 * When fading should start. This time moves into the future every time 20661 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20662 */ 20663 public long fadeStartTime; 20664 20665 20666 /** 20667 * The current state of the scrollbars: ON, OFF, or FADING 20668 */ 20669 public int state = OFF; 20670 20671 private int mLastColor; 20672 20673 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20674 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20675 scrollBarSize = configuration.getScaledScrollBarSize(); 20676 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20677 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20678 20679 paint = new Paint(); 20680 matrix = new Matrix(); 20681 // use use a height of 1, and then wack the matrix each time we 20682 // actually use it. 20683 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20684 paint.setShader(shader); 20685 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20686 20687 this.host = host; 20688 } 20689 20690 public void setFadeColor(int color) { 20691 if (color != mLastColor) { 20692 mLastColor = color; 20693 20694 if (color != 0) { 20695 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20696 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20697 paint.setShader(shader); 20698 // Restore the default transfer mode (src_over) 20699 paint.setXfermode(null); 20700 } else { 20701 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20702 paint.setShader(shader); 20703 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20704 } 20705 } 20706 } 20707 20708 public void run() { 20709 long now = AnimationUtils.currentAnimationTimeMillis(); 20710 if (now >= fadeStartTime) { 20711 20712 // the animation fades the scrollbars out by changing 20713 // the opacity (alpha) from fully opaque to fully 20714 // transparent 20715 int nextFrame = (int) now; 20716 int framesCount = 0; 20717 20718 Interpolator interpolator = scrollBarInterpolator; 20719 20720 // Start opaque 20721 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20722 20723 // End transparent 20724 nextFrame += scrollBarFadeDuration; 20725 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20726 20727 state = FADING; 20728 20729 // Kick off the fade animation 20730 host.invalidate(true); 20731 } 20732 } 20733 } 20734 20735 /** 20736 * Resuable callback for sending 20737 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20738 */ 20739 private class SendViewScrolledAccessibilityEvent implements Runnable { 20740 public volatile boolean mIsPending; 20741 20742 public void run() { 20743 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20744 mIsPending = false; 20745 } 20746 } 20747 20748 /** 20749 * <p> 20750 * This class represents a delegate that can be registered in a {@link View} 20751 * to enhance accessibility support via composition rather via inheritance. 20752 * It is specifically targeted to widget developers that extend basic View 20753 * classes i.e. classes in package android.view, that would like their 20754 * applications to be backwards compatible. 20755 * </p> 20756 * <div class="special reference"> 20757 * <h3>Developer Guides</h3> 20758 * <p>For more information about making applications accessible, read the 20759 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20760 * developer guide.</p> 20761 * </div> 20762 * <p> 20763 * A scenario in which a developer would like to use an accessibility delegate 20764 * is overriding a method introduced in a later API version then the minimal API 20765 * version supported by the application. For example, the method 20766 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20767 * in API version 4 when the accessibility APIs were first introduced. If a 20768 * developer would like his application to run on API version 4 devices (assuming 20769 * all other APIs used by the application are version 4 or lower) and take advantage 20770 * of this method, instead of overriding the method which would break the application's 20771 * backwards compatibility, he can override the corresponding method in this 20772 * delegate and register the delegate in the target View if the API version of 20773 * the system is high enough i.e. the API version is same or higher to the API 20774 * version that introduced 20775 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20776 * </p> 20777 * <p> 20778 * Here is an example implementation: 20779 * </p> 20780 * <code><pre><p> 20781 * if (Build.VERSION.SDK_INT >= 14) { 20782 * // If the API version is equal of higher than the version in 20783 * // which onInitializeAccessibilityNodeInfo was introduced we 20784 * // register a delegate with a customized implementation. 20785 * View view = findViewById(R.id.view_id); 20786 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20787 * public void onInitializeAccessibilityNodeInfo(View host, 20788 * AccessibilityNodeInfo info) { 20789 * // Let the default implementation populate the info. 20790 * super.onInitializeAccessibilityNodeInfo(host, info); 20791 * // Set some other information. 20792 * info.setEnabled(host.isEnabled()); 20793 * } 20794 * }); 20795 * } 20796 * </code></pre></p> 20797 * <p> 20798 * This delegate contains methods that correspond to the accessibility methods 20799 * in View. If a delegate has been specified the implementation in View hands 20800 * off handling to the corresponding method in this delegate. The default 20801 * implementation the delegate methods behaves exactly as the corresponding 20802 * method in View for the case of no accessibility delegate been set. Hence, 20803 * to customize the behavior of a View method, clients can override only the 20804 * corresponding delegate method without altering the behavior of the rest 20805 * accessibility related methods of the host view. 20806 * </p> 20807 */ 20808 public static class AccessibilityDelegate { 20809 20810 /** 20811 * Sends an accessibility event of the given type. If accessibility is not 20812 * enabled this method has no effect. 20813 * <p> 20814 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20815 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20816 * been set. 20817 * </p> 20818 * 20819 * @param host The View hosting the delegate. 20820 * @param eventType The type of the event to send. 20821 * 20822 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20823 */ 20824 public void sendAccessibilityEvent(View host, int eventType) { 20825 host.sendAccessibilityEventInternal(eventType); 20826 } 20827 20828 /** 20829 * Performs the specified accessibility action on the view. For 20830 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20831 * <p> 20832 * The default implementation behaves as 20833 * {@link View#performAccessibilityAction(int, Bundle) 20834 * View#performAccessibilityAction(int, Bundle)} for the case of 20835 * no accessibility delegate been set. 20836 * </p> 20837 * 20838 * @param action The action to perform. 20839 * @return Whether the action was performed. 20840 * 20841 * @see View#performAccessibilityAction(int, Bundle) 20842 * View#performAccessibilityAction(int, Bundle) 20843 */ 20844 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20845 return host.performAccessibilityActionInternal(action, args); 20846 } 20847 20848 /** 20849 * Sends an accessibility event. This method behaves exactly as 20850 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20851 * empty {@link AccessibilityEvent} and does not perform a check whether 20852 * accessibility is enabled. 20853 * <p> 20854 * The default implementation behaves as 20855 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20856 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20857 * the case of no accessibility delegate been set. 20858 * </p> 20859 * 20860 * @param host The View hosting the delegate. 20861 * @param event The event to send. 20862 * 20863 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20864 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20865 */ 20866 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20867 host.sendAccessibilityEventUncheckedInternal(event); 20868 } 20869 20870 /** 20871 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20872 * to its children for adding their text content to the event. 20873 * <p> 20874 * The default implementation behaves as 20875 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20876 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20877 * the case of no accessibility delegate been set. 20878 * </p> 20879 * 20880 * @param host The View hosting the delegate. 20881 * @param event The event. 20882 * @return True if the event population was completed. 20883 * 20884 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20885 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20886 */ 20887 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20888 return host.dispatchPopulateAccessibilityEventInternal(event); 20889 } 20890 20891 /** 20892 * Gives a chance to the host View to populate the accessibility event with its 20893 * text content. 20894 * <p> 20895 * The default implementation behaves as 20896 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20897 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20898 * the case of no accessibility delegate been set. 20899 * </p> 20900 * 20901 * @param host The View hosting the delegate. 20902 * @param event The accessibility event which to populate. 20903 * 20904 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20905 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20906 */ 20907 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20908 host.onPopulateAccessibilityEventInternal(event); 20909 } 20910 20911 /** 20912 * Initializes an {@link AccessibilityEvent} with information about the 20913 * the host View which is the event source. 20914 * <p> 20915 * The default implementation behaves as 20916 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20917 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20918 * the case of no accessibility delegate been set. 20919 * </p> 20920 * 20921 * @param host The View hosting the delegate. 20922 * @param event The event to initialize. 20923 * 20924 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20925 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20926 */ 20927 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20928 host.onInitializeAccessibilityEventInternal(event); 20929 } 20930 20931 /** 20932 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20933 * <p> 20934 * The default implementation behaves as 20935 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20936 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20937 * the case of no accessibility delegate been set. 20938 * </p> 20939 * 20940 * @param host The View hosting the delegate. 20941 * @param info The instance to initialize. 20942 * 20943 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20944 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20945 */ 20946 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20947 host.onInitializeAccessibilityNodeInfoInternal(info); 20948 } 20949 20950 /** 20951 * Called when a child of the host View has requested sending an 20952 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20953 * to augment the event. 20954 * <p> 20955 * The default implementation behaves as 20956 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20957 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20958 * the case of no accessibility delegate been set. 20959 * </p> 20960 * 20961 * @param host The View hosting the delegate. 20962 * @param child The child which requests sending the event. 20963 * @param event The event to be sent. 20964 * @return True if the event should be sent 20965 * 20966 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20967 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20968 */ 20969 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20970 AccessibilityEvent event) { 20971 return host.onRequestSendAccessibilityEventInternal(child, event); 20972 } 20973 20974 /** 20975 * Gets the provider for managing a virtual view hierarchy rooted at this View 20976 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20977 * that explore the window content. 20978 * <p> 20979 * The default implementation behaves as 20980 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20981 * the case of no accessibility delegate been set. 20982 * </p> 20983 * 20984 * @return The provider. 20985 * 20986 * @see AccessibilityNodeProvider 20987 */ 20988 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20989 return null; 20990 } 20991 20992 /** 20993 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20994 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20995 * This method is responsible for obtaining an accessibility node info from a 20996 * pool of reusable instances and calling 20997 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20998 * view to initialize the former. 20999 * <p> 21000 * <strong>Note:</strong> The client is responsible for recycling the obtained 21001 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 21002 * creation. 21003 * </p> 21004 * <p> 21005 * The default implementation behaves as 21006 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 21007 * the case of no accessibility delegate been set. 21008 * </p> 21009 * @return A populated {@link AccessibilityNodeInfo}. 21010 * 21011 * @see AccessibilityNodeInfo 21012 * 21013 * @hide 21014 */ 21015 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 21016 return host.createAccessibilityNodeInfoInternal(); 21017 } 21018 } 21019 21020 private class MatchIdPredicate implements Predicate<View> { 21021 public int mId; 21022 21023 @Override 21024 public boolean apply(View view) { 21025 return (view.mID == mId); 21026 } 21027 } 21028 21029 private class MatchLabelForPredicate implements Predicate<View> { 21030 private int mLabeledId; 21031 21032 @Override 21033 public boolean apply(View view) { 21034 return (view.mLabelForId == mLabeledId); 21035 } 21036 } 21037 21038 private class SendViewStateChangedAccessibilityEvent implements Runnable { 21039 private int mChangeTypes = 0; 21040 private boolean mPosted; 21041 private boolean mPostedWithDelay; 21042 private long mLastEventTimeMillis; 21043 21044 @Override 21045 public void run() { 21046 mPosted = false; 21047 mPostedWithDelay = false; 21048 mLastEventTimeMillis = SystemClock.uptimeMillis(); 21049 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 21050 final AccessibilityEvent event = AccessibilityEvent.obtain(); 21051 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 21052 event.setContentChangeTypes(mChangeTypes); 21053 sendAccessibilityEventUnchecked(event); 21054 } 21055 mChangeTypes = 0; 21056 } 21057 21058 public void runOrPost(int changeType) { 21059 mChangeTypes |= changeType; 21060 21061 // If this is a live region or the child of a live region, collect 21062 // all events from this frame and send them on the next frame. 21063 if (inLiveRegion()) { 21064 // If we're already posted with a delay, remove that. 21065 if (mPostedWithDelay) { 21066 removeCallbacks(this); 21067 mPostedWithDelay = false; 21068 } 21069 // Only post if we're not already posted. 21070 if (!mPosted) { 21071 post(this); 21072 mPosted = true; 21073 } 21074 return; 21075 } 21076 21077 if (mPosted) { 21078 return; 21079 } 21080 21081 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 21082 final long minEventIntevalMillis = 21083 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 21084 if (timeSinceLastMillis >= minEventIntevalMillis) { 21085 removeCallbacks(this); 21086 run(); 21087 } else { 21088 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 21089 mPostedWithDelay = true; 21090 } 21091 } 21092 } 21093 21094 private boolean inLiveRegion() { 21095 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21096 return true; 21097 } 21098 21099 ViewParent parent = getParent(); 21100 while (parent instanceof View) { 21101 if (((View) parent).getAccessibilityLiveRegion() 21102 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 21103 return true; 21104 } 21105 parent = parent.getParent(); 21106 } 21107 21108 return false; 21109 } 21110 21111 /** 21112 * Dump all private flags in readable format, useful for documentation and 21113 * sanity checking. 21114 */ 21115 private static void dumpFlags() { 21116 final HashMap<String, String> found = Maps.newHashMap(); 21117 try { 21118 for (Field field : View.class.getDeclaredFields()) { 21119 final int modifiers = field.getModifiers(); 21120 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 21121 if (field.getType().equals(int.class)) { 21122 final int value = field.getInt(null); 21123 dumpFlag(found, field.getName(), value); 21124 } else if (field.getType().equals(int[].class)) { 21125 final int[] values = (int[]) field.get(null); 21126 for (int i = 0; i < values.length; i++) { 21127 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 21128 } 21129 } 21130 } 21131 } 21132 } catch (IllegalAccessException e) { 21133 throw new RuntimeException(e); 21134 } 21135 21136 final ArrayList<String> keys = Lists.newArrayList(); 21137 keys.addAll(found.keySet()); 21138 Collections.sort(keys); 21139 for (String key : keys) { 21140 Log.d(VIEW_LOG_TAG, found.get(key)); 21141 } 21142 } 21143 21144 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 21145 // Sort flags by prefix, then by bits, always keeping unique keys 21146 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 21147 final int prefix = name.indexOf('_'); 21148 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 21149 final String output = bits + " " + name; 21150 found.put(key, output); 21151 } 21152} 21153