View.java revision 70d8be7616a450e9b7ef09c8bda5a8b25936a29a
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.CallSuper; 22import android.annotation.ColorInt; 23import android.annotation.DrawableRes; 24import android.annotation.FloatRange; 25import android.annotation.IdRes; 26import android.annotation.IntDef; 27import android.annotation.LayoutRes; 28import android.annotation.NonNull; 29import android.annotation.Nullable; 30import android.annotation.Size; 31import android.annotation.UiThread; 32import android.content.ClipData; 33import android.content.Context; 34import android.content.ContextWrapper; 35import android.content.Intent; 36import android.content.res.ColorStateList; 37import android.content.res.Configuration; 38import android.content.res.Resources; 39import android.content.res.TypedArray; 40import android.graphics.Bitmap; 41import android.graphics.Canvas; 42import android.graphics.Insets; 43import android.graphics.Interpolator; 44import android.graphics.LinearGradient; 45import android.graphics.Matrix; 46import android.graphics.Outline; 47import android.graphics.Paint; 48import android.graphics.PixelFormat; 49import android.graphics.Point; 50import android.graphics.PorterDuff; 51import android.graphics.PorterDuffXfermode; 52import android.graphics.Rect; 53import android.graphics.RectF; 54import android.graphics.Region; 55import android.graphics.Shader; 56import android.graphics.drawable.ColorDrawable; 57import android.graphics.drawable.Drawable; 58import android.hardware.display.DisplayManagerGlobal; 59import android.os.Build; 60import android.os.Build.VERSION_CODES; 61import android.os.Bundle; 62import android.os.Handler; 63import android.os.IBinder; 64import android.os.Parcel; 65import android.os.Parcelable; 66import android.os.RemoteException; 67import android.os.SystemClock; 68import android.os.SystemProperties; 69import android.os.Trace; 70import android.text.TextUtils; 71import android.util.AttributeSet; 72import android.util.FloatProperty; 73import android.util.LayoutDirection; 74import android.util.Log; 75import android.util.LongSparseLongArray; 76import android.util.Pools.SynchronizedPool; 77import android.util.Property; 78import android.util.SparseArray; 79import android.util.StateSet; 80import android.util.SuperNotCalledException; 81import android.util.TypedValue; 82import android.view.ContextMenu.ContextMenuInfo; 83import android.view.AccessibilityIterators.TextSegmentIterator; 84import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 85import android.view.AccessibilityIterators.WordTextSegmentIterator; 86import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 87import android.view.accessibility.AccessibilityEvent; 88import android.view.accessibility.AccessibilityEventSource; 89import android.view.accessibility.AccessibilityManager; 90import android.view.accessibility.AccessibilityNodeInfo; 91import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 92import android.view.accessibility.AccessibilityNodeProvider; 93import android.view.animation.Animation; 94import android.view.animation.AnimationUtils; 95import android.view.animation.Transformation; 96import android.view.inputmethod.EditorInfo; 97import android.view.inputmethod.InputConnection; 98import android.view.inputmethod.InputMethodManager; 99import android.widget.Checkable; 100import android.widget.FrameLayout; 101import android.widget.ScrollBarDrawable; 102 103import static android.os.Build.VERSION_CODES.*; 104import static java.lang.Math.max; 105 106import com.android.internal.R; 107import com.android.internal.util.Predicate; 108import com.android.internal.view.menu.MenuBuilder; 109import com.google.android.collect.Lists; 110import com.google.android.collect.Maps; 111 112import java.lang.annotation.Retention; 113import java.lang.annotation.RetentionPolicy; 114import java.lang.ref.WeakReference; 115import java.lang.reflect.Field; 116import java.lang.reflect.InvocationTargetException; 117import java.lang.reflect.Method; 118import java.lang.reflect.Modifier; 119import java.util.ArrayList; 120import java.util.Arrays; 121import java.util.Collections; 122import java.util.HashMap; 123import java.util.List; 124import java.util.Locale; 125import java.util.Map; 126import java.util.concurrent.CopyOnWriteArrayList; 127import java.util.concurrent.atomic.AtomicInteger; 128 129/** 130 * <p> 131 * This class represents the basic building block for user interface components. A View 132 * occupies a rectangular area on the screen and is responsible for drawing and 133 * event handling. View is the base class for <em>widgets</em>, which are 134 * used to create interactive UI components (buttons, text fields, etc.). The 135 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 136 * are invisible containers that hold other Views (or other ViewGroups) and define 137 * their layout properties. 138 * </p> 139 * 140 * <div class="special reference"> 141 * <h3>Developer Guides</h3> 142 * <p>For information about using this class to develop your application's user interface, 143 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 144 * </div> 145 * 146 * <a name="Using"></a> 147 * <h3>Using Views</h3> 148 * <p> 149 * All of the views in a window are arranged in a single tree. You can add views 150 * either from code or by specifying a tree of views in one or more XML layout 151 * files. There are many specialized subclasses of views that act as controls or 152 * are capable of displaying text, images, or other content. 153 * </p> 154 * <p> 155 * Once you have created a tree of views, there are typically a few types of 156 * common operations you may wish to perform: 157 * <ul> 158 * <li><strong>Set properties:</strong> for example setting the text of a 159 * {@link android.widget.TextView}. The available properties and the methods 160 * that set them will vary among the different subclasses of views. Note that 161 * properties that are known at build time can be set in the XML layout 162 * files.</li> 163 * <li><strong>Set focus:</strong> The framework will handled moving focus in 164 * response to user input. To force focus to a specific view, call 165 * {@link #requestFocus}.</li> 166 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 167 * that will be notified when something interesting happens to the view. For 168 * example, all views will let you set a listener to be notified when the view 169 * gains or loses focus. You can register such a listener using 170 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 171 * Other view subclasses offer more specialized listeners. For example, a Button 172 * exposes a listener to notify clients when the button is clicked.</li> 173 * <li><strong>Set visibility:</strong> You can hide or show views using 174 * {@link #setVisibility(int)}.</li> 175 * </ul> 176 * </p> 177 * <p><em> 178 * Note: The Android framework is responsible for measuring, laying out and 179 * drawing views. You should not call methods that perform these actions on 180 * views yourself unless you are actually implementing a 181 * {@link android.view.ViewGroup}. 182 * </em></p> 183 * 184 * <a name="Lifecycle"></a> 185 * <h3>Implementing a Custom View</h3> 186 * 187 * <p> 188 * To implement a custom view, you will usually begin by providing overrides for 189 * some of the standard methods that the framework calls on all views. You do 190 * not need to override all of these methods. In fact, you can start by just 191 * overriding {@link #onDraw(android.graphics.Canvas)}. 192 * <table border="2" width="85%" align="center" cellpadding="5"> 193 * <thead> 194 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 195 * </thead> 196 * 197 * <tbody> 198 * <tr> 199 * <td rowspan="2">Creation</td> 200 * <td>Constructors</td> 201 * <td>There is a form of the constructor that are called when the view 202 * is created from code and a form that is called when the view is 203 * inflated from a layout file. The second form should parse and apply 204 * any attributes defined in the layout file. 205 * </td> 206 * </tr> 207 * <tr> 208 * <td><code>{@link #onFinishInflate()}</code></td> 209 * <td>Called after a view and all of its children has been inflated 210 * from XML.</td> 211 * </tr> 212 * 213 * <tr> 214 * <td rowspan="3">Layout</td> 215 * <td><code>{@link #onMeasure(int, int)}</code></td> 216 * <td>Called to determine the size requirements for this view and all 217 * of its children. 218 * </td> 219 * </tr> 220 * <tr> 221 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 222 * <td>Called when this view should assign a size and position to all 223 * of its children. 224 * </td> 225 * </tr> 226 * <tr> 227 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 228 * <td>Called when the size of this view has changed. 229 * </td> 230 * </tr> 231 * 232 * <tr> 233 * <td>Drawing</td> 234 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 235 * <td>Called when the view should render its content. 236 * </td> 237 * </tr> 238 * 239 * <tr> 240 * <td rowspan="4">Event processing</td> 241 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 242 * <td>Called when a new hardware key event occurs. 243 * </td> 244 * </tr> 245 * <tr> 246 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 247 * <td>Called when a hardware key up event occurs. 248 * </td> 249 * </tr> 250 * <tr> 251 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 252 * <td>Called when a trackball motion event occurs. 253 * </td> 254 * </tr> 255 * <tr> 256 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 257 * <td>Called when a touch screen motion event occurs. 258 * </td> 259 * </tr> 260 * 261 * <tr> 262 * <td rowspan="2">Focus</td> 263 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 264 * <td>Called when the view gains or loses focus. 265 * </td> 266 * </tr> 267 * 268 * <tr> 269 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 270 * <td>Called when the window containing the view gains or loses focus. 271 * </td> 272 * </tr> 273 * 274 * <tr> 275 * <td rowspan="3">Attaching</td> 276 * <td><code>{@link #onAttachedToWindow()}</code></td> 277 * <td>Called when the view is attached to a window. 278 * </td> 279 * </tr> 280 * 281 * <tr> 282 * <td><code>{@link #onDetachedFromWindow}</code></td> 283 * <td>Called when the view is detached from its window. 284 * </td> 285 * </tr> 286 * 287 * <tr> 288 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 289 * <td>Called when the visibility of the window containing the view 290 * has changed. 291 * </td> 292 * </tr> 293 * </tbody> 294 * 295 * </table> 296 * </p> 297 * 298 * <a name="IDs"></a> 299 * <h3>IDs</h3> 300 * Views may have an integer id associated with them. These ids are typically 301 * assigned in the layout XML files, and are used to find specific views within 302 * the view tree. A common pattern is to: 303 * <ul> 304 * <li>Define a Button in the layout file and assign it a unique ID. 305 * <pre> 306 * <Button 307 * android:id="@+id/my_button" 308 * android:layout_width="wrap_content" 309 * android:layout_height="wrap_content" 310 * android:text="@string/my_button_text"/> 311 * </pre></li> 312 * <li>From the onCreate method of an Activity, find the Button 313 * <pre class="prettyprint"> 314 * Button myButton = (Button) findViewById(R.id.my_button); 315 * </pre></li> 316 * </ul> 317 * <p> 318 * View IDs need not be unique throughout the tree, but it is good practice to 319 * ensure that they are at least unique within the part of the tree you are 320 * searching. 321 * </p> 322 * 323 * <a name="Position"></a> 324 * <h3>Position</h3> 325 * <p> 326 * The geometry of a view is that of a rectangle. A view has a location, 327 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 328 * two dimensions, expressed as a width and a height. The unit for location 329 * and dimensions is the pixel. 330 * </p> 331 * 332 * <p> 333 * It is possible to retrieve the location of a view by invoking the methods 334 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 335 * coordinate of the rectangle representing the view. The latter returns the 336 * top, or Y, coordinate of the rectangle representing the view. These methods 337 * both return the location of the view relative to its parent. For instance, 338 * when getLeft() returns 20, that means the view is located 20 pixels to the 339 * right of the left edge of its direct parent. 340 * </p> 341 * 342 * <p> 343 * In addition, several convenience methods are offered to avoid unnecessary 344 * computations, namely {@link #getRight()} and {@link #getBottom()}. 345 * These methods return the coordinates of the right and bottom edges of the 346 * rectangle representing the view. For instance, calling {@link #getRight()} 347 * is similar to the following computation: <code>getLeft() + getWidth()</code> 348 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 349 * </p> 350 * 351 * <a name="SizePaddingMargins"></a> 352 * <h3>Size, padding and margins</h3> 353 * <p> 354 * The size of a view is expressed with a width and a height. A view actually 355 * possess two pairs of width and height values. 356 * </p> 357 * 358 * <p> 359 * The first pair is known as <em>measured width</em> and 360 * <em>measured height</em>. These dimensions define how big a view wants to be 361 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 362 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 363 * and {@link #getMeasuredHeight()}. 364 * </p> 365 * 366 * <p> 367 * The second pair is simply known as <em>width</em> and <em>height</em>, or 368 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 369 * dimensions define the actual size of the view on screen, at drawing time and 370 * after layout. These values may, but do not have to, be different from the 371 * measured width and height. The width and height can be obtained by calling 372 * {@link #getWidth()} and {@link #getHeight()}. 373 * </p> 374 * 375 * <p> 376 * To measure its dimensions, a view takes into account its padding. The padding 377 * is expressed in pixels for the left, top, right and bottom parts of the view. 378 * Padding can be used to offset the content of the view by a specific amount of 379 * pixels. For instance, a left padding of 2 will push the view's content by 380 * 2 pixels to the right of the left edge. Padding can be set using the 381 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 382 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 383 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 384 * {@link #getPaddingEnd()}. 385 * </p> 386 * 387 * <p> 388 * Even though a view can define a padding, it does not provide any support for 389 * margins. However, view groups provide such a support. Refer to 390 * {@link android.view.ViewGroup} and 391 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 392 * </p> 393 * 394 * <a name="Layout"></a> 395 * <h3>Layout</h3> 396 * <p> 397 * Layout is a two pass process: a measure pass and a layout pass. The measuring 398 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 399 * of the view tree. Each view pushes dimension specifications down the tree 400 * during the recursion. At the end of the measure pass, every view has stored 401 * its measurements. The second pass happens in 402 * {@link #layout(int,int,int,int)} and is also top-down. During 403 * this pass each parent is responsible for positioning all of its children 404 * using the sizes computed in the measure pass. 405 * </p> 406 * 407 * <p> 408 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 409 * {@link #getMeasuredHeight()} values must be set, along with those for all of 410 * that view's descendants. A view's measured width and measured height values 411 * must respect the constraints imposed by the view's parents. This guarantees 412 * that at the end of the measure pass, all parents accept all of their 413 * children's measurements. A parent view may call measure() more than once on 414 * its children. For example, the parent may measure each child once with 415 * unspecified dimensions to find out how big they want to be, then call 416 * measure() on them again with actual numbers if the sum of all the children's 417 * unconstrained sizes is too big or too small. 418 * </p> 419 * 420 * <p> 421 * The measure pass uses two classes to communicate dimensions. The 422 * {@link MeasureSpec} class is used by views to tell their parents how they 423 * want to be measured and positioned. The base LayoutParams class just 424 * describes how big the view wants to be for both width and height. For each 425 * dimension, it can specify one of: 426 * <ul> 427 * <li> an exact number 428 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 429 * (minus padding) 430 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 431 * enclose its content (plus padding). 432 * </ul> 433 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 434 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 435 * an X and Y value. 436 * </p> 437 * 438 * <p> 439 * MeasureSpecs are used to push requirements down the tree from parent to 440 * child. A MeasureSpec can be in one of three modes: 441 * <ul> 442 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 443 * of a child view. For example, a LinearLayout may call measure() on its child 444 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 445 * tall the child view wants to be given a width of 240 pixels. 446 * <li>EXACTLY: This is used by the parent to impose an exact size on the 447 * child. The child must use this size, and guarantee that all of its 448 * descendants will fit within this size. 449 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 450 * child. The child must guarantee that it and all of its descendants will fit 451 * within this size. 452 * </ul> 453 * </p> 454 * 455 * <p> 456 * To initiate a layout, call {@link #requestLayout}. This method is typically 457 * called by a view on itself when it believes that is can no longer fit within 458 * its current bounds. 459 * </p> 460 * 461 * <a name="Drawing"></a> 462 * <h3>Drawing</h3> 463 * <p> 464 * Drawing is handled by walking the tree and recording the drawing commands of 465 * any View that needs to update. After this, the drawing commands of the 466 * entire tree are issued to screen, clipped to the newly damaged area. 467 * </p> 468 * 469 * <p> 470 * The tree is largely recorded and drawn in order, with parents drawn before 471 * (i.e., behind) their children, with siblings drawn in the order they appear 472 * in the tree. If you set a background drawable for a View, then the View will 473 * draw it before calling back to its <code>onDraw()</code> method. The child 474 * drawing order can be overridden with 475 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 476 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 477 * </p> 478 * 479 * <p> 480 * To force a view to draw, call {@link #invalidate()}. 481 * </p> 482 * 483 * <a name="EventHandlingThreading"></a> 484 * <h3>Event Handling and Threading</h3> 485 * <p> 486 * The basic cycle of a view is as follows: 487 * <ol> 488 * <li>An event comes in and is dispatched to the appropriate view. The view 489 * handles the event and notifies any listeners.</li> 490 * <li>If in the course of processing the event, the view's bounds may need 491 * to be changed, the view will call {@link #requestLayout()}.</li> 492 * <li>Similarly, if in the course of processing the event the view's appearance 493 * may need to be changed, the view will call {@link #invalidate()}.</li> 494 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 495 * the framework will take care of measuring, laying out, and drawing the tree 496 * as appropriate.</li> 497 * </ol> 498 * </p> 499 * 500 * <p><em>Note: The entire view tree is single threaded. You must always be on 501 * the UI thread when calling any method on any view.</em> 502 * If you are doing work on other threads and want to update the state of a view 503 * from that thread, you should use a {@link Handler}. 504 * </p> 505 * 506 * <a name="FocusHandling"></a> 507 * <h3>Focus Handling</h3> 508 * <p> 509 * The framework will handle routine focus movement in response to user input. 510 * This includes changing the focus as views are removed or hidden, or as new 511 * views become available. Views indicate their willingness to take focus 512 * through the {@link #isFocusable} method. To change whether a view can take 513 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 514 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 515 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 516 * </p> 517 * <p> 518 * Focus movement is based on an algorithm which finds the nearest neighbor in a 519 * given direction. In rare cases, the default algorithm may not match the 520 * intended behavior of the developer. In these situations, you can provide 521 * explicit overrides by using these XML attributes in the layout file: 522 * <pre> 523 * nextFocusDown 524 * nextFocusLeft 525 * nextFocusRight 526 * nextFocusUp 527 * </pre> 528 * </p> 529 * 530 * 531 * <p> 532 * To get a particular view to take focus, call {@link #requestFocus()}. 533 * </p> 534 * 535 * <a name="TouchMode"></a> 536 * <h3>Touch Mode</h3> 537 * <p> 538 * When a user is navigating a user interface via directional keys such as a D-pad, it is 539 * necessary to give focus to actionable items such as buttons so the user can see 540 * what will take input. If the device has touch capabilities, however, and the user 541 * begins interacting with the interface by touching it, it is no longer necessary to 542 * always highlight, or give focus to, a particular view. This motivates a mode 543 * for interaction named 'touch mode'. 544 * </p> 545 * <p> 546 * For a touch capable device, once the user touches the screen, the device 547 * will enter touch mode. From this point onward, only views for which 548 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 549 * Other views that are touchable, like buttons, will not take focus when touched; they will 550 * only fire the on click listeners. 551 * </p> 552 * <p> 553 * Any time a user hits a directional key, such as a D-pad direction, the view device will 554 * exit touch mode, and find a view to take focus, so that the user may resume interacting 555 * with the user interface without touching the screen again. 556 * </p> 557 * <p> 558 * The touch mode state is maintained across {@link android.app.Activity}s. Call 559 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 560 * </p> 561 * 562 * <a name="Scrolling"></a> 563 * <h3>Scrolling</h3> 564 * <p> 565 * The framework provides basic support for views that wish to internally 566 * scroll their content. This includes keeping track of the X and Y scroll 567 * offset as well as mechanisms for drawing scrollbars. See 568 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 569 * {@link #awakenScrollBars()} for more details. 570 * </p> 571 * 572 * <a name="Tags"></a> 573 * <h3>Tags</h3> 574 * <p> 575 * Unlike IDs, tags are not used to identify views. Tags are essentially an 576 * extra piece of information that can be associated with a view. They are most 577 * often used as a convenience to store data related to views in the views 578 * themselves rather than by putting them in a separate structure. 579 * </p> 580 * 581 * <a name="Properties"></a> 582 * <h3>Properties</h3> 583 * <p> 584 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 585 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 586 * available both in the {@link Property} form as well as in similarly-named setter/getter 587 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 588 * be used to set persistent state associated with these rendering-related properties on the view. 589 * The properties and methods can also be used in conjunction with 590 * {@link android.animation.Animator Animator}-based animations, described more in the 591 * <a href="#Animation">Animation</a> section. 592 * </p> 593 * 594 * <a name="Animation"></a> 595 * <h3>Animation</h3> 596 * <p> 597 * Starting with Android 3.0, the preferred way of animating views is to use the 598 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 599 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 600 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 601 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 602 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 603 * makes animating these View properties particularly easy and efficient. 604 * </p> 605 * <p> 606 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 607 * You can attach an {@link Animation} object to a view using 608 * {@link #setAnimation(Animation)} or 609 * {@link #startAnimation(Animation)}. The animation can alter the scale, 610 * rotation, translation and alpha of a view over time. If the animation is 611 * attached to a view that has children, the animation will affect the entire 612 * subtree rooted by that node. When an animation is started, the framework will 613 * take care of redrawing the appropriate views until the animation completes. 614 * </p> 615 * 616 * <a name="Security"></a> 617 * <h3>Security</h3> 618 * <p> 619 * Sometimes it is essential that an application be able to verify that an action 620 * is being performed with the full knowledge and consent of the user, such as 621 * granting a permission request, making a purchase or clicking on an advertisement. 622 * Unfortunately, a malicious application could try to spoof the user into 623 * performing these actions, unaware, by concealing the intended purpose of the view. 624 * As a remedy, the framework offers a touch filtering mechanism that can be used to 625 * improve the security of views that provide access to sensitive functionality. 626 * </p><p> 627 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 628 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 629 * will discard touches that are received whenever the view's window is obscured by 630 * another visible window. As a result, the view will not receive touches whenever a 631 * toast, dialog or other window appears above the view's window. 632 * </p><p> 633 * For more fine-grained control over security, consider overriding the 634 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 635 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 636 * </p> 637 * 638 * @attr ref android.R.styleable#View_alpha 639 * @attr ref android.R.styleable#View_background 640 * @attr ref android.R.styleable#View_clickable 641 * @attr ref android.R.styleable#View_contentDescription 642 * @attr ref android.R.styleable#View_drawingCacheQuality 643 * @attr ref android.R.styleable#View_duplicateParentState 644 * @attr ref android.R.styleable#View_id 645 * @attr ref android.R.styleable#View_requiresFadingEdge 646 * @attr ref android.R.styleable#View_fadeScrollbars 647 * @attr ref android.R.styleable#View_fadingEdgeLength 648 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 649 * @attr ref android.R.styleable#View_fitsSystemWindows 650 * @attr ref android.R.styleable#View_isScrollContainer 651 * @attr ref android.R.styleable#View_focusable 652 * @attr ref android.R.styleable#View_focusableInTouchMode 653 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 654 * @attr ref android.R.styleable#View_keepScreenOn 655 * @attr ref android.R.styleable#View_layerType 656 * @attr ref android.R.styleable#View_layoutDirection 657 * @attr ref android.R.styleable#View_longClickable 658 * @attr ref android.R.styleable#View_minHeight 659 * @attr ref android.R.styleable#View_minWidth 660 * @attr ref android.R.styleable#View_nextFocusDown 661 * @attr ref android.R.styleable#View_nextFocusLeft 662 * @attr ref android.R.styleable#View_nextFocusRight 663 * @attr ref android.R.styleable#View_nextFocusUp 664 * @attr ref android.R.styleable#View_onClick 665 * @attr ref android.R.styleable#View_padding 666 * @attr ref android.R.styleable#View_paddingBottom 667 * @attr ref android.R.styleable#View_paddingLeft 668 * @attr ref android.R.styleable#View_paddingRight 669 * @attr ref android.R.styleable#View_paddingTop 670 * @attr ref android.R.styleable#View_paddingStart 671 * @attr ref android.R.styleable#View_paddingEnd 672 * @attr ref android.R.styleable#View_saveEnabled 673 * @attr ref android.R.styleable#View_rotation 674 * @attr ref android.R.styleable#View_rotationX 675 * @attr ref android.R.styleable#View_rotationY 676 * @attr ref android.R.styleable#View_scaleX 677 * @attr ref android.R.styleable#View_scaleY 678 * @attr ref android.R.styleable#View_scrollX 679 * @attr ref android.R.styleable#View_scrollY 680 * @attr ref android.R.styleable#View_scrollbarSize 681 * @attr ref android.R.styleable#View_scrollbarStyle 682 * @attr ref android.R.styleable#View_scrollbars 683 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 684 * @attr ref android.R.styleable#View_scrollbarFadeDuration 685 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 686 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 687 * @attr ref android.R.styleable#View_scrollbarThumbVertical 688 * @attr ref android.R.styleable#View_scrollbarTrackVertical 689 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 690 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 691 * @attr ref android.R.styleable#View_stateListAnimator 692 * @attr ref android.R.styleable#View_transitionName 693 * @attr ref android.R.styleable#View_soundEffectsEnabled 694 * @attr ref android.R.styleable#View_tag 695 * @attr ref android.R.styleable#View_textAlignment 696 * @attr ref android.R.styleable#View_textDirection 697 * @attr ref android.R.styleable#View_transformPivotX 698 * @attr ref android.R.styleable#View_transformPivotY 699 * @attr ref android.R.styleable#View_translationX 700 * @attr ref android.R.styleable#View_translationY 701 * @attr ref android.R.styleable#View_translationZ 702 * @attr ref android.R.styleable#View_visibility 703 * 704 * @see android.view.ViewGroup 705 */ 706@UiThread 707public class View implements Drawable.Callback, KeyEvent.Callback, 708 AccessibilityEventSource { 709 private static final boolean DBG = false; 710 711 /** 712 * The logging tag used by this class with android.util.Log. 713 */ 714 protected static final String VIEW_LOG_TAG = "View"; 715 716 /** 717 * When set to true, apps will draw debugging information about their layouts. 718 * 719 * @hide 720 */ 721 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 722 723 /** 724 * When set to true, this view will save its attribute data. 725 * 726 * @hide 727 */ 728 public static boolean mDebugViewAttributes = false; 729 730 /** 731 * Used to mark a View that has no ID. 732 */ 733 public static final int NO_ID = -1; 734 735 /** 736 * Signals that compatibility booleans have been initialized according to 737 * target SDK versions. 738 */ 739 private static boolean sCompatibilityDone = false; 740 741 /** 742 * Use the old (broken) way of building MeasureSpecs. 743 */ 744 private static boolean sUseBrokenMakeMeasureSpec = false; 745 746 /** 747 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 748 */ 749 static boolean sUseZeroUnspecifiedMeasureSpec = false; 750 751 /** 752 * Ignore any optimizations using the measure cache. 753 */ 754 private static boolean sIgnoreMeasureCache = false; 755 756 /** 757 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 758 * calling setFlags. 759 */ 760 private static final int NOT_FOCUSABLE = 0x00000000; 761 762 /** 763 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 764 * setFlags. 765 */ 766 private static final int FOCUSABLE = 0x00000001; 767 768 /** 769 * Mask for use with setFlags indicating bits used for focus. 770 */ 771 private static final int FOCUSABLE_MASK = 0x00000001; 772 773 /** 774 * This view will adjust its padding to fit sytem windows (e.g. status bar) 775 */ 776 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 777 778 /** @hide */ 779 @IntDef({VISIBLE, INVISIBLE, GONE}) 780 @Retention(RetentionPolicy.SOURCE) 781 public @interface Visibility {} 782 783 /** 784 * This view is visible. 785 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 786 * android:visibility}. 787 */ 788 public static final int VISIBLE = 0x00000000; 789 790 /** 791 * This view is invisible, but it still takes up space for layout purposes. 792 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 793 * android:visibility}. 794 */ 795 public static final int INVISIBLE = 0x00000004; 796 797 /** 798 * This view is invisible, and it doesn't take any space for layout 799 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 800 * android:visibility}. 801 */ 802 public static final int GONE = 0x00000008; 803 804 /** 805 * Mask for use with setFlags indicating bits used for visibility. 806 * {@hide} 807 */ 808 static final int VISIBILITY_MASK = 0x0000000C; 809 810 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 811 812 /** 813 * This view is enabled. Interpretation varies by subclass. 814 * Use with ENABLED_MASK when calling setFlags. 815 * {@hide} 816 */ 817 static final int ENABLED = 0x00000000; 818 819 /** 820 * This view is disabled. Interpretation varies by subclass. 821 * Use with ENABLED_MASK when calling setFlags. 822 * {@hide} 823 */ 824 static final int DISABLED = 0x00000020; 825 826 /** 827 * Mask for use with setFlags indicating bits used for indicating whether 828 * this view is enabled 829 * {@hide} 830 */ 831 static final int ENABLED_MASK = 0x00000020; 832 833 /** 834 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 835 * called and further optimizations will be performed. It is okay to have 836 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 837 * {@hide} 838 */ 839 static final int WILL_NOT_DRAW = 0x00000080; 840 841 /** 842 * Mask for use with setFlags indicating bits used for indicating whether 843 * this view is will draw 844 * {@hide} 845 */ 846 static final int DRAW_MASK = 0x00000080; 847 848 /** 849 * <p>This view doesn't show scrollbars.</p> 850 * {@hide} 851 */ 852 static final int SCROLLBARS_NONE = 0x00000000; 853 854 /** 855 * <p>This view shows horizontal scrollbars.</p> 856 * {@hide} 857 */ 858 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 859 860 /** 861 * <p>This view shows vertical scrollbars.</p> 862 * {@hide} 863 */ 864 static final int SCROLLBARS_VERTICAL = 0x00000200; 865 866 /** 867 * <p>Mask for use with setFlags indicating bits used for indicating which 868 * scrollbars are enabled.</p> 869 * {@hide} 870 */ 871 static final int SCROLLBARS_MASK = 0x00000300; 872 873 /** 874 * Indicates that the view should filter touches when its window is obscured. 875 * Refer to the class comments for more information about this security feature. 876 * {@hide} 877 */ 878 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 879 880 /** 881 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 882 * that they are optional and should be skipped if the window has 883 * requested system UI flags that ignore those insets for layout. 884 */ 885 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 886 887 /** 888 * <p>This view doesn't show fading edges.</p> 889 * {@hide} 890 */ 891 static final int FADING_EDGE_NONE = 0x00000000; 892 893 /** 894 * <p>This view shows horizontal fading edges.</p> 895 * {@hide} 896 */ 897 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 898 899 /** 900 * <p>This view shows vertical fading edges.</p> 901 * {@hide} 902 */ 903 static final int FADING_EDGE_VERTICAL = 0x00002000; 904 905 /** 906 * <p>Mask for use with setFlags indicating bits used for indicating which 907 * fading edges are enabled.</p> 908 * {@hide} 909 */ 910 static final int FADING_EDGE_MASK = 0x00003000; 911 912 /** 913 * <p>Indicates this view can be clicked. When clickable, a View reacts 914 * to clicks by notifying the OnClickListener.<p> 915 * {@hide} 916 */ 917 static final int CLICKABLE = 0x00004000; 918 919 /** 920 * <p>Indicates this view is caching its drawing into a bitmap.</p> 921 * {@hide} 922 */ 923 static final int DRAWING_CACHE_ENABLED = 0x00008000; 924 925 /** 926 * <p>Indicates that no icicle should be saved for this view.<p> 927 * {@hide} 928 */ 929 static final int SAVE_DISABLED = 0x000010000; 930 931 /** 932 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 933 * property.</p> 934 * {@hide} 935 */ 936 static final int SAVE_DISABLED_MASK = 0x000010000; 937 938 /** 939 * <p>Indicates that no drawing cache should ever be created for this view.<p> 940 * {@hide} 941 */ 942 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 943 944 /** 945 * <p>Indicates this view can take / keep focus when int touch mode.</p> 946 * {@hide} 947 */ 948 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 949 950 /** @hide */ 951 @Retention(RetentionPolicy.SOURCE) 952 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 953 public @interface DrawingCacheQuality {} 954 955 /** 956 * <p>Enables low quality mode for the drawing cache.</p> 957 */ 958 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 959 960 /** 961 * <p>Enables high quality mode for the drawing cache.</p> 962 */ 963 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 964 965 /** 966 * <p>Enables automatic quality mode for the drawing cache.</p> 967 */ 968 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 969 970 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 971 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 972 }; 973 974 /** 975 * <p>Mask for use with setFlags indicating bits used for the cache 976 * quality property.</p> 977 * {@hide} 978 */ 979 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 980 981 /** 982 * <p> 983 * Indicates this view can be long clicked. When long clickable, a View 984 * reacts to long clicks by notifying the OnLongClickListener or showing a 985 * context menu. 986 * </p> 987 * {@hide} 988 */ 989 static final int LONG_CLICKABLE = 0x00200000; 990 991 /** 992 * <p>Indicates that this view gets its drawable states from its direct parent 993 * and ignores its original internal states.</p> 994 * 995 * @hide 996 */ 997 static final int DUPLICATE_PARENT_STATE = 0x00400000; 998 999 /** 1000 * <p> 1001 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1002 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1003 * OnContextClickListener. 1004 * </p> 1005 * {@hide} 1006 */ 1007 static final int CONTEXT_CLICKABLE = 0x00800000; 1008 1009 1010 /** @hide */ 1011 @IntDef({ 1012 SCROLLBARS_INSIDE_OVERLAY, 1013 SCROLLBARS_INSIDE_INSET, 1014 SCROLLBARS_OUTSIDE_OVERLAY, 1015 SCROLLBARS_OUTSIDE_INSET 1016 }) 1017 @Retention(RetentionPolicy.SOURCE) 1018 public @interface ScrollBarStyle {} 1019 1020 /** 1021 * The scrollbar style to display the scrollbars inside the content area, 1022 * without increasing the padding. The scrollbars will be overlaid with 1023 * translucency on the view's content. 1024 */ 1025 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1026 1027 /** 1028 * The scrollbar style to display the scrollbars inside the padded area, 1029 * increasing the padding of the view. The scrollbars will not overlap the 1030 * content area of the view. 1031 */ 1032 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1033 1034 /** 1035 * The scrollbar style to display the scrollbars at the edge of the view, 1036 * without increasing the padding. The scrollbars will be overlaid with 1037 * translucency. 1038 */ 1039 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1040 1041 /** 1042 * The scrollbar style to display the scrollbars at the edge of the view, 1043 * increasing the padding of the view. The scrollbars will only overlap the 1044 * background, if any. 1045 */ 1046 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1047 1048 /** 1049 * Mask to check if the scrollbar style is overlay or inset. 1050 * {@hide} 1051 */ 1052 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1053 1054 /** 1055 * Mask to check if the scrollbar style is inside or outside. 1056 * {@hide} 1057 */ 1058 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1059 1060 /** 1061 * Mask for scrollbar style. 1062 * {@hide} 1063 */ 1064 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1065 1066 /** 1067 * View flag indicating that the screen should remain on while the 1068 * window containing this view is visible to the user. This effectively 1069 * takes care of automatically setting the WindowManager's 1070 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1071 */ 1072 public static final int KEEP_SCREEN_ON = 0x04000000; 1073 1074 /** 1075 * View flag indicating whether this view should have sound effects enabled 1076 * for events such as clicking and touching. 1077 */ 1078 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1079 1080 /** 1081 * View flag indicating whether this view should have haptic feedback 1082 * enabled for events such as long presses. 1083 */ 1084 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1085 1086 /** 1087 * <p>Indicates that the view hierarchy should stop saving state when 1088 * it reaches this view. If state saving is initiated immediately at 1089 * the view, it will be allowed. 1090 * {@hide} 1091 */ 1092 static final int PARENT_SAVE_DISABLED = 0x20000000; 1093 1094 /** 1095 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1096 * {@hide} 1097 */ 1098 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1099 1100 /** @hide */ 1101 @IntDef(flag = true, 1102 value = { 1103 FOCUSABLES_ALL, 1104 FOCUSABLES_TOUCH_MODE 1105 }) 1106 @Retention(RetentionPolicy.SOURCE) 1107 public @interface FocusableMode {} 1108 1109 /** 1110 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1111 * should add all focusable Views regardless if they are focusable in touch mode. 1112 */ 1113 public static final int FOCUSABLES_ALL = 0x00000000; 1114 1115 /** 1116 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1117 * should add only Views focusable in touch mode. 1118 */ 1119 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1120 1121 /** @hide */ 1122 @IntDef({ 1123 FOCUS_BACKWARD, 1124 FOCUS_FORWARD, 1125 FOCUS_LEFT, 1126 FOCUS_UP, 1127 FOCUS_RIGHT, 1128 FOCUS_DOWN 1129 }) 1130 @Retention(RetentionPolicy.SOURCE) 1131 public @interface FocusDirection {} 1132 1133 /** @hide */ 1134 @IntDef({ 1135 FOCUS_LEFT, 1136 FOCUS_UP, 1137 FOCUS_RIGHT, 1138 FOCUS_DOWN 1139 }) 1140 @Retention(RetentionPolicy.SOURCE) 1141 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1142 1143 /** 1144 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1145 * item. 1146 */ 1147 public static final int FOCUS_BACKWARD = 0x00000001; 1148 1149 /** 1150 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1151 * item. 1152 */ 1153 public static final int FOCUS_FORWARD = 0x00000002; 1154 1155 /** 1156 * Use with {@link #focusSearch(int)}. Move focus to the left. 1157 */ 1158 public static final int FOCUS_LEFT = 0x00000011; 1159 1160 /** 1161 * Use with {@link #focusSearch(int)}. Move focus up. 1162 */ 1163 public static final int FOCUS_UP = 0x00000021; 1164 1165 /** 1166 * Use with {@link #focusSearch(int)}. Move focus to the right. 1167 */ 1168 public static final int FOCUS_RIGHT = 0x00000042; 1169 1170 /** 1171 * Use with {@link #focusSearch(int)}. Move focus down. 1172 */ 1173 public static final int FOCUS_DOWN = 0x00000082; 1174 1175 /** 1176 * Bits of {@link #getMeasuredWidthAndState()} and 1177 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1178 */ 1179 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1180 1181 /** 1182 * Bits of {@link #getMeasuredWidthAndState()} and 1183 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1184 */ 1185 public static final int MEASURED_STATE_MASK = 0xff000000; 1186 1187 /** 1188 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1189 * for functions that combine both width and height into a single int, 1190 * such as {@link #getMeasuredState()} and the childState argument of 1191 * {@link #resolveSizeAndState(int, int, int)}. 1192 */ 1193 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1194 1195 /** 1196 * Bit of {@link #getMeasuredWidthAndState()} and 1197 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1198 * is smaller that the space the view would like to have. 1199 */ 1200 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1201 1202 /** 1203 * Base View state sets 1204 */ 1205 // Singles 1206 /** 1207 * Indicates the view has no states set. States are used with 1208 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1209 * view depending on its state. 1210 * 1211 * @see android.graphics.drawable.Drawable 1212 * @see #getDrawableState() 1213 */ 1214 protected static final int[] EMPTY_STATE_SET; 1215 /** 1216 * Indicates the view is enabled. States are used with 1217 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1218 * view depending on its state. 1219 * 1220 * @see android.graphics.drawable.Drawable 1221 * @see #getDrawableState() 1222 */ 1223 protected static final int[] ENABLED_STATE_SET; 1224 /** 1225 * Indicates the view is focused. States are used with 1226 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1227 * view depending on its state. 1228 * 1229 * @see android.graphics.drawable.Drawable 1230 * @see #getDrawableState() 1231 */ 1232 protected static final int[] FOCUSED_STATE_SET; 1233 /** 1234 * Indicates the view is selected. States are used with 1235 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1236 * view depending on its state. 1237 * 1238 * @see android.graphics.drawable.Drawable 1239 * @see #getDrawableState() 1240 */ 1241 protected static final int[] SELECTED_STATE_SET; 1242 /** 1243 * Indicates the view is pressed. States are used with 1244 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1245 * view depending on its state. 1246 * 1247 * @see android.graphics.drawable.Drawable 1248 * @see #getDrawableState() 1249 */ 1250 protected static final int[] PRESSED_STATE_SET; 1251 /** 1252 * Indicates the view's window has focus. States are used with 1253 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1254 * view depending on its state. 1255 * 1256 * @see android.graphics.drawable.Drawable 1257 * @see #getDrawableState() 1258 */ 1259 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1260 // Doubles 1261 /** 1262 * Indicates the view is enabled and has the focus. 1263 * 1264 * @see #ENABLED_STATE_SET 1265 * @see #FOCUSED_STATE_SET 1266 */ 1267 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1268 /** 1269 * Indicates the view is enabled and selected. 1270 * 1271 * @see #ENABLED_STATE_SET 1272 * @see #SELECTED_STATE_SET 1273 */ 1274 protected static final int[] ENABLED_SELECTED_STATE_SET; 1275 /** 1276 * Indicates the view is enabled and that its window has focus. 1277 * 1278 * @see #ENABLED_STATE_SET 1279 * @see #WINDOW_FOCUSED_STATE_SET 1280 */ 1281 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1282 /** 1283 * Indicates the view is focused and selected. 1284 * 1285 * @see #FOCUSED_STATE_SET 1286 * @see #SELECTED_STATE_SET 1287 */ 1288 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1289 /** 1290 * Indicates the view has the focus and that its window has the focus. 1291 * 1292 * @see #FOCUSED_STATE_SET 1293 * @see #WINDOW_FOCUSED_STATE_SET 1294 */ 1295 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1296 /** 1297 * Indicates the view is selected and that its window has the focus. 1298 * 1299 * @see #SELECTED_STATE_SET 1300 * @see #WINDOW_FOCUSED_STATE_SET 1301 */ 1302 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1303 // Triples 1304 /** 1305 * Indicates the view is enabled, focused and selected. 1306 * 1307 * @see #ENABLED_STATE_SET 1308 * @see #FOCUSED_STATE_SET 1309 * @see #SELECTED_STATE_SET 1310 */ 1311 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1312 /** 1313 * Indicates the view is enabled, focused and its window has the focus. 1314 * 1315 * @see #ENABLED_STATE_SET 1316 * @see #FOCUSED_STATE_SET 1317 * @see #WINDOW_FOCUSED_STATE_SET 1318 */ 1319 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1320 /** 1321 * Indicates the view is enabled, selected and its window has the focus. 1322 * 1323 * @see #ENABLED_STATE_SET 1324 * @see #SELECTED_STATE_SET 1325 * @see #WINDOW_FOCUSED_STATE_SET 1326 */ 1327 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1328 /** 1329 * Indicates the view is focused, selected and its window has the focus. 1330 * 1331 * @see #FOCUSED_STATE_SET 1332 * @see #SELECTED_STATE_SET 1333 * @see #WINDOW_FOCUSED_STATE_SET 1334 */ 1335 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1336 /** 1337 * Indicates the view is enabled, focused, selected and its window 1338 * has the focus. 1339 * 1340 * @see #ENABLED_STATE_SET 1341 * @see #FOCUSED_STATE_SET 1342 * @see #SELECTED_STATE_SET 1343 * @see #WINDOW_FOCUSED_STATE_SET 1344 */ 1345 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1346 /** 1347 * Indicates the view is pressed and its window has the focus. 1348 * 1349 * @see #PRESSED_STATE_SET 1350 * @see #WINDOW_FOCUSED_STATE_SET 1351 */ 1352 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1353 /** 1354 * Indicates the view is pressed and selected. 1355 * 1356 * @see #PRESSED_STATE_SET 1357 * @see #SELECTED_STATE_SET 1358 */ 1359 protected static final int[] PRESSED_SELECTED_STATE_SET; 1360 /** 1361 * Indicates the view is pressed, selected and its window has the focus. 1362 * 1363 * @see #PRESSED_STATE_SET 1364 * @see #SELECTED_STATE_SET 1365 * @see #WINDOW_FOCUSED_STATE_SET 1366 */ 1367 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1368 /** 1369 * Indicates the view is pressed and focused. 1370 * 1371 * @see #PRESSED_STATE_SET 1372 * @see #FOCUSED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed, focused and its window has the focus. 1377 * 1378 * @see #PRESSED_STATE_SET 1379 * @see #FOCUSED_STATE_SET 1380 * @see #WINDOW_FOCUSED_STATE_SET 1381 */ 1382 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1383 /** 1384 * Indicates the view is pressed, focused and selected. 1385 * 1386 * @see #PRESSED_STATE_SET 1387 * @see #SELECTED_STATE_SET 1388 * @see #FOCUSED_STATE_SET 1389 */ 1390 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1391 /** 1392 * Indicates the view is pressed, focused, selected and its window has the focus. 1393 * 1394 * @see #PRESSED_STATE_SET 1395 * @see #FOCUSED_STATE_SET 1396 * @see #SELECTED_STATE_SET 1397 * @see #WINDOW_FOCUSED_STATE_SET 1398 */ 1399 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1400 /** 1401 * Indicates the view is pressed and enabled. 1402 * 1403 * @see #PRESSED_STATE_SET 1404 * @see #ENABLED_STATE_SET 1405 */ 1406 protected static final int[] PRESSED_ENABLED_STATE_SET; 1407 /** 1408 * Indicates the view is pressed, enabled and its window has the focus. 1409 * 1410 * @see #PRESSED_STATE_SET 1411 * @see #ENABLED_STATE_SET 1412 * @see #WINDOW_FOCUSED_STATE_SET 1413 */ 1414 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1415 /** 1416 * Indicates the view is pressed, enabled and selected. 1417 * 1418 * @see #PRESSED_STATE_SET 1419 * @see #ENABLED_STATE_SET 1420 * @see #SELECTED_STATE_SET 1421 */ 1422 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1423 /** 1424 * Indicates the view is pressed, enabled, selected and its window has the 1425 * focus. 1426 * 1427 * @see #PRESSED_STATE_SET 1428 * @see #ENABLED_STATE_SET 1429 * @see #SELECTED_STATE_SET 1430 * @see #WINDOW_FOCUSED_STATE_SET 1431 */ 1432 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1433 /** 1434 * Indicates the view is pressed, enabled and focused. 1435 * 1436 * @see #PRESSED_STATE_SET 1437 * @see #ENABLED_STATE_SET 1438 * @see #FOCUSED_STATE_SET 1439 */ 1440 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1441 /** 1442 * Indicates the view is pressed, enabled, focused and its window has the 1443 * focus. 1444 * 1445 * @see #PRESSED_STATE_SET 1446 * @see #ENABLED_STATE_SET 1447 * @see #FOCUSED_STATE_SET 1448 * @see #WINDOW_FOCUSED_STATE_SET 1449 */ 1450 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1451 /** 1452 * Indicates the view is pressed, enabled, focused and selected. 1453 * 1454 * @see #PRESSED_STATE_SET 1455 * @see #ENABLED_STATE_SET 1456 * @see #SELECTED_STATE_SET 1457 * @see #FOCUSED_STATE_SET 1458 */ 1459 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1460 /** 1461 * Indicates the view is pressed, enabled, focused, selected and its window 1462 * has the focus. 1463 * 1464 * @see #PRESSED_STATE_SET 1465 * @see #ENABLED_STATE_SET 1466 * @see #SELECTED_STATE_SET 1467 * @see #FOCUSED_STATE_SET 1468 * @see #WINDOW_FOCUSED_STATE_SET 1469 */ 1470 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1471 1472 static { 1473 EMPTY_STATE_SET = StateSet.get(0); 1474 1475 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1476 1477 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1478 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1479 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1480 1481 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1482 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1483 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1484 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1485 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1486 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1487 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1488 | StateSet.VIEW_STATE_FOCUSED); 1489 1490 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1491 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1492 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1493 ENABLED_SELECTED_STATE_SET = StateSet.get( 1494 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1495 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1496 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1497 | StateSet.VIEW_STATE_ENABLED); 1498 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1499 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1500 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1501 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1502 | StateSet.VIEW_STATE_ENABLED); 1503 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1504 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1505 | StateSet.VIEW_STATE_ENABLED); 1506 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1507 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1508 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1509 1510 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1511 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1512 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1513 PRESSED_SELECTED_STATE_SET = StateSet.get( 1514 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1515 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1516 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1517 | StateSet.VIEW_STATE_PRESSED); 1518 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1519 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1520 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1521 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1522 | StateSet.VIEW_STATE_PRESSED); 1523 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1524 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1525 | StateSet.VIEW_STATE_PRESSED); 1526 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1527 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1528 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1529 PRESSED_ENABLED_STATE_SET = StateSet.get( 1530 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1531 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1532 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1533 | StateSet.VIEW_STATE_PRESSED); 1534 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1535 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1536 | StateSet.VIEW_STATE_PRESSED); 1537 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1538 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1539 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1540 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1541 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1542 | StateSet.VIEW_STATE_PRESSED); 1543 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1544 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1545 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1546 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1547 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1548 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1549 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1550 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1551 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1552 | StateSet.VIEW_STATE_PRESSED); 1553 } 1554 1555 /** 1556 * Accessibility event types that are dispatched for text population. 1557 */ 1558 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1559 AccessibilityEvent.TYPE_VIEW_CLICKED 1560 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1561 | AccessibilityEvent.TYPE_VIEW_SELECTED 1562 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1563 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1564 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1565 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1566 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1567 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1568 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1569 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1570 1571 /** 1572 * Temporary Rect currently for use in setBackground(). This will probably 1573 * be extended in the future to hold our own class with more than just 1574 * a Rect. :) 1575 */ 1576 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1577 1578 /** 1579 * Map used to store views' tags. 1580 */ 1581 private SparseArray<Object> mKeyedTags; 1582 1583 /** 1584 * The next available accessibility id. 1585 */ 1586 private static int sNextAccessibilityViewId; 1587 1588 /** 1589 * The animation currently associated with this view. 1590 * @hide 1591 */ 1592 protected Animation mCurrentAnimation = null; 1593 1594 /** 1595 * Width as measured during measure pass. 1596 * {@hide} 1597 */ 1598 @ViewDebug.ExportedProperty(category = "measurement") 1599 int mMeasuredWidth; 1600 1601 /** 1602 * Height as measured during measure pass. 1603 * {@hide} 1604 */ 1605 @ViewDebug.ExportedProperty(category = "measurement") 1606 int mMeasuredHeight; 1607 1608 /** 1609 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1610 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1611 * its display list. This flag, used only when hw accelerated, allows us to clear the 1612 * flag while retaining this information until it's needed (at getDisplayList() time and 1613 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1614 * 1615 * {@hide} 1616 */ 1617 boolean mRecreateDisplayList = false; 1618 1619 /** 1620 * The view's identifier. 1621 * {@hide} 1622 * 1623 * @see #setId(int) 1624 * @see #getId() 1625 */ 1626 @IdRes 1627 @ViewDebug.ExportedProperty(resolveId = true) 1628 int mID = NO_ID; 1629 1630 /** 1631 * The stable ID of this view for accessibility purposes. 1632 */ 1633 int mAccessibilityViewId = NO_ID; 1634 1635 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1636 1637 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1638 1639 /** 1640 * The view's tag. 1641 * {@hide} 1642 * 1643 * @see #setTag(Object) 1644 * @see #getTag() 1645 */ 1646 protected Object mTag = null; 1647 1648 // for mPrivateFlags: 1649 /** {@hide} */ 1650 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1651 /** {@hide} */ 1652 static final int PFLAG_FOCUSED = 0x00000002; 1653 /** {@hide} */ 1654 static final int PFLAG_SELECTED = 0x00000004; 1655 /** {@hide} */ 1656 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1657 /** {@hide} */ 1658 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1659 /** {@hide} */ 1660 static final int PFLAG_DRAWN = 0x00000020; 1661 /** 1662 * When this flag is set, this view is running an animation on behalf of its 1663 * children and should therefore not cancel invalidate requests, even if they 1664 * lie outside of this view's bounds. 1665 * 1666 * {@hide} 1667 */ 1668 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1669 /** {@hide} */ 1670 static final int PFLAG_SKIP_DRAW = 0x00000080; 1671 /** {@hide} */ 1672 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1673 /** {@hide} */ 1674 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1675 /** {@hide} */ 1676 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1677 /** {@hide} */ 1678 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1679 /** {@hide} */ 1680 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1681 1682 private static final int PFLAG_PRESSED = 0x00004000; 1683 1684 /** {@hide} */ 1685 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1686 /** 1687 * Flag used to indicate that this view should be drawn once more (and only once 1688 * more) after its animation has completed. 1689 * {@hide} 1690 */ 1691 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1692 1693 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1694 1695 /** 1696 * Indicates that the View returned true when onSetAlpha() was called and that 1697 * the alpha must be restored. 1698 * {@hide} 1699 */ 1700 static final int PFLAG_ALPHA_SET = 0x00040000; 1701 1702 /** 1703 * Set by {@link #setScrollContainer(boolean)}. 1704 */ 1705 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1706 1707 /** 1708 * Set by {@link #setScrollContainer(boolean)}. 1709 */ 1710 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1711 1712 /** 1713 * View flag indicating whether this view was invalidated (fully or partially.) 1714 * 1715 * @hide 1716 */ 1717 static final int PFLAG_DIRTY = 0x00200000; 1718 1719 /** 1720 * View flag indicating whether this view was invalidated by an opaque 1721 * invalidate request. 1722 * 1723 * @hide 1724 */ 1725 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1726 1727 /** 1728 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1729 * 1730 * @hide 1731 */ 1732 static final int PFLAG_DIRTY_MASK = 0x00600000; 1733 1734 /** 1735 * Indicates whether the background is opaque. 1736 * 1737 * @hide 1738 */ 1739 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1740 1741 /** 1742 * Indicates whether the scrollbars are opaque. 1743 * 1744 * @hide 1745 */ 1746 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1747 1748 /** 1749 * Indicates whether the view is opaque. 1750 * 1751 * @hide 1752 */ 1753 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1754 1755 /** 1756 * Indicates a prepressed state; 1757 * the short time between ACTION_DOWN and recognizing 1758 * a 'real' press. Prepressed is used to recognize quick taps 1759 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1760 * 1761 * @hide 1762 */ 1763 private static final int PFLAG_PREPRESSED = 0x02000000; 1764 1765 /** 1766 * Indicates whether the view is temporarily detached. 1767 * 1768 * @hide 1769 */ 1770 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1771 1772 /** 1773 * Indicates that we should awaken scroll bars once attached 1774 * 1775 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 1776 * during window attachment and it is no longer needed. Feel free to repurpose it. 1777 * 1778 * @hide 1779 */ 1780 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1781 1782 /** 1783 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1784 * @hide 1785 */ 1786 private static final int PFLAG_HOVERED = 0x10000000; 1787 1788 /** 1789 * no longer needed, should be reused 1790 */ 1791 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1792 1793 /** {@hide} */ 1794 static final int PFLAG_ACTIVATED = 0x40000000; 1795 1796 /** 1797 * Indicates that this view was specifically invalidated, not just dirtied because some 1798 * child view was invalidated. The flag is used to determine when we need to recreate 1799 * a view's display list (as opposed to just returning a reference to its existing 1800 * display list). 1801 * 1802 * @hide 1803 */ 1804 static final int PFLAG_INVALIDATED = 0x80000000; 1805 1806 /** 1807 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1808 * 1809 * |-------|-------|-------|-------| 1810 * 1 PFLAG2_DRAG_CAN_ACCEPT 1811 * 1 PFLAG2_DRAG_HOVERED 1812 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1813 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1814 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1815 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1816 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1817 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1818 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1819 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1820 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1821 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1822 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1823 * 111 PFLAG2_TEXT_DIRECTION_MASK 1824 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1825 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1826 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1827 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1828 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1829 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1830 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1831 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1832 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1833 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1834 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1835 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1836 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1837 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1838 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1839 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1840 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1841 * 1 PFLAG2_VIEW_QUICK_REJECTED 1842 * 1 PFLAG2_PADDING_RESOLVED 1843 * 1 PFLAG2_DRAWABLE_RESOLVED 1844 * 1 PFLAG2_HAS_TRANSIENT_STATE 1845 * |-------|-------|-------|-------| 1846 */ 1847 1848 /** 1849 * Indicates that this view has reported that it can accept the current drag's content. 1850 * Cleared when the drag operation concludes. 1851 * @hide 1852 */ 1853 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1854 1855 /** 1856 * Indicates that this view is currently directly under the drag location in a 1857 * drag-and-drop operation involving content that it can accept. Cleared when 1858 * the drag exits the view, or when the drag operation concludes. 1859 * @hide 1860 */ 1861 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1862 1863 /** @hide */ 1864 @IntDef({ 1865 LAYOUT_DIRECTION_LTR, 1866 LAYOUT_DIRECTION_RTL, 1867 LAYOUT_DIRECTION_INHERIT, 1868 LAYOUT_DIRECTION_LOCALE 1869 }) 1870 @Retention(RetentionPolicy.SOURCE) 1871 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1872 public @interface LayoutDir {} 1873 1874 /** @hide */ 1875 @IntDef({ 1876 LAYOUT_DIRECTION_LTR, 1877 LAYOUT_DIRECTION_RTL 1878 }) 1879 @Retention(RetentionPolicy.SOURCE) 1880 public @interface ResolvedLayoutDir {} 1881 1882 /** 1883 * A flag to indicate that the layout direction of this view has not been defined yet. 1884 * @hide 1885 */ 1886 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 1887 1888 /** 1889 * Horizontal layout direction of this view is from Left to Right. 1890 * Use with {@link #setLayoutDirection}. 1891 */ 1892 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1893 1894 /** 1895 * Horizontal layout direction of this view is from Right to Left. 1896 * Use with {@link #setLayoutDirection}. 1897 */ 1898 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1899 1900 /** 1901 * Horizontal layout direction of this view is inherited from its parent. 1902 * Use with {@link #setLayoutDirection}. 1903 */ 1904 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1905 1906 /** 1907 * Horizontal layout direction of this view is from deduced from the default language 1908 * script for the locale. Use with {@link #setLayoutDirection}. 1909 */ 1910 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1911 1912 /** 1913 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1914 * @hide 1915 */ 1916 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1917 1918 /** 1919 * Mask for use with private flags indicating bits used for horizontal layout direction. 1920 * @hide 1921 */ 1922 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1923 1924 /** 1925 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1926 * right-to-left direction. 1927 * @hide 1928 */ 1929 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1930 1931 /** 1932 * Indicates whether the view horizontal layout direction has been resolved. 1933 * @hide 1934 */ 1935 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1936 1937 /** 1938 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1939 * @hide 1940 */ 1941 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1942 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1943 1944 /* 1945 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1946 * flag value. 1947 * @hide 1948 */ 1949 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1950 LAYOUT_DIRECTION_LTR, 1951 LAYOUT_DIRECTION_RTL, 1952 LAYOUT_DIRECTION_INHERIT, 1953 LAYOUT_DIRECTION_LOCALE 1954 }; 1955 1956 /** 1957 * Default horizontal layout direction. 1958 */ 1959 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1960 1961 /** 1962 * Default horizontal layout direction. 1963 * @hide 1964 */ 1965 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1966 1967 /** 1968 * Text direction is inherited through {@link ViewGroup} 1969 */ 1970 public static final int TEXT_DIRECTION_INHERIT = 0; 1971 1972 /** 1973 * Text direction is using "first strong algorithm". The first strong directional character 1974 * determines the paragraph direction. If there is no strong directional character, the 1975 * paragraph direction is the view's resolved layout direction. 1976 */ 1977 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1978 1979 /** 1980 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1981 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1982 * If there are neither, the paragraph direction is the view's resolved layout direction. 1983 */ 1984 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1985 1986 /** 1987 * Text direction is forced to LTR. 1988 */ 1989 public static final int TEXT_DIRECTION_LTR = 3; 1990 1991 /** 1992 * Text direction is forced to RTL. 1993 */ 1994 public static final int TEXT_DIRECTION_RTL = 4; 1995 1996 /** 1997 * Text direction is coming from the system Locale. 1998 */ 1999 public static final int TEXT_DIRECTION_LOCALE = 5; 2000 2001 /** 2002 * Text direction is using "first strong algorithm". The first strong directional character 2003 * determines the paragraph direction. If there is no strong directional character, the 2004 * paragraph direction is LTR. 2005 */ 2006 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2007 2008 /** 2009 * Text direction is using "first strong algorithm". The first strong directional character 2010 * determines the paragraph direction. If there is no strong directional character, the 2011 * paragraph direction is RTL. 2012 */ 2013 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2014 2015 /** 2016 * Default text direction is inherited 2017 */ 2018 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2019 2020 /** 2021 * Default resolved text direction 2022 * @hide 2023 */ 2024 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2025 2026 /** 2027 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2028 * @hide 2029 */ 2030 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2031 2032 /** 2033 * Mask for use with private flags indicating bits used for text direction. 2034 * @hide 2035 */ 2036 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2037 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2038 2039 /** 2040 * Array of text direction flags for mapping attribute "textDirection" to correct 2041 * flag value. 2042 * @hide 2043 */ 2044 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2045 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2046 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2047 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2048 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2049 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2050 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2051 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2052 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2053 }; 2054 2055 /** 2056 * Indicates whether the view text direction has been resolved. 2057 * @hide 2058 */ 2059 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2060 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2061 2062 /** 2063 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2064 * @hide 2065 */ 2066 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2067 2068 /** 2069 * Mask for use with private flags indicating bits used for resolved text direction. 2070 * @hide 2071 */ 2072 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2073 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2074 2075 /** 2076 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2077 * @hide 2078 */ 2079 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2080 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2081 2082 /** @hide */ 2083 @IntDef({ 2084 TEXT_ALIGNMENT_INHERIT, 2085 TEXT_ALIGNMENT_GRAVITY, 2086 TEXT_ALIGNMENT_CENTER, 2087 TEXT_ALIGNMENT_TEXT_START, 2088 TEXT_ALIGNMENT_TEXT_END, 2089 TEXT_ALIGNMENT_VIEW_START, 2090 TEXT_ALIGNMENT_VIEW_END 2091 }) 2092 @Retention(RetentionPolicy.SOURCE) 2093 public @interface TextAlignment {} 2094 2095 /** 2096 * Default text alignment. The text alignment of this View is inherited from its parent. 2097 * Use with {@link #setTextAlignment(int)} 2098 */ 2099 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2100 2101 /** 2102 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2103 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2104 * 2105 * Use with {@link #setTextAlignment(int)} 2106 */ 2107 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2108 2109 /** 2110 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2111 * 2112 * Use with {@link #setTextAlignment(int)} 2113 */ 2114 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2115 2116 /** 2117 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2118 * 2119 * Use with {@link #setTextAlignment(int)} 2120 */ 2121 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2122 2123 /** 2124 * Center the paragraph, e.g. ALIGN_CENTER. 2125 * 2126 * Use with {@link #setTextAlignment(int)} 2127 */ 2128 public static final int TEXT_ALIGNMENT_CENTER = 4; 2129 2130 /** 2131 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2132 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2133 * 2134 * Use with {@link #setTextAlignment(int)} 2135 */ 2136 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2137 2138 /** 2139 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2140 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2141 * 2142 * Use with {@link #setTextAlignment(int)} 2143 */ 2144 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2145 2146 /** 2147 * Default text alignment is inherited 2148 */ 2149 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2150 2151 /** 2152 * Default resolved text alignment 2153 * @hide 2154 */ 2155 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2156 2157 /** 2158 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2159 * @hide 2160 */ 2161 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2162 2163 /** 2164 * Mask for use with private flags indicating bits used for text alignment. 2165 * @hide 2166 */ 2167 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2168 2169 /** 2170 * Array of text direction flags for mapping attribute "textAlignment" to correct 2171 * flag value. 2172 * @hide 2173 */ 2174 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2175 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2176 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2177 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2178 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2179 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2180 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2181 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2182 }; 2183 2184 /** 2185 * Indicates whether the view text alignment has been resolved. 2186 * @hide 2187 */ 2188 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2189 2190 /** 2191 * Bit shift to get the resolved text alignment. 2192 * @hide 2193 */ 2194 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2195 2196 /** 2197 * Mask for use with private flags indicating bits used for text alignment. 2198 * @hide 2199 */ 2200 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2201 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2202 2203 /** 2204 * Indicates whether if the view text alignment has been resolved to gravity 2205 */ 2206 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2207 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2208 2209 // Accessiblity constants for mPrivateFlags2 2210 2211 /** 2212 * Shift for the bits in {@link #mPrivateFlags2} related to the 2213 * "importantForAccessibility" attribute. 2214 */ 2215 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2216 2217 /** 2218 * Automatically determine whether a view is important for accessibility. 2219 */ 2220 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2221 2222 /** 2223 * The view is important for accessibility. 2224 */ 2225 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2226 2227 /** 2228 * The view is not important for accessibility. 2229 */ 2230 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2231 2232 /** 2233 * The view is not important for accessibility, nor are any of its 2234 * descendant views. 2235 */ 2236 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2237 2238 /** 2239 * The default whether the view is important for accessibility. 2240 */ 2241 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2242 2243 /** 2244 * Mask for obtainig the bits which specify how to determine 2245 * whether a view is important for accessibility. 2246 */ 2247 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2248 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2249 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2250 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2251 2252 /** 2253 * Shift for the bits in {@link #mPrivateFlags2} related to the 2254 * "accessibilityLiveRegion" attribute. 2255 */ 2256 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2257 2258 /** 2259 * Live region mode specifying that accessibility services should not 2260 * automatically announce changes to this view. This is the default live 2261 * region mode for most views. 2262 * <p> 2263 * Use with {@link #setAccessibilityLiveRegion(int)}. 2264 */ 2265 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2266 2267 /** 2268 * Live region mode specifying that accessibility services should announce 2269 * changes to this view. 2270 * <p> 2271 * Use with {@link #setAccessibilityLiveRegion(int)}. 2272 */ 2273 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2274 2275 /** 2276 * Live region mode specifying that accessibility services should interrupt 2277 * ongoing speech to immediately announce changes to this view. 2278 * <p> 2279 * Use with {@link #setAccessibilityLiveRegion(int)}. 2280 */ 2281 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2282 2283 /** 2284 * The default whether the view is important for accessibility. 2285 */ 2286 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2287 2288 /** 2289 * Mask for obtaining the bits which specify a view's accessibility live 2290 * region mode. 2291 */ 2292 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2293 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2294 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2295 2296 /** 2297 * Flag indicating whether a view has accessibility focus. 2298 */ 2299 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2300 2301 /** 2302 * Flag whether the accessibility state of the subtree rooted at this view changed. 2303 */ 2304 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2305 2306 /** 2307 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2308 * is used to check whether later changes to the view's transform should invalidate the 2309 * view to force the quickReject test to run again. 2310 */ 2311 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2312 2313 /** 2314 * Flag indicating that start/end padding has been resolved into left/right padding 2315 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2316 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2317 * during measurement. In some special cases this is required such as when an adapter-based 2318 * view measures prospective children without attaching them to a window. 2319 */ 2320 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2321 2322 /** 2323 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2324 */ 2325 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2326 2327 /** 2328 * Indicates that the view is tracking some sort of transient state 2329 * that the app should not need to be aware of, but that the framework 2330 * should take special care to preserve. 2331 */ 2332 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2333 2334 /** 2335 * Group of bits indicating that RTL properties resolution is done. 2336 */ 2337 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2338 PFLAG2_TEXT_DIRECTION_RESOLVED | 2339 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2340 PFLAG2_PADDING_RESOLVED | 2341 PFLAG2_DRAWABLE_RESOLVED; 2342 2343 // There are a couple of flags left in mPrivateFlags2 2344 2345 /* End of masks for mPrivateFlags2 */ 2346 2347 /** 2348 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2349 * 2350 * |-------|-------|-------|-------| 2351 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2352 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2353 * 1 PFLAG3_IS_LAID_OUT 2354 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2355 * 1 PFLAG3_CALLED_SUPER 2356 * 1 PFLAG3_APPLYING_INSETS 2357 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2358 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2359 * 1 PFLAG3_ASSIST_BLOCKED 2360 * |-------|-------|-------|-------| 2361 */ 2362 2363 /** 2364 * Flag indicating that view has a transform animation set on it. This is used to track whether 2365 * an animation is cleared between successive frames, in order to tell the associated 2366 * DisplayList to clear its animation matrix. 2367 */ 2368 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2369 2370 /** 2371 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2372 * animation is cleared between successive frames, in order to tell the associated 2373 * DisplayList to restore its alpha value. 2374 */ 2375 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2376 2377 /** 2378 * Flag indicating that the view has been through at least one layout since it 2379 * was last attached to a window. 2380 */ 2381 static final int PFLAG3_IS_LAID_OUT = 0x4; 2382 2383 /** 2384 * Flag indicating that a call to measure() was skipped and should be done 2385 * instead when layout() is invoked. 2386 */ 2387 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2388 2389 /** 2390 * Flag indicating that an overridden method correctly called down to 2391 * the superclass implementation as required by the API spec. 2392 */ 2393 static final int PFLAG3_CALLED_SUPER = 0x10; 2394 2395 /** 2396 * Flag indicating that we're in the process of applying window insets. 2397 */ 2398 static final int PFLAG3_APPLYING_INSETS = 0x20; 2399 2400 /** 2401 * Flag indicating that we're in the process of fitting system windows using the old method. 2402 */ 2403 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2404 2405 /** 2406 * Flag indicating that nested scrolling is enabled for this view. 2407 * The view will optionally cooperate with views up its parent chain to allow for 2408 * integrated nested scrolling along the same axis. 2409 */ 2410 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2411 2412 /** 2413 * Flag indicating that the bottom scroll indicator should be displayed 2414 * when this view can scroll up. 2415 */ 2416 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2417 2418 /** 2419 * Flag indicating that the bottom scroll indicator should be displayed 2420 * when this view can scroll down. 2421 */ 2422 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2423 2424 /** 2425 * Flag indicating that the left scroll indicator should be displayed 2426 * when this view can scroll left. 2427 */ 2428 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2429 2430 /** 2431 * Flag indicating that the right scroll indicator should be displayed 2432 * when this view can scroll right. 2433 */ 2434 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2435 2436 /** 2437 * Flag indicating that the start scroll indicator should be displayed 2438 * when this view can scroll in the start direction. 2439 */ 2440 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2441 2442 /** 2443 * Flag indicating that the end scroll indicator should be displayed 2444 * when this view can scroll in the end direction. 2445 */ 2446 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2447 2448 /* End of masks for mPrivateFlags3 */ 2449 2450 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2451 2452 static final int SCROLL_INDICATORS_NONE = 0x0000; 2453 2454 /** 2455 * Mask for use with setFlags indicating bits used for indicating which 2456 * scroll indicators are enabled. 2457 */ 2458 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2459 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2460 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2461 | PFLAG3_SCROLL_INDICATOR_END; 2462 2463 /** 2464 * Left-shift required to translate between public scroll indicator flags 2465 * and internal PFLAGS3 flags. When used as a right-shift, translates 2466 * PFLAGS3 flags to public flags. 2467 */ 2468 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2469 2470 /** @hide */ 2471 @Retention(RetentionPolicy.SOURCE) 2472 @IntDef(flag = true, 2473 value = { 2474 SCROLL_INDICATOR_TOP, 2475 SCROLL_INDICATOR_BOTTOM, 2476 SCROLL_INDICATOR_LEFT, 2477 SCROLL_INDICATOR_RIGHT, 2478 SCROLL_INDICATOR_START, 2479 SCROLL_INDICATOR_END, 2480 }) 2481 public @interface ScrollIndicators {} 2482 2483 /** 2484 * Scroll indicator direction for the top edge of the view. 2485 * 2486 * @see #setScrollIndicators(int) 2487 * @see #setScrollIndicators(int, int) 2488 * @see #getScrollIndicators() 2489 */ 2490 public static final int SCROLL_INDICATOR_TOP = 2491 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2492 2493 /** 2494 * Scroll indicator direction for the bottom edge of the view. 2495 * 2496 * @see #setScrollIndicators(int) 2497 * @see #setScrollIndicators(int, int) 2498 * @see #getScrollIndicators() 2499 */ 2500 public static final int SCROLL_INDICATOR_BOTTOM = 2501 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2502 2503 /** 2504 * Scroll indicator direction for the left edge of the view. 2505 * 2506 * @see #setScrollIndicators(int) 2507 * @see #setScrollIndicators(int, int) 2508 * @see #getScrollIndicators() 2509 */ 2510 public static final int SCROLL_INDICATOR_LEFT = 2511 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2512 2513 /** 2514 * Scroll indicator direction for the right edge of the view. 2515 * 2516 * @see #setScrollIndicators(int) 2517 * @see #setScrollIndicators(int, int) 2518 * @see #getScrollIndicators() 2519 */ 2520 public static final int SCROLL_INDICATOR_RIGHT = 2521 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2522 2523 /** 2524 * Scroll indicator direction for the starting edge of the view. 2525 * <p> 2526 * Resolved according to the view's layout direction, see 2527 * {@link #getLayoutDirection()} for more information. 2528 * 2529 * @see #setScrollIndicators(int) 2530 * @see #setScrollIndicators(int, int) 2531 * @see #getScrollIndicators() 2532 */ 2533 public static final int SCROLL_INDICATOR_START = 2534 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2535 2536 /** 2537 * Scroll indicator direction for the ending edge of the view. 2538 * <p> 2539 * Resolved according to the view's layout direction, see 2540 * {@link #getLayoutDirection()} for more information. 2541 * 2542 * @see #setScrollIndicators(int) 2543 * @see #setScrollIndicators(int, int) 2544 * @see #getScrollIndicators() 2545 */ 2546 public static final int SCROLL_INDICATOR_END = 2547 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2548 2549 /** 2550 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2551 * into this view.<p> 2552 */ 2553 static final int PFLAG3_ASSIST_BLOCKED = 0x100; 2554 2555 /** 2556 * Always allow a user to over-scroll this view, provided it is a 2557 * view that can scroll. 2558 * 2559 * @see #getOverScrollMode() 2560 * @see #setOverScrollMode(int) 2561 */ 2562 public static final int OVER_SCROLL_ALWAYS = 0; 2563 2564 /** 2565 * Allow a user to over-scroll this view only if the content is large 2566 * enough to meaningfully scroll, provided it is a view that can scroll. 2567 * 2568 * @see #getOverScrollMode() 2569 * @see #setOverScrollMode(int) 2570 */ 2571 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2572 2573 /** 2574 * Never allow a user to over-scroll this view. 2575 * 2576 * @see #getOverScrollMode() 2577 * @see #setOverScrollMode(int) 2578 */ 2579 public static final int OVER_SCROLL_NEVER = 2; 2580 2581 /** 2582 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2583 * requested the system UI (status bar) to be visible (the default). 2584 * 2585 * @see #setSystemUiVisibility(int) 2586 */ 2587 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2588 2589 /** 2590 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2591 * system UI to enter an unobtrusive "low profile" mode. 2592 * 2593 * <p>This is for use in games, book readers, video players, or any other 2594 * "immersive" application where the usual system chrome is deemed too distracting. 2595 * 2596 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2597 * 2598 * @see #setSystemUiVisibility(int) 2599 */ 2600 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2601 2602 /** 2603 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2604 * system navigation be temporarily hidden. 2605 * 2606 * <p>This is an even less obtrusive state than that called for by 2607 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2608 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2609 * those to disappear. This is useful (in conjunction with the 2610 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2611 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2612 * window flags) for displaying content using every last pixel on the display. 2613 * 2614 * <p>There is a limitation: because navigation controls are so important, the least user 2615 * interaction will cause them to reappear immediately. When this happens, both 2616 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2617 * so that both elements reappear at the same time. 2618 * 2619 * @see #setSystemUiVisibility(int) 2620 */ 2621 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2622 2623 /** 2624 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2625 * into the normal fullscreen mode so that its content can take over the screen 2626 * while still allowing the user to interact with the application. 2627 * 2628 * <p>This has the same visual effect as 2629 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2630 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2631 * meaning that non-critical screen decorations (such as the status bar) will be 2632 * hidden while the user is in the View's window, focusing the experience on 2633 * that content. Unlike the window flag, if you are using ActionBar in 2634 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2635 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2636 * hide the action bar. 2637 * 2638 * <p>This approach to going fullscreen is best used over the window flag when 2639 * it is a transient state -- that is, the application does this at certain 2640 * points in its user interaction where it wants to allow the user to focus 2641 * on content, but not as a continuous state. For situations where the application 2642 * would like to simply stay full screen the entire time (such as a game that 2643 * wants to take over the screen), the 2644 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2645 * is usually a better approach. The state set here will be removed by the system 2646 * in various situations (such as the user moving to another application) like 2647 * the other system UI states. 2648 * 2649 * <p>When using this flag, the application should provide some easy facility 2650 * for the user to go out of it. A common example would be in an e-book 2651 * reader, where tapping on the screen brings back whatever screen and UI 2652 * decorations that had been hidden while the user was immersed in reading 2653 * the book. 2654 * 2655 * @see #setSystemUiVisibility(int) 2656 */ 2657 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2658 2659 /** 2660 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2661 * flags, we would like a stable view of the content insets given to 2662 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2663 * will always represent the worst case that the application can expect 2664 * as a continuous state. In the stock Android UI this is the space for 2665 * the system bar, nav bar, and status bar, but not more transient elements 2666 * such as an input method. 2667 * 2668 * The stable layout your UI sees is based on the system UI modes you can 2669 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2670 * then you will get a stable layout for changes of the 2671 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2672 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2673 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2674 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2675 * with a stable layout. (Note that you should avoid using 2676 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2677 * 2678 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2679 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2680 * then a hidden status bar will be considered a "stable" state for purposes 2681 * here. This allows your UI to continually hide the status bar, while still 2682 * using the system UI flags to hide the action bar while still retaining 2683 * a stable layout. Note that changing the window fullscreen flag will never 2684 * provide a stable layout for a clean transition. 2685 * 2686 * <p>If you are using ActionBar in 2687 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2688 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2689 * insets it adds to those given to the application. 2690 */ 2691 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2692 2693 /** 2694 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2695 * to be laid out as if it has requested 2696 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2697 * allows it to avoid artifacts when switching in and out of that mode, at 2698 * the expense that some of its user interface may be covered by screen 2699 * decorations when they are shown. You can perform layout of your inner 2700 * UI elements to account for the navigation system UI through the 2701 * {@link #fitSystemWindows(Rect)} method. 2702 */ 2703 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2704 2705 /** 2706 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2707 * to be laid out as if it has requested 2708 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2709 * allows it to avoid artifacts when switching in and out of that mode, at 2710 * the expense that some of its user interface may be covered by screen 2711 * decorations when they are shown. You can perform layout of your inner 2712 * UI elements to account for non-fullscreen system UI through the 2713 * {@link #fitSystemWindows(Rect)} method. 2714 */ 2715 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2716 2717 /** 2718 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2719 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2720 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2721 * user interaction. 2722 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2723 * has an effect when used in combination with that flag.</p> 2724 */ 2725 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2726 2727 /** 2728 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2729 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2730 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2731 * experience while also hiding the system bars. If this flag is not set, 2732 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2733 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2734 * if the user swipes from the top of the screen. 2735 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2736 * system gestures, such as swiping from the top of the screen. These transient system bars 2737 * will overlay app’s content, may have some degree of transparency, and will automatically 2738 * hide after a short timeout. 2739 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2740 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2741 * with one or both of those flags.</p> 2742 */ 2743 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2744 2745 /** 2746 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2747 * is compatible with light status bar backgrounds. 2748 * 2749 * <p>For this to take effect, the window must request 2750 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2751 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2752 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2753 * FLAG_TRANSLUCENT_STATUS}. 2754 * 2755 * @see android.R.attr#windowLightStatusBar 2756 */ 2757 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2758 2759 /** 2760 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2761 */ 2762 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2763 2764 /** 2765 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2766 */ 2767 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2768 2769 /** 2770 * @hide 2771 * 2772 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2773 * out of the public fields to keep the undefined bits out of the developer's way. 2774 * 2775 * Flag to make the status bar not expandable. Unless you also 2776 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2777 */ 2778 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2779 2780 /** 2781 * @hide 2782 * 2783 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2784 * out of the public fields to keep the undefined bits out of the developer's way. 2785 * 2786 * Flag to hide notification icons and scrolling ticker text. 2787 */ 2788 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2789 2790 /** 2791 * @hide 2792 * 2793 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2794 * out of the public fields to keep the undefined bits out of the developer's way. 2795 * 2796 * Flag to disable incoming notification alerts. This will not block 2797 * icons, but it will block sound, vibrating and other visual or aural notifications. 2798 */ 2799 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2800 2801 /** 2802 * @hide 2803 * 2804 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2805 * out of the public fields to keep the undefined bits out of the developer's way. 2806 * 2807 * Flag to hide only the scrolling ticker. Note that 2808 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2809 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2810 */ 2811 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2812 2813 /** 2814 * @hide 2815 * 2816 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2817 * out of the public fields to keep the undefined bits out of the developer's way. 2818 * 2819 * Flag to hide the center system info area. 2820 */ 2821 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2822 2823 /** 2824 * @hide 2825 * 2826 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2827 * out of the public fields to keep the undefined bits out of the developer's way. 2828 * 2829 * Flag to hide only the home button. Don't use this 2830 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2831 */ 2832 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2833 2834 /** 2835 * @hide 2836 * 2837 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2838 * out of the public fields to keep the undefined bits out of the developer's way. 2839 * 2840 * Flag to hide only the back button. Don't use this 2841 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2842 */ 2843 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2844 2845 /** 2846 * @hide 2847 * 2848 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2849 * out of the public fields to keep the undefined bits out of the developer's way. 2850 * 2851 * Flag to hide only the clock. You might use this if your activity has 2852 * its own clock making the status bar's clock redundant. 2853 */ 2854 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2855 2856 /** 2857 * @hide 2858 * 2859 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2860 * out of the public fields to keep the undefined bits out of the developer's way. 2861 * 2862 * Flag to hide only the recent apps button. Don't use this 2863 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2864 */ 2865 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2866 2867 /** 2868 * @hide 2869 * 2870 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2871 * out of the public fields to keep the undefined bits out of the developer's way. 2872 * 2873 * Flag to disable the global search gesture. Don't use this 2874 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2875 */ 2876 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2877 2878 /** 2879 * @hide 2880 * 2881 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2882 * out of the public fields to keep the undefined bits out of the developer's way. 2883 * 2884 * Flag to specify that the status bar is displayed in transient mode. 2885 */ 2886 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2887 2888 /** 2889 * @hide 2890 * 2891 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2892 * out of the public fields to keep the undefined bits out of the developer's way. 2893 * 2894 * Flag to specify that the navigation bar is displayed in transient mode. 2895 */ 2896 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2897 2898 /** 2899 * @hide 2900 * 2901 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2902 * out of the public fields to keep the undefined bits out of the developer's way. 2903 * 2904 * Flag to specify that the hidden status bar would like to be shown. 2905 */ 2906 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2907 2908 /** 2909 * @hide 2910 * 2911 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2912 * out of the public fields to keep the undefined bits out of the developer's way. 2913 * 2914 * Flag to specify that the hidden navigation bar would like to be shown. 2915 */ 2916 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2917 2918 /** 2919 * @hide 2920 * 2921 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2922 * out of the public fields to keep the undefined bits out of the developer's way. 2923 * 2924 * Flag to specify that the status bar is displayed in translucent mode. 2925 */ 2926 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2927 2928 /** 2929 * @hide 2930 * 2931 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2932 * out of the public fields to keep the undefined bits out of the developer's way. 2933 * 2934 * Flag to specify that the navigation bar is displayed in translucent mode. 2935 */ 2936 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2937 2938 /** 2939 * @hide 2940 * 2941 * Whether Recents is visible or not. 2942 */ 2943 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2944 2945 /** 2946 * @hide 2947 * 2948 * Makes system ui transparent. 2949 */ 2950 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2951 2952 /** 2953 * @hide 2954 */ 2955 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2956 2957 /** 2958 * These are the system UI flags that can be cleared by events outside 2959 * of an application. Currently this is just the ability to tap on the 2960 * screen while hiding the navigation bar to have it return. 2961 * @hide 2962 */ 2963 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2964 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2965 | SYSTEM_UI_FLAG_FULLSCREEN; 2966 2967 /** 2968 * Flags that can impact the layout in relation to system UI. 2969 */ 2970 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2971 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2972 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2973 2974 /** @hide */ 2975 @IntDef(flag = true, 2976 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2977 @Retention(RetentionPolicy.SOURCE) 2978 public @interface FindViewFlags {} 2979 2980 /** 2981 * Find views that render the specified text. 2982 * 2983 * @see #findViewsWithText(ArrayList, CharSequence, int) 2984 */ 2985 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2986 2987 /** 2988 * Find find views that contain the specified content description. 2989 * 2990 * @see #findViewsWithText(ArrayList, CharSequence, int) 2991 */ 2992 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2993 2994 /** 2995 * Find views that contain {@link AccessibilityNodeProvider}. Such 2996 * a View is a root of virtual view hierarchy and may contain the searched 2997 * text. If this flag is set Views with providers are automatically 2998 * added and it is a responsibility of the client to call the APIs of 2999 * the provider to determine whether the virtual tree rooted at this View 3000 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3001 * representing the virtual views with this text. 3002 * 3003 * @see #findViewsWithText(ArrayList, CharSequence, int) 3004 * 3005 * @hide 3006 */ 3007 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3008 3009 /** 3010 * The undefined cursor position. 3011 * 3012 * @hide 3013 */ 3014 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3015 3016 /** 3017 * Indicates that the screen has changed state and is now off. 3018 * 3019 * @see #onScreenStateChanged(int) 3020 */ 3021 public static final int SCREEN_STATE_OFF = 0x0; 3022 3023 /** 3024 * Indicates that the screen has changed state and is now on. 3025 * 3026 * @see #onScreenStateChanged(int) 3027 */ 3028 public static final int SCREEN_STATE_ON = 0x1; 3029 3030 /** 3031 * Indicates no axis of view scrolling. 3032 */ 3033 public static final int SCROLL_AXIS_NONE = 0; 3034 3035 /** 3036 * Indicates scrolling along the horizontal axis. 3037 */ 3038 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3039 3040 /** 3041 * Indicates scrolling along the vertical axis. 3042 */ 3043 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3044 3045 /** 3046 * Controls the over-scroll mode for this view. 3047 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3048 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3049 * and {@link #OVER_SCROLL_NEVER}. 3050 */ 3051 private int mOverScrollMode; 3052 3053 /** 3054 * The parent this view is attached to. 3055 * {@hide} 3056 * 3057 * @see #getParent() 3058 */ 3059 protected ViewParent mParent; 3060 3061 /** 3062 * {@hide} 3063 */ 3064 AttachInfo mAttachInfo; 3065 3066 /** 3067 * {@hide} 3068 */ 3069 @ViewDebug.ExportedProperty(flagMapping = { 3070 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3071 name = "FORCE_LAYOUT"), 3072 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3073 name = "LAYOUT_REQUIRED"), 3074 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3075 name = "DRAWING_CACHE_INVALID", outputIf = false), 3076 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3077 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3078 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3079 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3080 }, formatToHexString = true) 3081 int mPrivateFlags; 3082 int mPrivateFlags2; 3083 int mPrivateFlags3; 3084 3085 /** 3086 * This view's request for the visibility of the status bar. 3087 * @hide 3088 */ 3089 @ViewDebug.ExportedProperty(flagMapping = { 3090 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3091 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3092 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3093 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3094 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3095 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3096 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3097 equals = SYSTEM_UI_FLAG_VISIBLE, 3098 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3099 }, formatToHexString = true) 3100 int mSystemUiVisibility; 3101 3102 /** 3103 * Reference count for transient state. 3104 * @see #setHasTransientState(boolean) 3105 */ 3106 int mTransientStateCount = 0; 3107 3108 /** 3109 * Count of how many windows this view has been attached to. 3110 */ 3111 int mWindowAttachCount; 3112 3113 /** 3114 * The layout parameters associated with this view and used by the parent 3115 * {@link android.view.ViewGroup} to determine how this view should be 3116 * laid out. 3117 * {@hide} 3118 */ 3119 protected ViewGroup.LayoutParams mLayoutParams; 3120 3121 /** 3122 * The view flags hold various views states. 3123 * {@hide} 3124 */ 3125 @ViewDebug.ExportedProperty(formatToHexString = true) 3126 int mViewFlags; 3127 3128 static class TransformationInfo { 3129 /** 3130 * The transform matrix for the View. This transform is calculated internally 3131 * based on the translation, rotation, and scale properties. 3132 * 3133 * Do *not* use this variable directly; instead call getMatrix(), which will 3134 * load the value from the View's RenderNode. 3135 */ 3136 private final Matrix mMatrix = new Matrix(); 3137 3138 /** 3139 * The inverse transform matrix for the View. This transform is calculated 3140 * internally based on the translation, rotation, and scale properties. 3141 * 3142 * Do *not* use this variable directly; instead call getInverseMatrix(), 3143 * which will load the value from the View's RenderNode. 3144 */ 3145 private Matrix mInverseMatrix; 3146 3147 /** 3148 * The opacity of the View. This is a value from 0 to 1, where 0 means 3149 * completely transparent and 1 means completely opaque. 3150 */ 3151 @ViewDebug.ExportedProperty 3152 float mAlpha = 1f; 3153 3154 /** 3155 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3156 * property only used by transitions, which is composited with the other alpha 3157 * values to calculate the final visual alpha value. 3158 */ 3159 float mTransitionAlpha = 1f; 3160 } 3161 3162 TransformationInfo mTransformationInfo; 3163 3164 /** 3165 * Current clip bounds. to which all drawing of this view are constrained. 3166 */ 3167 Rect mClipBounds = null; 3168 3169 private boolean mLastIsOpaque; 3170 3171 /** 3172 * The distance in pixels from the left edge of this view's parent 3173 * to the left edge of this view. 3174 * {@hide} 3175 */ 3176 @ViewDebug.ExportedProperty(category = "layout") 3177 protected int mLeft; 3178 /** 3179 * The distance in pixels from the left edge of this view's parent 3180 * to the right edge of this view. 3181 * {@hide} 3182 */ 3183 @ViewDebug.ExportedProperty(category = "layout") 3184 protected int mRight; 3185 /** 3186 * The distance in pixels from the top edge of this view's parent 3187 * to the top edge of this view. 3188 * {@hide} 3189 */ 3190 @ViewDebug.ExportedProperty(category = "layout") 3191 protected int mTop; 3192 /** 3193 * The distance in pixels from the top edge of this view's parent 3194 * to the bottom edge of this view. 3195 * {@hide} 3196 */ 3197 @ViewDebug.ExportedProperty(category = "layout") 3198 protected int mBottom; 3199 3200 /** 3201 * The offset, in pixels, by which the content of this view is scrolled 3202 * horizontally. 3203 * {@hide} 3204 */ 3205 @ViewDebug.ExportedProperty(category = "scrolling") 3206 protected int mScrollX; 3207 /** 3208 * The offset, in pixels, by which the content of this view is scrolled 3209 * vertically. 3210 * {@hide} 3211 */ 3212 @ViewDebug.ExportedProperty(category = "scrolling") 3213 protected int mScrollY; 3214 3215 /** 3216 * The left padding in pixels, that is the distance in pixels between the 3217 * left edge of this view and the left edge of its content. 3218 * {@hide} 3219 */ 3220 @ViewDebug.ExportedProperty(category = "padding") 3221 protected int mPaddingLeft = 0; 3222 /** 3223 * The right padding in pixels, that is the distance in pixels between the 3224 * right edge of this view and the right edge of its content. 3225 * {@hide} 3226 */ 3227 @ViewDebug.ExportedProperty(category = "padding") 3228 protected int mPaddingRight = 0; 3229 /** 3230 * The top padding in pixels, that is the distance in pixels between the 3231 * top edge of this view and the top edge of its content. 3232 * {@hide} 3233 */ 3234 @ViewDebug.ExportedProperty(category = "padding") 3235 protected int mPaddingTop; 3236 /** 3237 * The bottom padding in pixels, that is the distance in pixels between the 3238 * bottom edge of this view and the bottom edge of its content. 3239 * {@hide} 3240 */ 3241 @ViewDebug.ExportedProperty(category = "padding") 3242 protected int mPaddingBottom; 3243 3244 /** 3245 * The layout insets in pixels, that is the distance in pixels between the 3246 * visible edges of this view its bounds. 3247 */ 3248 private Insets mLayoutInsets; 3249 3250 /** 3251 * Briefly describes the view and is primarily used for accessibility support. 3252 */ 3253 private CharSequence mContentDescription; 3254 3255 /** 3256 * Specifies the id of a view for which this view serves as a label for 3257 * accessibility purposes. 3258 */ 3259 private int mLabelForId = View.NO_ID; 3260 3261 /** 3262 * Predicate for matching labeled view id with its label for 3263 * accessibility purposes. 3264 */ 3265 private MatchLabelForPredicate mMatchLabelForPredicate; 3266 3267 /** 3268 * Specifies a view before which this one is visited in accessibility traversal. 3269 */ 3270 private int mAccessibilityTraversalBeforeId = NO_ID; 3271 3272 /** 3273 * Specifies a view after which this one is visited in accessibility traversal. 3274 */ 3275 private int mAccessibilityTraversalAfterId = NO_ID; 3276 3277 /** 3278 * Predicate for matching a view by its id. 3279 */ 3280 private MatchIdPredicate mMatchIdPredicate; 3281 3282 /** 3283 * Cache the paddingRight set by the user to append to the scrollbar's size. 3284 * 3285 * @hide 3286 */ 3287 @ViewDebug.ExportedProperty(category = "padding") 3288 protected int mUserPaddingRight; 3289 3290 /** 3291 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3292 * 3293 * @hide 3294 */ 3295 @ViewDebug.ExportedProperty(category = "padding") 3296 protected int mUserPaddingBottom; 3297 3298 /** 3299 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3300 * 3301 * @hide 3302 */ 3303 @ViewDebug.ExportedProperty(category = "padding") 3304 protected int mUserPaddingLeft; 3305 3306 /** 3307 * Cache the paddingStart set by the user to append to the scrollbar's size. 3308 * 3309 */ 3310 @ViewDebug.ExportedProperty(category = "padding") 3311 int mUserPaddingStart; 3312 3313 /** 3314 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3315 * 3316 */ 3317 @ViewDebug.ExportedProperty(category = "padding") 3318 int mUserPaddingEnd; 3319 3320 /** 3321 * Cache initial left padding. 3322 * 3323 * @hide 3324 */ 3325 int mUserPaddingLeftInitial; 3326 3327 /** 3328 * Cache initial right padding. 3329 * 3330 * @hide 3331 */ 3332 int mUserPaddingRightInitial; 3333 3334 /** 3335 * Default undefined padding 3336 */ 3337 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3338 3339 /** 3340 * Cache if a left padding has been defined 3341 */ 3342 private boolean mLeftPaddingDefined = false; 3343 3344 /** 3345 * Cache if a right padding has been defined 3346 */ 3347 private boolean mRightPaddingDefined = false; 3348 3349 /** 3350 * @hide 3351 */ 3352 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3353 /** 3354 * @hide 3355 */ 3356 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3357 3358 private LongSparseLongArray mMeasureCache; 3359 3360 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3361 private Drawable mBackground; 3362 private TintInfo mBackgroundTint; 3363 3364 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3365 private ForegroundInfo mForegroundInfo; 3366 3367 private Drawable mScrollIndicatorDrawable; 3368 3369 /** 3370 * RenderNode used for backgrounds. 3371 * <p> 3372 * When non-null and valid, this is expected to contain an up-to-date copy 3373 * of the background drawable. It is cleared on temporary detach, and reset 3374 * on cleanup. 3375 */ 3376 private RenderNode mBackgroundRenderNode; 3377 3378 private int mBackgroundResource; 3379 private boolean mBackgroundSizeChanged; 3380 3381 private String mTransitionName; 3382 3383 static class TintInfo { 3384 ColorStateList mTintList; 3385 PorterDuff.Mode mTintMode; 3386 boolean mHasTintMode; 3387 boolean mHasTintList; 3388 } 3389 3390 private static class ForegroundInfo { 3391 private Drawable mDrawable; 3392 private TintInfo mTintInfo; 3393 private int mGravity = Gravity.FILL; 3394 private boolean mInsidePadding = true; 3395 private boolean mBoundsChanged = true; 3396 private final Rect mSelfBounds = new Rect(); 3397 private final Rect mOverlayBounds = new Rect(); 3398 } 3399 3400 static class ListenerInfo { 3401 /** 3402 * Listener used to dispatch focus change events. 3403 * This field should be made private, so it is hidden from the SDK. 3404 * {@hide} 3405 */ 3406 protected OnFocusChangeListener mOnFocusChangeListener; 3407 3408 /** 3409 * Listeners for layout change events. 3410 */ 3411 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3412 3413 protected OnScrollChangeListener mOnScrollChangeListener; 3414 3415 /** 3416 * Listeners for attach events. 3417 */ 3418 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3419 3420 /** 3421 * Listener used to dispatch click events. 3422 * This field should be made private, so it is hidden from the SDK. 3423 * {@hide} 3424 */ 3425 public OnClickListener mOnClickListener; 3426 3427 /** 3428 * Listener used to dispatch long click events. 3429 * This field should be made private, so it is hidden from the SDK. 3430 * {@hide} 3431 */ 3432 protected OnLongClickListener mOnLongClickListener; 3433 3434 /** 3435 * Listener used to dispatch context click events. This field should be made private, so it 3436 * is hidden from the SDK. 3437 * {@hide} 3438 */ 3439 protected OnContextClickListener mOnContextClickListener; 3440 3441 /** 3442 * Listener used to build the context menu. 3443 * This field should be made private, so it is hidden from the SDK. 3444 * {@hide} 3445 */ 3446 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3447 3448 private OnKeyListener mOnKeyListener; 3449 3450 private OnTouchListener mOnTouchListener; 3451 3452 private OnHoverListener mOnHoverListener; 3453 3454 private OnGenericMotionListener mOnGenericMotionListener; 3455 3456 private OnDragListener mOnDragListener; 3457 3458 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3459 3460 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3461 } 3462 3463 ListenerInfo mListenerInfo; 3464 3465 /** 3466 * The application environment this view lives in. 3467 * This field should be made private, so it is hidden from the SDK. 3468 * {@hide} 3469 */ 3470 @ViewDebug.ExportedProperty(deepExport = true) 3471 protected Context mContext; 3472 3473 private final Resources mResources; 3474 3475 private ScrollabilityCache mScrollCache; 3476 3477 private int[] mDrawableState = null; 3478 3479 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3480 3481 /** 3482 * Animator that automatically runs based on state changes. 3483 */ 3484 private StateListAnimator mStateListAnimator; 3485 3486 /** 3487 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3488 * the user may specify which view to go to next. 3489 */ 3490 private int mNextFocusLeftId = View.NO_ID; 3491 3492 /** 3493 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3494 * the user may specify which view to go to next. 3495 */ 3496 private int mNextFocusRightId = View.NO_ID; 3497 3498 /** 3499 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3500 * the user may specify which view to go to next. 3501 */ 3502 private int mNextFocusUpId = View.NO_ID; 3503 3504 /** 3505 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3506 * the user may specify which view to go to next. 3507 */ 3508 private int mNextFocusDownId = View.NO_ID; 3509 3510 /** 3511 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3512 * the user may specify which view to go to next. 3513 */ 3514 int mNextFocusForwardId = View.NO_ID; 3515 3516 private CheckForLongPress mPendingCheckForLongPress; 3517 private CheckForTap mPendingCheckForTap = null; 3518 private PerformClick mPerformClick; 3519 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3520 3521 private UnsetPressedState mUnsetPressedState; 3522 3523 /** 3524 * Whether the long press's action has been invoked. The tap's action is invoked on the 3525 * up event while a long press is invoked as soon as the long press duration is reached, so 3526 * a long press could be performed before the tap is checked, in which case the tap's action 3527 * should not be invoked. 3528 */ 3529 private boolean mHasPerformedLongPress; 3530 3531 /** 3532 * Whether a context click button is currently pressed down. This is true when the stylus is 3533 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3534 * pressed. This is false once the button is released or if the stylus has been lifted. 3535 */ 3536 private boolean mInContextButtonPress; 3537 3538 /** 3539 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3540 * true after a stylus button press has occured, when the next up event should not be recognized 3541 * as a tap. 3542 */ 3543 private boolean mIgnoreNextUpEvent; 3544 3545 /** 3546 * The minimum height of the view. We'll try our best to have the height 3547 * of this view to at least this amount. 3548 */ 3549 @ViewDebug.ExportedProperty(category = "measurement") 3550 private int mMinHeight; 3551 3552 /** 3553 * The minimum width of the view. We'll try our best to have the width 3554 * of this view to at least this amount. 3555 */ 3556 @ViewDebug.ExportedProperty(category = "measurement") 3557 private int mMinWidth; 3558 3559 /** 3560 * The delegate to handle touch events that are physically in this view 3561 * but should be handled by another view. 3562 */ 3563 private TouchDelegate mTouchDelegate = null; 3564 3565 /** 3566 * Solid color to use as a background when creating the drawing cache. Enables 3567 * the cache to use 16 bit bitmaps instead of 32 bit. 3568 */ 3569 private int mDrawingCacheBackgroundColor = 0; 3570 3571 /** 3572 * Special tree observer used when mAttachInfo is null. 3573 */ 3574 private ViewTreeObserver mFloatingTreeObserver; 3575 3576 /** 3577 * Cache the touch slop from the context that created the view. 3578 */ 3579 private int mTouchSlop; 3580 3581 /** 3582 * Object that handles automatic animation of view properties. 3583 */ 3584 private ViewPropertyAnimator mAnimator = null; 3585 3586 /** 3587 * Flag indicating that a drag can cross window boundaries. When 3588 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3589 * with this flag set, all visible applications will be able to participate 3590 * in the drag operation and receive the dragged content. 3591 * 3592 * @hide 3593 */ 3594 public static final int DRAG_FLAG_GLOBAL = 1; 3595 3596 /** 3597 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3598 */ 3599 private float mVerticalScrollFactor; 3600 3601 /** 3602 * Position of the vertical scroll bar. 3603 */ 3604 private int mVerticalScrollbarPosition; 3605 3606 /** 3607 * Position the scroll bar at the default position as determined by the system. 3608 */ 3609 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3610 3611 /** 3612 * Position the scroll bar along the left edge. 3613 */ 3614 public static final int SCROLLBAR_POSITION_LEFT = 1; 3615 3616 /** 3617 * Position the scroll bar along the right edge. 3618 */ 3619 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3620 3621 /** 3622 * Indicates that the view does not have a layer. 3623 * 3624 * @see #getLayerType() 3625 * @see #setLayerType(int, android.graphics.Paint) 3626 * @see #LAYER_TYPE_SOFTWARE 3627 * @see #LAYER_TYPE_HARDWARE 3628 */ 3629 public static final int LAYER_TYPE_NONE = 0; 3630 3631 /** 3632 * <p>Indicates that the view has a software layer. A software layer is backed 3633 * by a bitmap and causes the view to be rendered using Android's software 3634 * rendering pipeline, even if hardware acceleration is enabled.</p> 3635 * 3636 * <p>Software layers have various usages:</p> 3637 * <p>When the application is not using hardware acceleration, a software layer 3638 * is useful to apply a specific color filter and/or blending mode and/or 3639 * translucency to a view and all its children.</p> 3640 * <p>When the application is using hardware acceleration, a software layer 3641 * is useful to render drawing primitives not supported by the hardware 3642 * accelerated pipeline. It can also be used to cache a complex view tree 3643 * into a texture and reduce the complexity of drawing operations. For instance, 3644 * when animating a complex view tree with a translation, a software layer can 3645 * be used to render the view tree only once.</p> 3646 * <p>Software layers should be avoided when the affected view tree updates 3647 * often. Every update will require to re-render the software layer, which can 3648 * potentially be slow (particularly when hardware acceleration is turned on 3649 * since the layer will have to be uploaded into a hardware texture after every 3650 * update.)</p> 3651 * 3652 * @see #getLayerType() 3653 * @see #setLayerType(int, android.graphics.Paint) 3654 * @see #LAYER_TYPE_NONE 3655 * @see #LAYER_TYPE_HARDWARE 3656 */ 3657 public static final int LAYER_TYPE_SOFTWARE = 1; 3658 3659 /** 3660 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3661 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3662 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3663 * rendering pipeline, but only if hardware acceleration is turned on for the 3664 * view hierarchy. When hardware acceleration is turned off, hardware layers 3665 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3666 * 3667 * <p>A hardware layer is useful to apply a specific color filter and/or 3668 * blending mode and/or translucency to a view and all its children.</p> 3669 * <p>A hardware layer can be used to cache a complex view tree into a 3670 * texture and reduce the complexity of drawing operations. For instance, 3671 * when animating a complex view tree with a translation, a hardware layer can 3672 * be used to render the view tree only once.</p> 3673 * <p>A hardware layer can also be used to increase the rendering quality when 3674 * rotation transformations are applied on a view. It can also be used to 3675 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3676 * 3677 * @see #getLayerType() 3678 * @see #setLayerType(int, android.graphics.Paint) 3679 * @see #LAYER_TYPE_NONE 3680 * @see #LAYER_TYPE_SOFTWARE 3681 */ 3682 public static final int LAYER_TYPE_HARDWARE = 2; 3683 3684 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3685 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3686 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3687 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3688 }) 3689 int mLayerType = LAYER_TYPE_NONE; 3690 Paint mLayerPaint; 3691 3692 /** 3693 * Set to true when drawing cache is enabled and cannot be created. 3694 * 3695 * @hide 3696 */ 3697 public boolean mCachingFailed; 3698 private Bitmap mDrawingCache; 3699 private Bitmap mUnscaledDrawingCache; 3700 3701 /** 3702 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3703 * <p> 3704 * When non-null and valid, this is expected to contain an up-to-date copy 3705 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3706 * cleanup. 3707 */ 3708 final RenderNode mRenderNode; 3709 3710 /** 3711 * Set to true when the view is sending hover accessibility events because it 3712 * is the innermost hovered view. 3713 */ 3714 private boolean mSendingHoverAccessibilityEvents; 3715 3716 /** 3717 * Delegate for injecting accessibility functionality. 3718 */ 3719 AccessibilityDelegate mAccessibilityDelegate; 3720 3721 /** 3722 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3723 * and add/remove objects to/from the overlay directly through the Overlay methods. 3724 */ 3725 ViewOverlay mOverlay; 3726 3727 /** 3728 * The currently active parent view for receiving delegated nested scrolling events. 3729 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3730 * by {@link #stopNestedScroll()} at the same point where we clear 3731 * requestDisallowInterceptTouchEvent. 3732 */ 3733 private ViewParent mNestedScrollingParent; 3734 3735 /** 3736 * Consistency verifier for debugging purposes. 3737 * @hide 3738 */ 3739 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3740 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3741 new InputEventConsistencyVerifier(this, 0) : null; 3742 3743 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3744 3745 private int[] mTempNestedScrollConsumed; 3746 3747 /** 3748 * An overlay is going to draw this View instead of being drawn as part of this 3749 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3750 * when this view is invalidated. 3751 */ 3752 GhostView mGhostView; 3753 3754 /** 3755 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3756 * @hide 3757 */ 3758 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3759 public String[] mAttributes; 3760 3761 /** 3762 * Maps a Resource id to its name. 3763 */ 3764 private static SparseArray<String> mAttributeMap; 3765 3766 /** 3767 * @hide 3768 */ 3769 String mStartActivityRequestWho; 3770 3771 /** 3772 * Simple constructor to use when creating a view from code. 3773 * 3774 * @param context The Context the view is running in, through which it can 3775 * access the current theme, resources, etc. 3776 */ 3777 public View(Context context) { 3778 mContext = context; 3779 mResources = context != null ? context.getResources() : null; 3780 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3781 // Set some flags defaults 3782 mPrivateFlags2 = 3783 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3784 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3785 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3786 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3787 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3788 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3789 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3790 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3791 mUserPaddingStart = UNDEFINED_PADDING; 3792 mUserPaddingEnd = UNDEFINED_PADDING; 3793 mRenderNode = RenderNode.create(getClass().getName(), this); 3794 3795 if (!sCompatibilityDone && context != null) { 3796 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3797 3798 // Older apps may need this compatibility hack for measurement. 3799 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3800 3801 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3802 // of whether a layout was requested on that View. 3803 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3804 3805 Canvas.sCompatibilityRestore = targetSdkVersion < MNC; 3806 3807 // In MNC and newer, our widgets can pass a "hint" value in the size 3808 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 3809 // know what the expected parent size is going to be, so e.g. list items can size 3810 // themselves at 1/3 the size of their container. It breaks older apps though, 3811 // specifically apps that use some popular open source libraries. 3812 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < MNC; 3813 3814 sCompatibilityDone = true; 3815 } 3816 } 3817 3818 /** 3819 * Constructor that is called when inflating a view from XML. This is called 3820 * when a view is being constructed from an XML file, supplying attributes 3821 * that were specified in the XML file. This version uses a default style of 3822 * 0, so the only attribute values applied are those in the Context's Theme 3823 * and the given AttributeSet. 3824 * 3825 * <p> 3826 * The method onFinishInflate() will be called after all children have been 3827 * added. 3828 * 3829 * @param context The Context the view is running in, through which it can 3830 * access the current theme, resources, etc. 3831 * @param attrs The attributes of the XML tag that is inflating the view. 3832 * @see #View(Context, AttributeSet, int) 3833 */ 3834 public View(Context context, @Nullable AttributeSet attrs) { 3835 this(context, attrs, 0); 3836 } 3837 3838 /** 3839 * Perform inflation from XML and apply a class-specific base style from a 3840 * theme attribute. This constructor of View allows subclasses to use their 3841 * own base style when they are inflating. For example, a Button class's 3842 * constructor would call this version of the super class constructor and 3843 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3844 * allows the theme's button style to modify all of the base view attributes 3845 * (in particular its background) as well as the Button class's attributes. 3846 * 3847 * @param context The Context the view is running in, through which it can 3848 * access the current theme, resources, etc. 3849 * @param attrs The attributes of the XML tag that is inflating the view. 3850 * @param defStyleAttr An attribute in the current theme that contains a 3851 * reference to a style resource that supplies default values for 3852 * the view. Can be 0 to not look for defaults. 3853 * @see #View(Context, AttributeSet) 3854 */ 3855 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 3856 this(context, attrs, defStyleAttr, 0); 3857 } 3858 3859 /** 3860 * Perform inflation from XML and apply a class-specific base style from a 3861 * theme attribute or style resource. This constructor of View allows 3862 * subclasses to use their own base style when they are inflating. 3863 * <p> 3864 * When determining the final value of a particular attribute, there are 3865 * four inputs that come into play: 3866 * <ol> 3867 * <li>Any attribute values in the given AttributeSet. 3868 * <li>The style resource specified in the AttributeSet (named "style"). 3869 * <li>The default style specified by <var>defStyleAttr</var>. 3870 * <li>The default style specified by <var>defStyleRes</var>. 3871 * <li>The base values in this theme. 3872 * </ol> 3873 * <p> 3874 * Each of these inputs is considered in-order, with the first listed taking 3875 * precedence over the following ones. In other words, if in the 3876 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3877 * , then the button's text will <em>always</em> be black, regardless of 3878 * what is specified in any of the styles. 3879 * 3880 * @param context The Context the view is running in, through which it can 3881 * access the current theme, resources, etc. 3882 * @param attrs The attributes of the XML tag that is inflating the view. 3883 * @param defStyleAttr An attribute in the current theme that contains a 3884 * reference to a style resource that supplies default values for 3885 * the view. Can be 0 to not look for defaults. 3886 * @param defStyleRes A resource identifier of a style resource that 3887 * supplies default values for the view, used only if 3888 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3889 * to not look for defaults. 3890 * @see #View(Context, AttributeSet, int) 3891 */ 3892 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3893 this(context); 3894 3895 final TypedArray a = context.obtainStyledAttributes( 3896 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3897 3898 if (mDebugViewAttributes) { 3899 saveAttributeData(attrs, a); 3900 } 3901 3902 Drawable background = null; 3903 3904 int leftPadding = -1; 3905 int topPadding = -1; 3906 int rightPadding = -1; 3907 int bottomPadding = -1; 3908 int startPadding = UNDEFINED_PADDING; 3909 int endPadding = UNDEFINED_PADDING; 3910 3911 int padding = -1; 3912 3913 int viewFlagValues = 0; 3914 int viewFlagMasks = 0; 3915 3916 boolean setScrollContainer = false; 3917 3918 int x = 0; 3919 int y = 0; 3920 3921 float tx = 0; 3922 float ty = 0; 3923 float tz = 0; 3924 float elevation = 0; 3925 float rotation = 0; 3926 float rotationX = 0; 3927 float rotationY = 0; 3928 float sx = 1f; 3929 float sy = 1f; 3930 boolean transformSet = false; 3931 3932 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3933 int overScrollMode = mOverScrollMode; 3934 boolean initializeScrollbars = false; 3935 boolean initializeScrollIndicators = false; 3936 3937 boolean startPaddingDefined = false; 3938 boolean endPaddingDefined = false; 3939 boolean leftPaddingDefined = false; 3940 boolean rightPaddingDefined = false; 3941 3942 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3943 3944 final int N = a.getIndexCount(); 3945 for (int i = 0; i < N; i++) { 3946 int attr = a.getIndex(i); 3947 switch (attr) { 3948 case com.android.internal.R.styleable.View_background: 3949 background = a.getDrawable(attr); 3950 break; 3951 case com.android.internal.R.styleable.View_padding: 3952 padding = a.getDimensionPixelSize(attr, -1); 3953 mUserPaddingLeftInitial = padding; 3954 mUserPaddingRightInitial = padding; 3955 leftPaddingDefined = true; 3956 rightPaddingDefined = true; 3957 break; 3958 case com.android.internal.R.styleable.View_paddingLeft: 3959 leftPadding = a.getDimensionPixelSize(attr, -1); 3960 mUserPaddingLeftInitial = leftPadding; 3961 leftPaddingDefined = true; 3962 break; 3963 case com.android.internal.R.styleable.View_paddingTop: 3964 topPadding = a.getDimensionPixelSize(attr, -1); 3965 break; 3966 case com.android.internal.R.styleable.View_paddingRight: 3967 rightPadding = a.getDimensionPixelSize(attr, -1); 3968 mUserPaddingRightInitial = rightPadding; 3969 rightPaddingDefined = true; 3970 break; 3971 case com.android.internal.R.styleable.View_paddingBottom: 3972 bottomPadding = a.getDimensionPixelSize(attr, -1); 3973 break; 3974 case com.android.internal.R.styleable.View_paddingStart: 3975 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3976 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3977 break; 3978 case com.android.internal.R.styleable.View_paddingEnd: 3979 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3980 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3981 break; 3982 case com.android.internal.R.styleable.View_scrollX: 3983 x = a.getDimensionPixelOffset(attr, 0); 3984 break; 3985 case com.android.internal.R.styleable.View_scrollY: 3986 y = a.getDimensionPixelOffset(attr, 0); 3987 break; 3988 case com.android.internal.R.styleable.View_alpha: 3989 setAlpha(a.getFloat(attr, 1f)); 3990 break; 3991 case com.android.internal.R.styleable.View_transformPivotX: 3992 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3993 break; 3994 case com.android.internal.R.styleable.View_transformPivotY: 3995 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3996 break; 3997 case com.android.internal.R.styleable.View_translationX: 3998 tx = a.getDimensionPixelOffset(attr, 0); 3999 transformSet = true; 4000 break; 4001 case com.android.internal.R.styleable.View_translationY: 4002 ty = a.getDimensionPixelOffset(attr, 0); 4003 transformSet = true; 4004 break; 4005 case com.android.internal.R.styleable.View_translationZ: 4006 tz = a.getDimensionPixelOffset(attr, 0); 4007 transformSet = true; 4008 break; 4009 case com.android.internal.R.styleable.View_elevation: 4010 elevation = a.getDimensionPixelOffset(attr, 0); 4011 transformSet = true; 4012 break; 4013 case com.android.internal.R.styleable.View_rotation: 4014 rotation = a.getFloat(attr, 0); 4015 transformSet = true; 4016 break; 4017 case com.android.internal.R.styleable.View_rotationX: 4018 rotationX = a.getFloat(attr, 0); 4019 transformSet = true; 4020 break; 4021 case com.android.internal.R.styleable.View_rotationY: 4022 rotationY = a.getFloat(attr, 0); 4023 transformSet = true; 4024 break; 4025 case com.android.internal.R.styleable.View_scaleX: 4026 sx = a.getFloat(attr, 1f); 4027 transformSet = true; 4028 break; 4029 case com.android.internal.R.styleable.View_scaleY: 4030 sy = a.getFloat(attr, 1f); 4031 transformSet = true; 4032 break; 4033 case com.android.internal.R.styleable.View_id: 4034 mID = a.getResourceId(attr, NO_ID); 4035 break; 4036 case com.android.internal.R.styleable.View_tag: 4037 mTag = a.getText(attr); 4038 break; 4039 case com.android.internal.R.styleable.View_fitsSystemWindows: 4040 if (a.getBoolean(attr, false)) { 4041 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4042 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4043 } 4044 break; 4045 case com.android.internal.R.styleable.View_focusable: 4046 if (a.getBoolean(attr, false)) { 4047 viewFlagValues |= FOCUSABLE; 4048 viewFlagMasks |= FOCUSABLE_MASK; 4049 } 4050 break; 4051 case com.android.internal.R.styleable.View_focusableInTouchMode: 4052 if (a.getBoolean(attr, false)) { 4053 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4054 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4055 } 4056 break; 4057 case com.android.internal.R.styleable.View_clickable: 4058 if (a.getBoolean(attr, false)) { 4059 viewFlagValues |= CLICKABLE; 4060 viewFlagMasks |= CLICKABLE; 4061 } 4062 break; 4063 case com.android.internal.R.styleable.View_longClickable: 4064 if (a.getBoolean(attr, false)) { 4065 viewFlagValues |= LONG_CLICKABLE; 4066 viewFlagMasks |= LONG_CLICKABLE; 4067 } 4068 break; 4069 case com.android.internal.R.styleable.View_contextClickable: 4070 if (a.getBoolean(attr, false)) { 4071 viewFlagValues |= CONTEXT_CLICKABLE; 4072 viewFlagMasks |= CONTEXT_CLICKABLE; 4073 } 4074 break; 4075 case com.android.internal.R.styleable.View_saveEnabled: 4076 if (!a.getBoolean(attr, true)) { 4077 viewFlagValues |= SAVE_DISABLED; 4078 viewFlagMasks |= SAVE_DISABLED_MASK; 4079 } 4080 break; 4081 case com.android.internal.R.styleable.View_duplicateParentState: 4082 if (a.getBoolean(attr, false)) { 4083 viewFlagValues |= DUPLICATE_PARENT_STATE; 4084 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4085 } 4086 break; 4087 case com.android.internal.R.styleable.View_visibility: 4088 final int visibility = a.getInt(attr, 0); 4089 if (visibility != 0) { 4090 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4091 viewFlagMasks |= VISIBILITY_MASK; 4092 } 4093 break; 4094 case com.android.internal.R.styleable.View_layoutDirection: 4095 // Clear any layout direction flags (included resolved bits) already set 4096 mPrivateFlags2 &= 4097 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4098 // Set the layout direction flags depending on the value of the attribute 4099 final int layoutDirection = a.getInt(attr, -1); 4100 final int value = (layoutDirection != -1) ? 4101 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4102 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4103 break; 4104 case com.android.internal.R.styleable.View_drawingCacheQuality: 4105 final int cacheQuality = a.getInt(attr, 0); 4106 if (cacheQuality != 0) { 4107 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4108 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4109 } 4110 break; 4111 case com.android.internal.R.styleable.View_contentDescription: 4112 setContentDescription(a.getString(attr)); 4113 break; 4114 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4115 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4116 break; 4117 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4118 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4119 break; 4120 case com.android.internal.R.styleable.View_labelFor: 4121 setLabelFor(a.getResourceId(attr, NO_ID)); 4122 break; 4123 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4124 if (!a.getBoolean(attr, true)) { 4125 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4126 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4127 } 4128 break; 4129 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4130 if (!a.getBoolean(attr, true)) { 4131 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4132 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4133 } 4134 break; 4135 case R.styleable.View_scrollbars: 4136 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4137 if (scrollbars != SCROLLBARS_NONE) { 4138 viewFlagValues |= scrollbars; 4139 viewFlagMasks |= SCROLLBARS_MASK; 4140 initializeScrollbars = true; 4141 } 4142 break; 4143 //noinspection deprecation 4144 case R.styleable.View_fadingEdge: 4145 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4146 // Ignore the attribute starting with ICS 4147 break; 4148 } 4149 // With builds < ICS, fall through and apply fading edges 4150 case R.styleable.View_requiresFadingEdge: 4151 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4152 if (fadingEdge != FADING_EDGE_NONE) { 4153 viewFlagValues |= fadingEdge; 4154 viewFlagMasks |= FADING_EDGE_MASK; 4155 initializeFadingEdgeInternal(a); 4156 } 4157 break; 4158 case R.styleable.View_scrollbarStyle: 4159 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4160 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4161 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4162 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4163 } 4164 break; 4165 case R.styleable.View_isScrollContainer: 4166 setScrollContainer = true; 4167 if (a.getBoolean(attr, false)) { 4168 setScrollContainer(true); 4169 } 4170 break; 4171 case com.android.internal.R.styleable.View_keepScreenOn: 4172 if (a.getBoolean(attr, false)) { 4173 viewFlagValues |= KEEP_SCREEN_ON; 4174 viewFlagMasks |= KEEP_SCREEN_ON; 4175 } 4176 break; 4177 case R.styleable.View_filterTouchesWhenObscured: 4178 if (a.getBoolean(attr, false)) { 4179 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4180 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4181 } 4182 break; 4183 case R.styleable.View_nextFocusLeft: 4184 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4185 break; 4186 case R.styleable.View_nextFocusRight: 4187 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4188 break; 4189 case R.styleable.View_nextFocusUp: 4190 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4191 break; 4192 case R.styleable.View_nextFocusDown: 4193 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4194 break; 4195 case R.styleable.View_nextFocusForward: 4196 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4197 break; 4198 case R.styleable.View_minWidth: 4199 mMinWidth = a.getDimensionPixelSize(attr, 0); 4200 break; 4201 case R.styleable.View_minHeight: 4202 mMinHeight = a.getDimensionPixelSize(attr, 0); 4203 break; 4204 case R.styleable.View_onClick: 4205 if (context.isRestricted()) { 4206 throw new IllegalStateException("The android:onClick attribute cannot " 4207 + "be used within a restricted context"); 4208 } 4209 4210 final String handlerName = a.getString(attr); 4211 if (handlerName != null) { 4212 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4213 } 4214 break; 4215 case R.styleable.View_overScrollMode: 4216 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4217 break; 4218 case R.styleable.View_verticalScrollbarPosition: 4219 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4220 break; 4221 case R.styleable.View_layerType: 4222 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4223 break; 4224 case R.styleable.View_textDirection: 4225 // Clear any text direction flag already set 4226 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4227 // Set the text direction flags depending on the value of the attribute 4228 final int textDirection = a.getInt(attr, -1); 4229 if (textDirection != -1) { 4230 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4231 } 4232 break; 4233 case R.styleable.View_textAlignment: 4234 // Clear any text alignment flag already set 4235 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4236 // Set the text alignment flag depending on the value of the attribute 4237 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4238 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4239 break; 4240 case R.styleable.View_importantForAccessibility: 4241 setImportantForAccessibility(a.getInt(attr, 4242 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4243 break; 4244 case R.styleable.View_accessibilityLiveRegion: 4245 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4246 break; 4247 case R.styleable.View_transitionName: 4248 setTransitionName(a.getString(attr)); 4249 break; 4250 case R.styleable.View_nestedScrollingEnabled: 4251 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4252 break; 4253 case R.styleable.View_stateListAnimator: 4254 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4255 a.getResourceId(attr, 0))); 4256 break; 4257 case R.styleable.View_backgroundTint: 4258 // This will get applied later during setBackground(). 4259 if (mBackgroundTint == null) { 4260 mBackgroundTint = new TintInfo(); 4261 } 4262 mBackgroundTint.mTintList = a.getColorStateList( 4263 R.styleable.View_backgroundTint); 4264 mBackgroundTint.mHasTintList = true; 4265 break; 4266 case R.styleable.View_backgroundTintMode: 4267 // This will get applied later during setBackground(). 4268 if (mBackgroundTint == null) { 4269 mBackgroundTint = new TintInfo(); 4270 } 4271 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4272 R.styleable.View_backgroundTintMode, -1), null); 4273 mBackgroundTint.mHasTintMode = true; 4274 break; 4275 case R.styleable.View_outlineProvider: 4276 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4277 PROVIDER_BACKGROUND)); 4278 break; 4279 case R.styleable.View_foreground: 4280 if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) { 4281 setForeground(a.getDrawable(attr)); 4282 } 4283 break; 4284 case R.styleable.View_foregroundGravity: 4285 if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) { 4286 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4287 } 4288 break; 4289 case R.styleable.View_foregroundTintMode: 4290 if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) { 4291 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4292 } 4293 break; 4294 case R.styleable.View_foregroundTint: 4295 if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) { 4296 setForegroundTintList(a.getColorStateList(attr)); 4297 } 4298 break; 4299 case R.styleable.View_foregroundInsidePadding: 4300 if (targetSdkVersion >= VERSION_CODES.MNC || this instanceof FrameLayout) { 4301 if (mForegroundInfo == null) { 4302 mForegroundInfo = new ForegroundInfo(); 4303 } 4304 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4305 mForegroundInfo.mInsidePadding); 4306 } 4307 break; 4308 case R.styleable.View_scrollIndicators: 4309 final int scrollIndicators = 4310 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4311 & SCROLL_INDICATORS_PFLAG3_MASK; 4312 if (scrollIndicators != 0) { 4313 mPrivateFlags3 |= scrollIndicators; 4314 initializeScrollIndicators = true; 4315 } 4316 break; 4317 } 4318 } 4319 4320 setOverScrollMode(overScrollMode); 4321 4322 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4323 // the resolved layout direction). Those cached values will be used later during padding 4324 // resolution. 4325 mUserPaddingStart = startPadding; 4326 mUserPaddingEnd = endPadding; 4327 4328 if (background != null) { 4329 setBackground(background); 4330 } 4331 4332 // setBackground above will record that padding is currently provided by the background. 4333 // If we have padding specified via xml, record that here instead and use it. 4334 mLeftPaddingDefined = leftPaddingDefined; 4335 mRightPaddingDefined = rightPaddingDefined; 4336 4337 if (padding >= 0) { 4338 leftPadding = padding; 4339 topPadding = padding; 4340 rightPadding = padding; 4341 bottomPadding = padding; 4342 mUserPaddingLeftInitial = padding; 4343 mUserPaddingRightInitial = padding; 4344 } 4345 4346 if (isRtlCompatibilityMode()) { 4347 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4348 // left / right padding are used if defined (meaning here nothing to do). If they are not 4349 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4350 // start / end and resolve them as left / right (layout direction is not taken into account). 4351 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4352 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4353 // defined. 4354 if (!mLeftPaddingDefined && startPaddingDefined) { 4355 leftPadding = startPadding; 4356 } 4357 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4358 if (!mRightPaddingDefined && endPaddingDefined) { 4359 rightPadding = endPadding; 4360 } 4361 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4362 } else { 4363 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4364 // values defined. Otherwise, left /right values are used. 4365 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4366 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4367 // defined. 4368 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4369 4370 if (mLeftPaddingDefined && !hasRelativePadding) { 4371 mUserPaddingLeftInitial = leftPadding; 4372 } 4373 if (mRightPaddingDefined && !hasRelativePadding) { 4374 mUserPaddingRightInitial = rightPadding; 4375 } 4376 } 4377 4378 internalSetPadding( 4379 mUserPaddingLeftInitial, 4380 topPadding >= 0 ? topPadding : mPaddingTop, 4381 mUserPaddingRightInitial, 4382 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4383 4384 if (viewFlagMasks != 0) { 4385 setFlags(viewFlagValues, viewFlagMasks); 4386 } 4387 4388 if (initializeScrollbars) { 4389 initializeScrollbarsInternal(a); 4390 } 4391 4392 if (initializeScrollIndicators) { 4393 initializeScrollIndicatorsInternal(); 4394 } 4395 4396 a.recycle(); 4397 4398 // Needs to be called after mViewFlags is set 4399 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4400 recomputePadding(); 4401 } 4402 4403 if (x != 0 || y != 0) { 4404 scrollTo(x, y); 4405 } 4406 4407 if (transformSet) { 4408 setTranslationX(tx); 4409 setTranslationY(ty); 4410 setTranslationZ(tz); 4411 setElevation(elevation); 4412 setRotation(rotation); 4413 setRotationX(rotationX); 4414 setRotationY(rotationY); 4415 setScaleX(sx); 4416 setScaleY(sy); 4417 } 4418 4419 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4420 setScrollContainer(true); 4421 } 4422 4423 computeOpaqueFlags(); 4424 } 4425 4426 /** 4427 * An implementation of OnClickListener that attempts to lazily load a 4428 * named click handling method from a parent or ancestor context. 4429 */ 4430 private static class DeclaredOnClickListener implements OnClickListener { 4431 private final View mHostView; 4432 private final String mMethodName; 4433 4434 private Method mMethod; 4435 4436 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4437 mHostView = hostView; 4438 mMethodName = methodName; 4439 } 4440 4441 @Override 4442 public void onClick(@NonNull View v) { 4443 if (mMethod == null) { 4444 mMethod = resolveMethod(mHostView.getContext(), mMethodName); 4445 } 4446 4447 try { 4448 mMethod.invoke(mHostView.getContext(), v); 4449 } catch (IllegalAccessException e) { 4450 throw new IllegalStateException( 4451 "Could not execute non-public method for android:onClick", e); 4452 } catch (InvocationTargetException e) { 4453 throw new IllegalStateException( 4454 "Could not execute method for android:onClick", e); 4455 } 4456 } 4457 4458 @NonNull 4459 private Method resolveMethod(@Nullable Context context, @NonNull String name) { 4460 while (context != null) { 4461 try { 4462 if (!context.isRestricted()) { 4463 return context.getClass().getMethod(mMethodName, View.class); 4464 } 4465 } catch (NoSuchMethodException e) { 4466 // Failed to find method, keep searching up the hierarchy. 4467 } 4468 4469 if (context instanceof ContextWrapper) { 4470 context = ((ContextWrapper) context).getBaseContext(); 4471 } else { 4472 // Can't search up the hierarchy, null out and fail. 4473 context = null; 4474 } 4475 } 4476 4477 final int id = mHostView.getId(); 4478 final String idText = id == NO_ID ? "" : " with id '" 4479 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4480 throw new IllegalStateException("Could not find method " + mMethodName 4481 + "(View) in a parent or ancestor Context for android:onClick " 4482 + "attribute defined on view " + mHostView.getClass() + idText); 4483 } 4484 } 4485 4486 /** 4487 * Non-public constructor for use in testing 4488 */ 4489 View() { 4490 mResources = null; 4491 mRenderNode = RenderNode.create(getClass().getName(), this); 4492 } 4493 4494 private static SparseArray<String> getAttributeMap() { 4495 if (mAttributeMap == null) { 4496 mAttributeMap = new SparseArray<>(); 4497 } 4498 return mAttributeMap; 4499 } 4500 4501 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4502 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4503 final int indexCount = t.getIndexCount(); 4504 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4505 4506 int i = 0; 4507 4508 // Store raw XML attributes. 4509 for (int j = 0; j < attrsCount; ++j) { 4510 attributes[i] = attrs.getAttributeName(j); 4511 attributes[i + 1] = attrs.getAttributeValue(j); 4512 i += 2; 4513 } 4514 4515 // Store resolved styleable attributes. 4516 final Resources res = t.getResources(); 4517 final SparseArray<String> attributeMap = getAttributeMap(); 4518 for (int j = 0; j < indexCount; ++j) { 4519 final int index = t.getIndex(j); 4520 if (!t.hasValueOrEmpty(index)) { 4521 // Value is undefined. Skip it. 4522 continue; 4523 } 4524 4525 final int resourceId = t.getResourceId(index, 0); 4526 if (resourceId == 0) { 4527 // Value is not a reference. Skip it. 4528 continue; 4529 } 4530 4531 String resourceName = attributeMap.get(resourceId); 4532 if (resourceName == null) { 4533 try { 4534 resourceName = res.getResourceName(resourceId); 4535 } catch (Resources.NotFoundException e) { 4536 resourceName = "0x" + Integer.toHexString(resourceId); 4537 } 4538 attributeMap.put(resourceId, resourceName); 4539 } 4540 4541 attributes[i] = resourceName; 4542 attributes[i + 1] = t.getString(index); 4543 i += 2; 4544 } 4545 4546 // Trim to fit contents. 4547 final String[] trimmed = new String[i]; 4548 System.arraycopy(attributes, 0, trimmed, 0, i); 4549 mAttributes = trimmed; 4550 } 4551 4552 public String toString() { 4553 StringBuilder out = new StringBuilder(128); 4554 out.append(getClass().getName()); 4555 out.append('{'); 4556 out.append(Integer.toHexString(System.identityHashCode(this))); 4557 out.append(' '); 4558 switch (mViewFlags&VISIBILITY_MASK) { 4559 case VISIBLE: out.append('V'); break; 4560 case INVISIBLE: out.append('I'); break; 4561 case GONE: out.append('G'); break; 4562 default: out.append('.'); break; 4563 } 4564 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4565 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4566 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4567 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4568 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4569 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4570 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4571 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 4572 out.append(' '); 4573 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4574 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4575 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4576 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4577 out.append('p'); 4578 } else { 4579 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4580 } 4581 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4582 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4583 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4584 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4585 out.append(' '); 4586 out.append(mLeft); 4587 out.append(','); 4588 out.append(mTop); 4589 out.append('-'); 4590 out.append(mRight); 4591 out.append(','); 4592 out.append(mBottom); 4593 final int id = getId(); 4594 if (id != NO_ID) { 4595 out.append(" #"); 4596 out.append(Integer.toHexString(id)); 4597 final Resources r = mResources; 4598 if (Resources.resourceHasPackage(id) && r != null) { 4599 try { 4600 String pkgname; 4601 switch (id&0xff000000) { 4602 case 0x7f000000: 4603 pkgname="app"; 4604 break; 4605 case 0x01000000: 4606 pkgname="android"; 4607 break; 4608 default: 4609 pkgname = r.getResourcePackageName(id); 4610 break; 4611 } 4612 String typename = r.getResourceTypeName(id); 4613 String entryname = r.getResourceEntryName(id); 4614 out.append(" "); 4615 out.append(pkgname); 4616 out.append(":"); 4617 out.append(typename); 4618 out.append("/"); 4619 out.append(entryname); 4620 } catch (Resources.NotFoundException e) { 4621 } 4622 } 4623 } 4624 out.append("}"); 4625 return out.toString(); 4626 } 4627 4628 /** 4629 * <p> 4630 * Initializes the fading edges from a given set of styled attributes. This 4631 * method should be called by subclasses that need fading edges and when an 4632 * instance of these subclasses is created programmatically rather than 4633 * being inflated from XML. This method is automatically called when the XML 4634 * is inflated. 4635 * </p> 4636 * 4637 * @param a the styled attributes set to initialize the fading edges from 4638 * 4639 * @removed 4640 */ 4641 protected void initializeFadingEdge(TypedArray a) { 4642 // This method probably shouldn't have been included in the SDK to begin with. 4643 // It relies on 'a' having been initialized using an attribute filter array that is 4644 // not publicly available to the SDK. The old method has been renamed 4645 // to initializeFadingEdgeInternal and hidden for framework use only; 4646 // this one initializes using defaults to make it safe to call for apps. 4647 4648 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4649 4650 initializeFadingEdgeInternal(arr); 4651 4652 arr.recycle(); 4653 } 4654 4655 /** 4656 * <p> 4657 * Initializes the fading edges from a given set of styled attributes. This 4658 * method should be called by subclasses that need fading edges and when an 4659 * instance of these subclasses is created programmatically rather than 4660 * being inflated from XML. This method is automatically called when the XML 4661 * is inflated. 4662 * </p> 4663 * 4664 * @param a the styled attributes set to initialize the fading edges from 4665 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4666 */ 4667 protected void initializeFadingEdgeInternal(TypedArray a) { 4668 initScrollCache(); 4669 4670 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4671 R.styleable.View_fadingEdgeLength, 4672 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4673 } 4674 4675 /** 4676 * Returns the size of the vertical faded edges used to indicate that more 4677 * content in this view is visible. 4678 * 4679 * @return The size in pixels of the vertical faded edge or 0 if vertical 4680 * faded edges are not enabled for this view. 4681 * @attr ref android.R.styleable#View_fadingEdgeLength 4682 */ 4683 public int getVerticalFadingEdgeLength() { 4684 if (isVerticalFadingEdgeEnabled()) { 4685 ScrollabilityCache cache = mScrollCache; 4686 if (cache != null) { 4687 return cache.fadingEdgeLength; 4688 } 4689 } 4690 return 0; 4691 } 4692 4693 /** 4694 * Set the size of the faded edge used to indicate that more content in this 4695 * view is available. Will not change whether the fading edge is enabled; use 4696 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4697 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4698 * for the vertical or horizontal fading edges. 4699 * 4700 * @param length The size in pixels of the faded edge used to indicate that more 4701 * content in this view is visible. 4702 */ 4703 public void setFadingEdgeLength(int length) { 4704 initScrollCache(); 4705 mScrollCache.fadingEdgeLength = length; 4706 } 4707 4708 /** 4709 * Returns the size of the horizontal faded edges used to indicate that more 4710 * content in this view is visible. 4711 * 4712 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4713 * faded edges are not enabled for this view. 4714 * @attr ref android.R.styleable#View_fadingEdgeLength 4715 */ 4716 public int getHorizontalFadingEdgeLength() { 4717 if (isHorizontalFadingEdgeEnabled()) { 4718 ScrollabilityCache cache = mScrollCache; 4719 if (cache != null) { 4720 return cache.fadingEdgeLength; 4721 } 4722 } 4723 return 0; 4724 } 4725 4726 /** 4727 * Returns the width of the vertical scrollbar. 4728 * 4729 * @return The width in pixels of the vertical scrollbar or 0 if there 4730 * is no vertical scrollbar. 4731 */ 4732 public int getVerticalScrollbarWidth() { 4733 ScrollabilityCache cache = mScrollCache; 4734 if (cache != null) { 4735 ScrollBarDrawable scrollBar = cache.scrollBar; 4736 if (scrollBar != null) { 4737 int size = scrollBar.getSize(true); 4738 if (size <= 0) { 4739 size = cache.scrollBarSize; 4740 } 4741 return size; 4742 } 4743 return 0; 4744 } 4745 return 0; 4746 } 4747 4748 /** 4749 * Returns the height of the horizontal scrollbar. 4750 * 4751 * @return The height in pixels of the horizontal scrollbar or 0 if 4752 * there is no horizontal scrollbar. 4753 */ 4754 protected int getHorizontalScrollbarHeight() { 4755 ScrollabilityCache cache = mScrollCache; 4756 if (cache != null) { 4757 ScrollBarDrawable scrollBar = cache.scrollBar; 4758 if (scrollBar != null) { 4759 int size = scrollBar.getSize(false); 4760 if (size <= 0) { 4761 size = cache.scrollBarSize; 4762 } 4763 return size; 4764 } 4765 return 0; 4766 } 4767 return 0; 4768 } 4769 4770 /** 4771 * <p> 4772 * Initializes the scrollbars from a given set of styled attributes. This 4773 * method should be called by subclasses that need scrollbars and when an 4774 * instance of these subclasses is created programmatically rather than 4775 * being inflated from XML. This method is automatically called when the XML 4776 * is inflated. 4777 * </p> 4778 * 4779 * @param a the styled attributes set to initialize the scrollbars from 4780 * 4781 * @removed 4782 */ 4783 protected void initializeScrollbars(TypedArray a) { 4784 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4785 // using the View filter array which is not available to the SDK. As such, internal 4786 // framework usage now uses initializeScrollbarsInternal and we grab a default 4787 // TypedArray with the right filter instead here. 4788 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4789 4790 initializeScrollbarsInternal(arr); 4791 4792 // We ignored the method parameter. Recycle the one we actually did use. 4793 arr.recycle(); 4794 } 4795 4796 /** 4797 * <p> 4798 * Initializes the scrollbars from a given set of styled attributes. This 4799 * method should be called by subclasses that need scrollbars and when an 4800 * instance of these subclasses is created programmatically rather than 4801 * being inflated from XML. This method is automatically called when the XML 4802 * is inflated. 4803 * </p> 4804 * 4805 * @param a the styled attributes set to initialize the scrollbars from 4806 * @hide 4807 */ 4808 protected void initializeScrollbarsInternal(TypedArray a) { 4809 initScrollCache(); 4810 4811 final ScrollabilityCache scrollabilityCache = mScrollCache; 4812 4813 if (scrollabilityCache.scrollBar == null) { 4814 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4815 scrollabilityCache.scrollBar.setCallback(this); 4816 scrollabilityCache.scrollBar.setState(getDrawableState()); 4817 } 4818 4819 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4820 4821 if (!fadeScrollbars) { 4822 scrollabilityCache.state = ScrollabilityCache.ON; 4823 } 4824 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4825 4826 4827 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4828 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4829 .getScrollBarFadeDuration()); 4830 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4831 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4832 ViewConfiguration.getScrollDefaultDelay()); 4833 4834 4835 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4836 com.android.internal.R.styleable.View_scrollbarSize, 4837 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4838 4839 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4840 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4841 4842 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4843 if (thumb != null) { 4844 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4845 } 4846 4847 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4848 false); 4849 if (alwaysDraw) { 4850 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4851 } 4852 4853 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4854 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4855 4856 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4857 if (thumb != null) { 4858 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4859 } 4860 4861 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4862 false); 4863 if (alwaysDraw) { 4864 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4865 } 4866 4867 // Apply layout direction to the new Drawables if needed 4868 final int layoutDirection = getLayoutDirection(); 4869 if (track != null) { 4870 track.setLayoutDirection(layoutDirection); 4871 } 4872 if (thumb != null) { 4873 thumb.setLayoutDirection(layoutDirection); 4874 } 4875 4876 // Re-apply user/background padding so that scrollbar(s) get added 4877 resolvePadding(); 4878 } 4879 4880 private void initializeScrollIndicatorsInternal() { 4881 // Some day maybe we'll break this into top/left/start/etc. and let the 4882 // client control it. Until then, you can have any scroll indicator you 4883 // want as long as it's a 1dp foreground-colored rectangle. 4884 if (mScrollIndicatorDrawable == null) { 4885 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 4886 } 4887 } 4888 4889 /** 4890 * <p> 4891 * Initalizes the scrollability cache if necessary. 4892 * </p> 4893 */ 4894 private void initScrollCache() { 4895 if (mScrollCache == null) { 4896 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4897 } 4898 } 4899 4900 private ScrollabilityCache getScrollCache() { 4901 initScrollCache(); 4902 return mScrollCache; 4903 } 4904 4905 /** 4906 * Set the position of the vertical scroll bar. Should be one of 4907 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4908 * {@link #SCROLLBAR_POSITION_RIGHT}. 4909 * 4910 * @param position Where the vertical scroll bar should be positioned. 4911 */ 4912 public void setVerticalScrollbarPosition(int position) { 4913 if (mVerticalScrollbarPosition != position) { 4914 mVerticalScrollbarPosition = position; 4915 computeOpaqueFlags(); 4916 resolvePadding(); 4917 } 4918 } 4919 4920 /** 4921 * @return The position where the vertical scroll bar will show, if applicable. 4922 * @see #setVerticalScrollbarPosition(int) 4923 */ 4924 public int getVerticalScrollbarPosition() { 4925 return mVerticalScrollbarPosition; 4926 } 4927 4928 /** 4929 * Sets the state of all scroll indicators. 4930 * <p> 4931 * See {@link #setScrollIndicators(int, int)} for usage information. 4932 * 4933 * @param indicators a bitmask of indicators that should be enabled, or 4934 * {@code 0} to disable all indicators 4935 * @see #setScrollIndicators(int, int) 4936 * @see #getScrollIndicators() 4937 * @attr ref android.R.styleable#View_scrollIndicators 4938 */ 4939 public void setScrollIndicators(@ScrollIndicators int indicators) { 4940 setScrollIndicators(indicators, 4941 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 4942 } 4943 4944 /** 4945 * Sets the state of the scroll indicators specified by the mask. To change 4946 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 4947 * <p> 4948 * When a scroll indicator is enabled, it will be displayed if the view 4949 * can scroll in the direction of the indicator. 4950 * <p> 4951 * Multiple indicator types may be enabled or disabled by passing the 4952 * logical OR of the desired types. If multiple types are specified, they 4953 * will all be set to the same enabled state. 4954 * <p> 4955 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 4956 * 4957 * @param indicators the indicator direction, or the logical OR of multiple 4958 * indicator directions. One or more of: 4959 * <ul> 4960 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 4961 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 4962 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 4963 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 4964 * <li>{@link #SCROLL_INDICATOR_START}</li> 4965 * <li>{@link #SCROLL_INDICATOR_END}</li> 4966 * </ul> 4967 * @see #setScrollIndicators(int) 4968 * @see #getScrollIndicators() 4969 * @attr ref android.R.styleable#View_scrollIndicators 4970 */ 4971 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 4972 // Shift and sanitize mask. 4973 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 4974 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 4975 4976 // Shift and mask indicators. 4977 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 4978 indicators &= mask; 4979 4980 // Merge with non-masked flags. 4981 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 4982 4983 if (mPrivateFlags3 != updatedFlags) { 4984 mPrivateFlags3 = updatedFlags; 4985 4986 if (indicators != 0) { 4987 initializeScrollIndicatorsInternal(); 4988 } 4989 invalidate(); 4990 } 4991 } 4992 4993 /** 4994 * Returns a bitmask representing the enabled scroll indicators. 4995 * <p> 4996 * For example, if the top and left scroll indicators are enabled and all 4997 * other indicators are disabled, the return value will be 4998 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 4999 * <p> 5000 * To check whether the bottom scroll indicator is enabled, use the value 5001 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5002 * 5003 * @return a bitmask representing the enabled scroll indicators 5004 */ 5005 @ScrollIndicators 5006 public int getScrollIndicators() { 5007 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5008 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5009 } 5010 5011 ListenerInfo getListenerInfo() { 5012 if (mListenerInfo != null) { 5013 return mListenerInfo; 5014 } 5015 mListenerInfo = new ListenerInfo(); 5016 return mListenerInfo; 5017 } 5018 5019 /** 5020 * Register a callback to be invoked when the scroll X or Y positions of 5021 * this view change. 5022 * <p> 5023 * <b>Note:</b> Some views handle scrolling independently from View and may 5024 * have their own separate listeners for scroll-type events. For example, 5025 * {@link android.widget.ListView ListView} allows clients to register an 5026 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5027 * to listen for changes in list scroll position. 5028 * 5029 * @param l The listener to notify when the scroll X or Y position changes. 5030 * @see android.view.View#getScrollX() 5031 * @see android.view.View#getScrollY() 5032 */ 5033 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5034 getListenerInfo().mOnScrollChangeListener = l; 5035 } 5036 5037 /** 5038 * Register a callback to be invoked when focus of this view changed. 5039 * 5040 * @param l The callback that will run. 5041 */ 5042 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5043 getListenerInfo().mOnFocusChangeListener = l; 5044 } 5045 5046 /** 5047 * Add a listener that will be called when the bounds of the view change due to 5048 * layout processing. 5049 * 5050 * @param listener The listener that will be called when layout bounds change. 5051 */ 5052 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5053 ListenerInfo li = getListenerInfo(); 5054 if (li.mOnLayoutChangeListeners == null) { 5055 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5056 } 5057 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5058 li.mOnLayoutChangeListeners.add(listener); 5059 } 5060 } 5061 5062 /** 5063 * Remove a listener for layout changes. 5064 * 5065 * @param listener The listener for layout bounds change. 5066 */ 5067 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5068 ListenerInfo li = mListenerInfo; 5069 if (li == null || li.mOnLayoutChangeListeners == null) { 5070 return; 5071 } 5072 li.mOnLayoutChangeListeners.remove(listener); 5073 } 5074 5075 /** 5076 * Add a listener for attach state changes. 5077 * 5078 * This listener will be called whenever this view is attached or detached 5079 * from a window. Remove the listener using 5080 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5081 * 5082 * @param listener Listener to attach 5083 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5084 */ 5085 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5086 ListenerInfo li = getListenerInfo(); 5087 if (li.mOnAttachStateChangeListeners == null) { 5088 li.mOnAttachStateChangeListeners 5089 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5090 } 5091 li.mOnAttachStateChangeListeners.add(listener); 5092 } 5093 5094 /** 5095 * Remove a listener for attach state changes. The listener will receive no further 5096 * notification of window attach/detach events. 5097 * 5098 * @param listener Listener to remove 5099 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5100 */ 5101 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5102 ListenerInfo li = mListenerInfo; 5103 if (li == null || li.mOnAttachStateChangeListeners == null) { 5104 return; 5105 } 5106 li.mOnAttachStateChangeListeners.remove(listener); 5107 } 5108 5109 /** 5110 * Returns the focus-change callback registered for this view. 5111 * 5112 * @return The callback, or null if one is not registered. 5113 */ 5114 public OnFocusChangeListener getOnFocusChangeListener() { 5115 ListenerInfo li = mListenerInfo; 5116 return li != null ? li.mOnFocusChangeListener : null; 5117 } 5118 5119 /** 5120 * Register a callback to be invoked when this view is clicked. If this view is not 5121 * clickable, it becomes clickable. 5122 * 5123 * @param l The callback that will run 5124 * 5125 * @see #setClickable(boolean) 5126 */ 5127 public void setOnClickListener(@Nullable OnClickListener l) { 5128 if (!isClickable()) { 5129 setClickable(true); 5130 } 5131 getListenerInfo().mOnClickListener = l; 5132 } 5133 5134 /** 5135 * Return whether this view has an attached OnClickListener. Returns 5136 * true if there is a listener, false if there is none. 5137 */ 5138 public boolean hasOnClickListeners() { 5139 ListenerInfo li = mListenerInfo; 5140 return (li != null && li.mOnClickListener != null); 5141 } 5142 5143 /** 5144 * Register a callback to be invoked when this view is clicked and held. If this view is not 5145 * long clickable, it becomes long clickable. 5146 * 5147 * @param l The callback that will run 5148 * 5149 * @see #setLongClickable(boolean) 5150 */ 5151 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5152 if (!isLongClickable()) { 5153 setLongClickable(true); 5154 } 5155 getListenerInfo().mOnLongClickListener = l; 5156 } 5157 5158 /** 5159 * Register a callback to be invoked when this view is context clicked. If the view is not 5160 * context clickable, it becomes context clickable. 5161 * 5162 * @param l The callback that will run 5163 * @see #setContextClickable(boolean) 5164 */ 5165 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5166 if (!isContextClickable()) { 5167 setContextClickable(true); 5168 } 5169 getListenerInfo().mOnContextClickListener = l; 5170 } 5171 5172 /** 5173 * Register a callback to be invoked when the context menu for this view is 5174 * being built. If this view is not long clickable, it becomes long clickable. 5175 * 5176 * @param l The callback that will run 5177 * 5178 */ 5179 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5180 if (!isLongClickable()) { 5181 setLongClickable(true); 5182 } 5183 getListenerInfo().mOnCreateContextMenuListener = l; 5184 } 5185 5186 /** 5187 * Call this view's OnClickListener, if it is defined. Performs all normal 5188 * actions associated with clicking: reporting accessibility event, playing 5189 * a sound, etc. 5190 * 5191 * @return True there was an assigned OnClickListener that was called, false 5192 * otherwise is returned. 5193 */ 5194 public boolean performClick() { 5195 final boolean result; 5196 final ListenerInfo li = mListenerInfo; 5197 if (li != null && li.mOnClickListener != null) { 5198 playSoundEffect(SoundEffectConstants.CLICK); 5199 li.mOnClickListener.onClick(this); 5200 result = true; 5201 } else { 5202 result = false; 5203 } 5204 5205 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5206 return result; 5207 } 5208 5209 /** 5210 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5211 * this only calls the listener, and does not do any associated clicking 5212 * actions like reporting an accessibility event. 5213 * 5214 * @return True there was an assigned OnClickListener that was called, false 5215 * otherwise is returned. 5216 */ 5217 public boolean callOnClick() { 5218 ListenerInfo li = mListenerInfo; 5219 if (li != null && li.mOnClickListener != null) { 5220 li.mOnClickListener.onClick(this); 5221 return true; 5222 } 5223 return false; 5224 } 5225 5226 /** 5227 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 5228 * OnLongClickListener did not consume the event. 5229 * 5230 * @return True if one of the above receivers consumed the event, false otherwise. 5231 */ 5232 public boolean performLongClick() { 5233 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5234 5235 boolean handled = false; 5236 ListenerInfo li = mListenerInfo; 5237 if (li != null && li.mOnLongClickListener != null) { 5238 handled = li.mOnLongClickListener.onLongClick(View.this); 5239 } 5240 if (!handled) { 5241 handled = showContextMenu(); 5242 } 5243 if (handled) { 5244 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5245 } 5246 return handled; 5247 } 5248 5249 /** 5250 * Call this view's OnContextClickListener, if it is defined. 5251 * 5252 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5253 * otherwise. 5254 */ 5255 public boolean performContextClick() { 5256 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5257 5258 boolean handled = false; 5259 ListenerInfo li = mListenerInfo; 5260 if (li != null && li.mOnContextClickListener != null) { 5261 handled = li.mOnContextClickListener.onContextClick(View.this); 5262 } 5263 if (handled) { 5264 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5265 } 5266 return handled; 5267 } 5268 5269 /** 5270 * Performs button-related actions during a touch down event. 5271 * 5272 * @param event The event. 5273 * @return True if the down was consumed. 5274 * 5275 * @hide 5276 */ 5277 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5278 if (event.getToolType(0) == MotionEvent.TOOL_TYPE_MOUSE && 5279 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5280 showContextMenu(event.getX(), event.getY(), event.getMetaState()); 5281 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5282 return true; 5283 } 5284 return false; 5285 } 5286 5287 /** 5288 * Bring up the context menu for this view. 5289 * 5290 * @return Whether a context menu was displayed. 5291 */ 5292 public boolean showContextMenu() { 5293 return getParent().showContextMenuForChild(this); 5294 } 5295 5296 /** 5297 * Bring up the context menu for this view, referring to the item under the specified point. 5298 * 5299 * @param x The referenced x coordinate. 5300 * @param y The referenced y coordinate. 5301 * @param metaState The keyboard modifiers that were pressed. 5302 * @return Whether a context menu was displayed. 5303 * 5304 * @hide 5305 */ 5306 public boolean showContextMenu(float x, float y, int metaState) { 5307 return showContextMenu(); 5308 } 5309 5310 /** 5311 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5312 * 5313 * @param callback Callback that will control the lifecycle of the action mode 5314 * @return The new action mode if it is started, null otherwise 5315 * 5316 * @see ActionMode 5317 * @see #startActionMode(android.view.ActionMode.Callback, int) 5318 */ 5319 public ActionMode startActionMode(ActionMode.Callback callback) { 5320 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5321 } 5322 5323 /** 5324 * Start an action mode with the given type. 5325 * 5326 * @param callback Callback that will control the lifecycle of the action mode 5327 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5328 * @return The new action mode if it is started, null otherwise 5329 * 5330 * @see ActionMode 5331 */ 5332 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5333 ViewParent parent = getParent(); 5334 if (parent == null) return null; 5335 try { 5336 return parent.startActionModeForChild(this, callback, type); 5337 } catch (AbstractMethodError ame) { 5338 // Older implementations of custom views might not implement this. 5339 return parent.startActionModeForChild(this, callback); 5340 } 5341 } 5342 5343 /** 5344 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5345 * Context, creating a unique View identifier to retrieve the result. 5346 * 5347 * @param intent The Intent to be started. 5348 * @param requestCode The request code to use. 5349 * @hide 5350 */ 5351 public void startActivityForResult(Intent intent, int requestCode) { 5352 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5353 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5354 } 5355 5356 /** 5357 * If this View corresponds to the calling who, dispatches the activity result. 5358 * @param who The identifier for the targeted View to receive the result. 5359 * @param requestCode The integer request code originally supplied to 5360 * startActivityForResult(), allowing you to identify who this 5361 * result came from. 5362 * @param resultCode The integer result code returned by the child activity 5363 * through its setResult(). 5364 * @param data An Intent, which can return result data to the caller 5365 * (various data can be attached to Intent "extras"). 5366 * @return {@code true} if the activity result was dispatched. 5367 * @hide 5368 */ 5369 public boolean dispatchActivityResult( 5370 String who, int requestCode, int resultCode, Intent data) { 5371 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5372 onActivityResult(requestCode, resultCode, data); 5373 mStartActivityRequestWho = null; 5374 return true; 5375 } 5376 return false; 5377 } 5378 5379 /** 5380 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5381 * 5382 * @param requestCode The integer request code originally supplied to 5383 * startActivityForResult(), allowing you to identify who this 5384 * result came from. 5385 * @param resultCode The integer result code returned by the child activity 5386 * through its setResult(). 5387 * @param data An Intent, which can return result data to the caller 5388 * (various data can be attached to Intent "extras"). 5389 * @hide 5390 */ 5391 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5392 // Do nothing. 5393 } 5394 5395 /** 5396 * Register a callback to be invoked when a hardware key is pressed in this view. 5397 * Key presses in software input methods will generally not trigger the methods of 5398 * this listener. 5399 * @param l the key listener to attach to this view 5400 */ 5401 public void setOnKeyListener(OnKeyListener l) { 5402 getListenerInfo().mOnKeyListener = l; 5403 } 5404 5405 /** 5406 * Register a callback to be invoked when a touch event is sent to this view. 5407 * @param l the touch listener to attach to this view 5408 */ 5409 public void setOnTouchListener(OnTouchListener l) { 5410 getListenerInfo().mOnTouchListener = l; 5411 } 5412 5413 /** 5414 * Register a callback to be invoked when a generic motion event is sent to this view. 5415 * @param l the generic motion listener to attach to this view 5416 */ 5417 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5418 getListenerInfo().mOnGenericMotionListener = l; 5419 } 5420 5421 /** 5422 * Register a callback to be invoked when a hover event is sent to this view. 5423 * @param l the hover listener to attach to this view 5424 */ 5425 public void setOnHoverListener(OnHoverListener l) { 5426 getListenerInfo().mOnHoverListener = l; 5427 } 5428 5429 /** 5430 * Register a drag event listener callback object for this View. The parameter is 5431 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5432 * View, the system calls the 5433 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5434 * @param l An implementation of {@link android.view.View.OnDragListener}. 5435 */ 5436 public void setOnDragListener(OnDragListener l) { 5437 getListenerInfo().mOnDragListener = l; 5438 } 5439 5440 /** 5441 * Give this view focus. This will cause 5442 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5443 * 5444 * Note: this does not check whether this {@link View} should get focus, it just 5445 * gives it focus no matter what. It should only be called internally by framework 5446 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5447 * 5448 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5449 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5450 * focus moved when requestFocus() is called. It may not always 5451 * apply, in which case use the default View.FOCUS_DOWN. 5452 * @param previouslyFocusedRect The rectangle of the view that had focus 5453 * prior in this View's coordinate system. 5454 */ 5455 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5456 if (DBG) { 5457 System.out.println(this + " requestFocus()"); 5458 } 5459 5460 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5461 mPrivateFlags |= PFLAG_FOCUSED; 5462 5463 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5464 5465 if (mParent != null) { 5466 mParent.requestChildFocus(this, this); 5467 } 5468 5469 if (mAttachInfo != null) { 5470 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5471 } 5472 5473 onFocusChanged(true, direction, previouslyFocusedRect); 5474 refreshDrawableState(); 5475 } 5476 } 5477 5478 /** 5479 * Populates <code>outRect</code> with the hotspot bounds. By default, 5480 * the hotspot bounds are identical to the screen bounds. 5481 * 5482 * @param outRect rect to populate with hotspot bounds 5483 * @hide Only for internal use by views and widgets. 5484 */ 5485 public void getHotspotBounds(Rect outRect) { 5486 final Drawable background = getBackground(); 5487 if (background != null) { 5488 background.getHotspotBounds(outRect); 5489 } else { 5490 getBoundsOnScreen(outRect); 5491 } 5492 } 5493 5494 /** 5495 * Request that a rectangle of this view be visible on the screen, 5496 * scrolling if necessary just enough. 5497 * 5498 * <p>A View should call this if it maintains some notion of which part 5499 * of its content is interesting. For example, a text editing view 5500 * should call this when its cursor moves. 5501 * 5502 * @param rectangle The rectangle. 5503 * @return Whether any parent scrolled. 5504 */ 5505 public boolean requestRectangleOnScreen(Rect rectangle) { 5506 return requestRectangleOnScreen(rectangle, false); 5507 } 5508 5509 /** 5510 * Request that a rectangle of this view be visible on the screen, 5511 * scrolling if necessary just enough. 5512 * 5513 * <p>A View should call this if it maintains some notion of which part 5514 * of its content is interesting. For example, a text editing view 5515 * should call this when its cursor moves. 5516 * 5517 * <p>When <code>immediate</code> is set to true, scrolling will not be 5518 * animated. 5519 * 5520 * @param rectangle The rectangle. 5521 * @param immediate True to forbid animated scrolling, false otherwise 5522 * @return Whether any parent scrolled. 5523 */ 5524 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5525 if (mParent == null) { 5526 return false; 5527 } 5528 5529 View child = this; 5530 5531 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5532 position.set(rectangle); 5533 5534 ViewParent parent = mParent; 5535 boolean scrolled = false; 5536 while (parent != null) { 5537 rectangle.set((int) position.left, (int) position.top, 5538 (int) position.right, (int) position.bottom); 5539 5540 scrolled |= parent.requestChildRectangleOnScreen(child, 5541 rectangle, immediate); 5542 5543 if (!child.hasIdentityMatrix()) { 5544 child.getMatrix().mapRect(position); 5545 } 5546 5547 position.offset(child.mLeft, child.mTop); 5548 5549 if (!(parent instanceof View)) { 5550 break; 5551 } 5552 5553 View parentView = (View) parent; 5554 5555 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5556 5557 child = parentView; 5558 parent = child.getParent(); 5559 } 5560 5561 return scrolled; 5562 } 5563 5564 /** 5565 * Called when this view wants to give up focus. If focus is cleared 5566 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5567 * <p> 5568 * <strong>Note:</strong> When a View clears focus the framework is trying 5569 * to give focus to the first focusable View from the top. Hence, if this 5570 * View is the first from the top that can take focus, then all callbacks 5571 * related to clearing focus will be invoked after which the framework will 5572 * give focus to this view. 5573 * </p> 5574 */ 5575 public void clearFocus() { 5576 if (DBG) { 5577 System.out.println(this + " clearFocus()"); 5578 } 5579 5580 clearFocusInternal(null, true, true); 5581 } 5582 5583 /** 5584 * Clears focus from the view, optionally propagating the change up through 5585 * the parent hierarchy and requesting that the root view place new focus. 5586 * 5587 * @param propagate whether to propagate the change up through the parent 5588 * hierarchy 5589 * @param refocus when propagate is true, specifies whether to request the 5590 * root view place new focus 5591 */ 5592 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5593 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5594 mPrivateFlags &= ~PFLAG_FOCUSED; 5595 5596 if (propagate && mParent != null) { 5597 mParent.clearChildFocus(this); 5598 } 5599 5600 onFocusChanged(false, 0, null); 5601 refreshDrawableState(); 5602 5603 if (propagate && (!refocus || !rootViewRequestFocus())) { 5604 notifyGlobalFocusCleared(this); 5605 } 5606 } 5607 } 5608 5609 void notifyGlobalFocusCleared(View oldFocus) { 5610 if (oldFocus != null && mAttachInfo != null) { 5611 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5612 } 5613 } 5614 5615 boolean rootViewRequestFocus() { 5616 final View root = getRootView(); 5617 return root != null && root.requestFocus(); 5618 } 5619 5620 /** 5621 * Called internally by the view system when a new view is getting focus. 5622 * This is what clears the old focus. 5623 * <p> 5624 * <b>NOTE:</b> The parent view's focused child must be updated manually 5625 * after calling this method. Otherwise, the view hierarchy may be left in 5626 * an inconstent state. 5627 */ 5628 void unFocus(View focused) { 5629 if (DBG) { 5630 System.out.println(this + " unFocus()"); 5631 } 5632 5633 clearFocusInternal(focused, false, false); 5634 } 5635 5636 /** 5637 * Returns true if this view has focus itself, or is the ancestor of the 5638 * view that has focus. 5639 * 5640 * @return True if this view has or contains focus, false otherwise. 5641 */ 5642 @ViewDebug.ExportedProperty(category = "focus") 5643 public boolean hasFocus() { 5644 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5645 } 5646 5647 /** 5648 * Returns true if this view is focusable or if it contains a reachable View 5649 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5650 * is a View whose parents do not block descendants focus. 5651 * 5652 * Only {@link #VISIBLE} views are considered focusable. 5653 * 5654 * @return True if the view is focusable or if the view contains a focusable 5655 * View, false otherwise. 5656 * 5657 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5658 * @see ViewGroup#getTouchscreenBlocksFocus() 5659 */ 5660 public boolean hasFocusable() { 5661 if (!isFocusableInTouchMode()) { 5662 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5663 final ViewGroup g = (ViewGroup) p; 5664 if (g.shouldBlockFocusForTouchscreen()) { 5665 return false; 5666 } 5667 } 5668 } 5669 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5670 } 5671 5672 /** 5673 * Called by the view system when the focus state of this view changes. 5674 * When the focus change event is caused by directional navigation, direction 5675 * and previouslyFocusedRect provide insight into where the focus is coming from. 5676 * When overriding, be sure to call up through to the super class so that 5677 * the standard focus handling will occur. 5678 * 5679 * @param gainFocus True if the View has focus; false otherwise. 5680 * @param direction The direction focus has moved when requestFocus() 5681 * is called to give this view focus. Values are 5682 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5683 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5684 * It may not always apply, in which case use the default. 5685 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5686 * system, of the previously focused view. If applicable, this will be 5687 * passed in as finer grained information about where the focus is coming 5688 * from (in addition to direction). Will be <code>null</code> otherwise. 5689 */ 5690 @CallSuper 5691 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5692 @Nullable Rect previouslyFocusedRect) { 5693 if (gainFocus) { 5694 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5695 } else { 5696 notifyViewAccessibilityStateChangedIfNeeded( 5697 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5698 } 5699 5700 InputMethodManager imm = InputMethodManager.peekInstance(); 5701 if (!gainFocus) { 5702 if (isPressed()) { 5703 setPressed(false); 5704 } 5705 if (imm != null && mAttachInfo != null 5706 && mAttachInfo.mHasWindowFocus) { 5707 imm.focusOut(this); 5708 } 5709 onFocusLost(); 5710 } else if (imm != null && mAttachInfo != null 5711 && mAttachInfo.mHasWindowFocus) { 5712 imm.focusIn(this); 5713 } 5714 5715 invalidate(true); 5716 ListenerInfo li = mListenerInfo; 5717 if (li != null && li.mOnFocusChangeListener != null) { 5718 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5719 } 5720 5721 if (mAttachInfo != null) { 5722 mAttachInfo.mKeyDispatchState.reset(this); 5723 } 5724 } 5725 5726 /** 5727 * Sends an accessibility event of the given type. If accessibility is 5728 * not enabled this method has no effect. The default implementation calls 5729 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5730 * to populate information about the event source (this View), then calls 5731 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5732 * populate the text content of the event source including its descendants, 5733 * and last calls 5734 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5735 * on its parent to request sending of the event to interested parties. 5736 * <p> 5737 * If an {@link AccessibilityDelegate} has been specified via calling 5738 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5739 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5740 * responsible for handling this call. 5741 * </p> 5742 * 5743 * @param eventType The type of the event to send, as defined by several types from 5744 * {@link android.view.accessibility.AccessibilityEvent}, such as 5745 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5746 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5747 * 5748 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5749 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5750 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5751 * @see AccessibilityDelegate 5752 */ 5753 public void sendAccessibilityEvent(int eventType) { 5754 if (mAccessibilityDelegate != null) { 5755 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5756 } else { 5757 sendAccessibilityEventInternal(eventType); 5758 } 5759 } 5760 5761 /** 5762 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5763 * {@link AccessibilityEvent} to make an announcement which is related to some 5764 * sort of a context change for which none of the events representing UI transitions 5765 * is a good fit. For example, announcing a new page in a book. If accessibility 5766 * is not enabled this method does nothing. 5767 * 5768 * @param text The announcement text. 5769 */ 5770 public void announceForAccessibility(CharSequence text) { 5771 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5772 AccessibilityEvent event = AccessibilityEvent.obtain( 5773 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5774 onInitializeAccessibilityEvent(event); 5775 event.getText().add(text); 5776 event.setContentDescription(null); 5777 mParent.requestSendAccessibilityEvent(this, event); 5778 } 5779 } 5780 5781 /** 5782 * @see #sendAccessibilityEvent(int) 5783 * 5784 * Note: Called from the default {@link AccessibilityDelegate}. 5785 * 5786 * @hide 5787 */ 5788 public void sendAccessibilityEventInternal(int eventType) { 5789 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5790 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5791 } 5792 } 5793 5794 /** 5795 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5796 * takes as an argument an empty {@link AccessibilityEvent} and does not 5797 * perform a check whether accessibility is enabled. 5798 * <p> 5799 * If an {@link AccessibilityDelegate} has been specified via calling 5800 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5801 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5802 * is responsible for handling this call. 5803 * </p> 5804 * 5805 * @param event The event to send. 5806 * 5807 * @see #sendAccessibilityEvent(int) 5808 */ 5809 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5810 if (mAccessibilityDelegate != null) { 5811 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5812 } else { 5813 sendAccessibilityEventUncheckedInternal(event); 5814 } 5815 } 5816 5817 /** 5818 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5819 * 5820 * Note: Called from the default {@link AccessibilityDelegate}. 5821 * 5822 * @hide 5823 */ 5824 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5825 if (!isShown()) { 5826 return; 5827 } 5828 onInitializeAccessibilityEvent(event); 5829 // Only a subset of accessibility events populates text content. 5830 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5831 dispatchPopulateAccessibilityEvent(event); 5832 } 5833 // In the beginning we called #isShown(), so we know that getParent() is not null. 5834 getParent().requestSendAccessibilityEvent(this, event); 5835 } 5836 5837 /** 5838 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5839 * to its children for adding their text content to the event. Note that the 5840 * event text is populated in a separate dispatch path since we add to the 5841 * event not only the text of the source but also the text of all its descendants. 5842 * A typical implementation will call 5843 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5844 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5845 * on each child. Override this method if custom population of the event text 5846 * content is required. 5847 * <p> 5848 * If an {@link AccessibilityDelegate} has been specified via calling 5849 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5850 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5851 * is responsible for handling this call. 5852 * </p> 5853 * <p> 5854 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5855 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5856 * </p> 5857 * 5858 * @param event The event. 5859 * 5860 * @return True if the event population was completed. 5861 */ 5862 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5863 if (mAccessibilityDelegate != null) { 5864 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5865 } else { 5866 return dispatchPopulateAccessibilityEventInternal(event); 5867 } 5868 } 5869 5870 /** 5871 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5872 * 5873 * Note: Called from the default {@link AccessibilityDelegate}. 5874 * 5875 * @hide 5876 */ 5877 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5878 onPopulateAccessibilityEvent(event); 5879 return false; 5880 } 5881 5882 /** 5883 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5884 * giving a chance to this View to populate the accessibility event with its 5885 * text content. While this method is free to modify event 5886 * attributes other than text content, doing so should normally be performed in 5887 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5888 * <p> 5889 * Example: Adding formatted date string to an accessibility event in addition 5890 * to the text added by the super implementation: 5891 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5892 * super.onPopulateAccessibilityEvent(event); 5893 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5894 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5895 * mCurrentDate.getTimeInMillis(), flags); 5896 * event.getText().add(selectedDateUtterance); 5897 * }</pre> 5898 * <p> 5899 * If an {@link AccessibilityDelegate} has been specified via calling 5900 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5901 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5902 * is responsible for handling this call. 5903 * </p> 5904 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5905 * information to the event, in case the default implementation has basic information to add. 5906 * </p> 5907 * 5908 * @param event The accessibility event which to populate. 5909 * 5910 * @see #sendAccessibilityEvent(int) 5911 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5912 */ 5913 @CallSuper 5914 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5915 if (mAccessibilityDelegate != null) { 5916 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5917 } else { 5918 onPopulateAccessibilityEventInternal(event); 5919 } 5920 } 5921 5922 /** 5923 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5924 * 5925 * Note: Called from the default {@link AccessibilityDelegate}. 5926 * 5927 * @hide 5928 */ 5929 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5930 } 5931 5932 /** 5933 * Initializes an {@link AccessibilityEvent} with information about 5934 * this View which is the event source. In other words, the source of 5935 * an accessibility event is the view whose state change triggered firing 5936 * the event. 5937 * <p> 5938 * Example: Setting the password property of an event in addition 5939 * to properties set by the super implementation: 5940 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5941 * super.onInitializeAccessibilityEvent(event); 5942 * event.setPassword(true); 5943 * }</pre> 5944 * <p> 5945 * If an {@link AccessibilityDelegate} has been specified via calling 5946 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5947 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5948 * is responsible for handling this call. 5949 * </p> 5950 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5951 * information to the event, in case the default implementation has basic information to add. 5952 * </p> 5953 * @param event The event to initialize. 5954 * 5955 * @see #sendAccessibilityEvent(int) 5956 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5957 */ 5958 @CallSuper 5959 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5960 if (mAccessibilityDelegate != null) { 5961 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5962 } else { 5963 onInitializeAccessibilityEventInternal(event); 5964 } 5965 } 5966 5967 /** 5968 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5969 * 5970 * Note: Called from the default {@link AccessibilityDelegate}. 5971 * 5972 * @hide 5973 */ 5974 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5975 event.setSource(this); 5976 event.setClassName(getAccessibilityClassName()); 5977 event.setPackageName(getContext().getPackageName()); 5978 event.setEnabled(isEnabled()); 5979 event.setContentDescription(mContentDescription); 5980 5981 switch (event.getEventType()) { 5982 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5983 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5984 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5985 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5986 event.setItemCount(focusablesTempList.size()); 5987 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5988 if (mAttachInfo != null) { 5989 focusablesTempList.clear(); 5990 } 5991 } break; 5992 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5993 CharSequence text = getIterableTextForAccessibility(); 5994 if (text != null && text.length() > 0) { 5995 event.setFromIndex(getAccessibilitySelectionStart()); 5996 event.setToIndex(getAccessibilitySelectionEnd()); 5997 event.setItemCount(text.length()); 5998 } 5999 } break; 6000 } 6001 } 6002 6003 /** 6004 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6005 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6006 * This method is responsible for obtaining an accessibility node info from a 6007 * pool of reusable instances and calling 6008 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6009 * initialize the former. 6010 * <p> 6011 * Note: The client is responsible for recycling the obtained instance by calling 6012 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6013 * </p> 6014 * 6015 * @return A populated {@link AccessibilityNodeInfo}. 6016 * 6017 * @see AccessibilityNodeInfo 6018 */ 6019 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6020 if (mAccessibilityDelegate != null) { 6021 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6022 } else { 6023 return createAccessibilityNodeInfoInternal(); 6024 } 6025 } 6026 6027 /** 6028 * @see #createAccessibilityNodeInfo() 6029 * 6030 * @hide 6031 */ 6032 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6033 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6034 if (provider != null) { 6035 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6036 } else { 6037 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6038 onInitializeAccessibilityNodeInfo(info); 6039 return info; 6040 } 6041 } 6042 6043 /** 6044 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6045 * The base implementation sets: 6046 * <ul> 6047 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6048 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6049 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6050 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6051 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6052 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6053 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6054 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6055 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6056 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6057 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6058 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6059 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6060 * </ul> 6061 * <p> 6062 * Subclasses should override this method, call the super implementation, 6063 * and set additional attributes. 6064 * </p> 6065 * <p> 6066 * If an {@link AccessibilityDelegate} has been specified via calling 6067 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6068 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6069 * is responsible for handling this call. 6070 * </p> 6071 * 6072 * @param info The instance to initialize. 6073 */ 6074 @CallSuper 6075 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6076 if (mAccessibilityDelegate != null) { 6077 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6078 } else { 6079 onInitializeAccessibilityNodeInfoInternal(info); 6080 } 6081 } 6082 6083 /** 6084 * Gets the location of this view in screen coordinates. 6085 * 6086 * @param outRect The output location 6087 * @hide 6088 */ 6089 public void getBoundsOnScreen(Rect outRect) { 6090 getBoundsOnScreen(outRect, false); 6091 } 6092 6093 /** 6094 * Gets the location of this view in screen coordinates. 6095 * 6096 * @param outRect The output location 6097 * @param clipToParent Whether to clip child bounds to the parent ones. 6098 * @hide 6099 */ 6100 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6101 if (mAttachInfo == null) { 6102 return; 6103 } 6104 6105 RectF position = mAttachInfo.mTmpTransformRect; 6106 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6107 6108 if (!hasIdentityMatrix()) { 6109 getMatrix().mapRect(position); 6110 } 6111 6112 position.offset(mLeft, mTop); 6113 6114 ViewParent parent = mParent; 6115 while (parent instanceof View) { 6116 View parentView = (View) parent; 6117 6118 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6119 6120 if (clipToParent) { 6121 position.left = Math.max(position.left, 0); 6122 position.top = Math.max(position.top, 0); 6123 position.right = Math.min(position.right, parentView.getWidth()); 6124 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6125 } 6126 6127 if (!parentView.hasIdentityMatrix()) { 6128 parentView.getMatrix().mapRect(position); 6129 } 6130 6131 position.offset(parentView.mLeft, parentView.mTop); 6132 6133 parent = parentView.mParent; 6134 } 6135 6136 if (parent instanceof ViewRootImpl) { 6137 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6138 position.offset(0, -viewRootImpl.mCurScrollY); 6139 } 6140 6141 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6142 6143 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 6144 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 6145 } 6146 6147 /** 6148 * Return the class name of this object to be used for accessibility purposes. 6149 * Subclasses should only override this if they are implementing something that 6150 * should be seen as a completely new class of view when used by accessibility, 6151 * unrelated to the class it is deriving from. This is used to fill in 6152 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6153 */ 6154 public CharSequence getAccessibilityClassName() { 6155 return View.class.getName(); 6156 } 6157 6158 /** 6159 * Called when assist structure is being retrieved from a view as part of 6160 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6161 * @param structure Fill in with structured view data. The default implementation 6162 * fills in all data that can be inferred from the view itself. 6163 */ 6164 public void onProvideStructure(ViewStructure structure) { 6165 final int id = mID; 6166 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6167 && (id&0x0000ffff) != 0) { 6168 String pkg, type, entry; 6169 try { 6170 final Resources res = getResources(); 6171 entry = res.getResourceEntryName(id); 6172 type = res.getResourceTypeName(id); 6173 pkg = res.getResourcePackageName(id); 6174 } catch (Resources.NotFoundException e) { 6175 entry = type = pkg = null; 6176 } 6177 structure.setId(id, pkg, type, entry); 6178 } else { 6179 structure.setId(id, null, null, null); 6180 } 6181 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6182 if (!hasIdentityMatrix()) { 6183 structure.setTransformation(getMatrix()); 6184 } 6185 structure.setElevation(getZ()); 6186 structure.setVisibility(getVisibility()); 6187 structure.setEnabled(isEnabled()); 6188 if (isClickable()) { 6189 structure.setClickable(true); 6190 } 6191 if (isFocusable()) { 6192 structure.setFocusable(true); 6193 } 6194 if (isFocused()) { 6195 structure.setFocused(true); 6196 } 6197 if (isAccessibilityFocused()) { 6198 structure.setAccessibilityFocused(true); 6199 } 6200 if (isSelected()) { 6201 structure.setSelected(true); 6202 } 6203 if (isActivated()) { 6204 structure.setActivated(true); 6205 } 6206 if (isLongClickable()) { 6207 structure.setLongClickable(true); 6208 } 6209 if (this instanceof Checkable) { 6210 structure.setCheckable(true); 6211 if (((Checkable)this).isChecked()) { 6212 structure.setChecked(true); 6213 } 6214 } 6215 if (isContextClickable()) { 6216 structure.setContextClickable(true); 6217 } 6218 structure.setClassName(getAccessibilityClassName().toString()); 6219 structure.setContentDescription(getContentDescription()); 6220 } 6221 6222 /** 6223 * Called when assist structure is being retrieved from a view as part of 6224 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6225 * generate additional virtual structure under this view. The defaullt implementation 6226 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6227 * view's virtual accessibility nodes, if any. You can override this for a more 6228 * optimal implementation providing this data. 6229 */ 6230 public void onProvideVirtualStructure(ViewStructure structure) { 6231 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6232 if (provider != null) { 6233 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6234 structure.setChildCount(1); 6235 ViewStructure root = structure.newChild(0); 6236 populateVirtualStructure(root, provider, info); 6237 info.recycle(); 6238 } 6239 } 6240 6241 private void populateVirtualStructure(ViewStructure structure, 6242 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6243 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6244 null, null, null); 6245 Rect rect = structure.getTempRect(); 6246 info.getBoundsInParent(rect); 6247 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6248 structure.setVisibility(VISIBLE); 6249 structure.setEnabled(info.isEnabled()); 6250 if (info.isClickable()) { 6251 structure.setClickable(true); 6252 } 6253 if (info.isFocusable()) { 6254 structure.setFocusable(true); 6255 } 6256 if (info.isFocused()) { 6257 structure.setFocused(true); 6258 } 6259 if (info.isAccessibilityFocused()) { 6260 structure.setAccessibilityFocused(true); 6261 } 6262 if (info.isSelected()) { 6263 structure.setSelected(true); 6264 } 6265 if (info.isLongClickable()) { 6266 structure.setLongClickable(true); 6267 } 6268 if (info.isCheckable()) { 6269 structure.setCheckable(true); 6270 if (info.isChecked()) { 6271 structure.setChecked(true); 6272 } 6273 } 6274 if (info.isContextClickable()) { 6275 structure.setContextClickable(true); 6276 } 6277 CharSequence cname = info.getClassName(); 6278 structure.setClassName(cname != null ? cname.toString() : null); 6279 structure.setContentDescription(info.getContentDescription()); 6280 if (info.getText() != null || info.getError() != null) { 6281 structure.setText(info.getText(), info.getTextSelectionStart(), 6282 info.getTextSelectionEnd()); 6283 } 6284 final int NCHILDREN = info.getChildCount(); 6285 if (NCHILDREN > 0) { 6286 structure.setChildCount(NCHILDREN); 6287 for (int i=0; i<NCHILDREN; i++) { 6288 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6289 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6290 ViewStructure child = structure.newChild(i); 6291 populateVirtualStructure(child, provider, cinfo); 6292 cinfo.recycle(); 6293 } 6294 } 6295 } 6296 6297 /** 6298 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6299 * implementation calls {@link #onProvideStructure} and 6300 * {@link #onProvideVirtualStructure}. 6301 */ 6302 public void dispatchProvideStructure(ViewStructure structure) { 6303 if (!isAssistBlocked()) { 6304 onProvideStructure(structure); 6305 onProvideVirtualStructure(structure); 6306 } else { 6307 structure.setClassName(getAccessibilityClassName().toString()); 6308 structure.setAssistBlocked(true); 6309 } 6310 } 6311 6312 /** 6313 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6314 * 6315 * Note: Called from the default {@link AccessibilityDelegate}. 6316 * 6317 * @hide 6318 */ 6319 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6320 if (mAttachInfo == null) { 6321 return; 6322 } 6323 6324 Rect bounds = mAttachInfo.mTmpInvalRect; 6325 6326 getDrawingRect(bounds); 6327 info.setBoundsInParent(bounds); 6328 6329 getBoundsOnScreen(bounds, true); 6330 info.setBoundsInScreen(bounds); 6331 6332 ViewParent parent = getParentForAccessibility(); 6333 if (parent instanceof View) { 6334 info.setParent((View) parent); 6335 } 6336 6337 if (mID != View.NO_ID) { 6338 View rootView = getRootView(); 6339 if (rootView == null) { 6340 rootView = this; 6341 } 6342 6343 View label = rootView.findLabelForView(this, mID); 6344 if (label != null) { 6345 info.setLabeledBy(label); 6346 } 6347 6348 if ((mAttachInfo.mAccessibilityFetchFlags 6349 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6350 && Resources.resourceHasPackage(mID)) { 6351 try { 6352 String viewId = getResources().getResourceName(mID); 6353 info.setViewIdResourceName(viewId); 6354 } catch (Resources.NotFoundException nfe) { 6355 /* ignore */ 6356 } 6357 } 6358 } 6359 6360 if (mLabelForId != View.NO_ID) { 6361 View rootView = getRootView(); 6362 if (rootView == null) { 6363 rootView = this; 6364 } 6365 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6366 if (labeled != null) { 6367 info.setLabelFor(labeled); 6368 } 6369 } 6370 6371 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6372 View rootView = getRootView(); 6373 if (rootView == null) { 6374 rootView = this; 6375 } 6376 View next = rootView.findViewInsideOutShouldExist(this, 6377 mAccessibilityTraversalBeforeId); 6378 if (next != null && next.includeForAccessibility()) { 6379 info.setTraversalBefore(next); 6380 } 6381 } 6382 6383 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6384 View rootView = getRootView(); 6385 if (rootView == null) { 6386 rootView = this; 6387 } 6388 View next = rootView.findViewInsideOutShouldExist(this, 6389 mAccessibilityTraversalAfterId); 6390 if (next != null && next.includeForAccessibility()) { 6391 info.setTraversalAfter(next); 6392 } 6393 } 6394 6395 info.setVisibleToUser(isVisibleToUser()); 6396 6397 info.setPackageName(mContext.getPackageName()); 6398 info.setClassName(getAccessibilityClassName()); 6399 info.setContentDescription(getContentDescription()); 6400 6401 info.setEnabled(isEnabled()); 6402 info.setClickable(isClickable()); 6403 info.setFocusable(isFocusable()); 6404 info.setFocused(isFocused()); 6405 info.setAccessibilityFocused(isAccessibilityFocused()); 6406 info.setSelected(isSelected()); 6407 info.setLongClickable(isLongClickable()); 6408 info.setContextClickable(isContextClickable()); 6409 info.setLiveRegion(getAccessibilityLiveRegion()); 6410 6411 // TODO: These make sense only if we are in an AdapterView but all 6412 // views can be selected. Maybe from accessibility perspective 6413 // we should report as selectable view in an AdapterView. 6414 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6415 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6416 6417 if (isFocusable()) { 6418 if (isFocused()) { 6419 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6420 } else { 6421 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6422 } 6423 } 6424 6425 if (!isAccessibilityFocused()) { 6426 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6427 } else { 6428 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6429 } 6430 6431 if (isClickable() && isEnabled()) { 6432 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6433 } 6434 6435 if (isLongClickable() && isEnabled()) { 6436 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6437 } 6438 6439 if (isContextClickable() && isEnabled()) { 6440 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 6441 } 6442 6443 CharSequence text = getIterableTextForAccessibility(); 6444 if (text != null && text.length() > 0) { 6445 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6446 6447 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6448 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6449 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6450 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6451 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6452 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6453 } 6454 6455 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6456 } 6457 6458 private View findLabelForView(View view, int labeledId) { 6459 if (mMatchLabelForPredicate == null) { 6460 mMatchLabelForPredicate = new MatchLabelForPredicate(); 6461 } 6462 mMatchLabelForPredicate.mLabeledId = labeledId; 6463 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 6464 } 6465 6466 /** 6467 * Computes whether this view is visible to the user. Such a view is 6468 * attached, visible, all its predecessors are visible, it is not clipped 6469 * entirely by its predecessors, and has an alpha greater than zero. 6470 * 6471 * @return Whether the view is visible on the screen. 6472 * 6473 * @hide 6474 */ 6475 protected boolean isVisibleToUser() { 6476 return isVisibleToUser(null); 6477 } 6478 6479 /** 6480 * Computes whether the given portion of this view is visible to the user. 6481 * Such a view is attached, visible, all its predecessors are visible, 6482 * has an alpha greater than zero, and the specified portion is not 6483 * clipped entirely by its predecessors. 6484 * 6485 * @param boundInView the portion of the view to test; coordinates should be relative; may be 6486 * <code>null</code>, and the entire view will be tested in this case. 6487 * When <code>true</code> is returned by the function, the actual visible 6488 * region will be stored in this parameter; that is, if boundInView is fully 6489 * contained within the view, no modification will be made, otherwise regions 6490 * outside of the visible area of the view will be clipped. 6491 * 6492 * @return Whether the specified portion of the view is visible on the screen. 6493 * 6494 * @hide 6495 */ 6496 protected boolean isVisibleToUser(Rect boundInView) { 6497 if (mAttachInfo != null) { 6498 // Attached to invisible window means this view is not visible. 6499 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 6500 return false; 6501 } 6502 // An invisible predecessor or one with alpha zero means 6503 // that this view is not visible to the user. 6504 Object current = this; 6505 while (current instanceof View) { 6506 View view = (View) current; 6507 // We have attach info so this view is attached and there is no 6508 // need to check whether we reach to ViewRootImpl on the way up. 6509 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 6510 view.getVisibility() != VISIBLE) { 6511 return false; 6512 } 6513 current = view.mParent; 6514 } 6515 // Check if the view is entirely covered by its predecessors. 6516 Rect visibleRect = mAttachInfo.mTmpInvalRect; 6517 Point offset = mAttachInfo.mPoint; 6518 if (!getGlobalVisibleRect(visibleRect, offset)) { 6519 return false; 6520 } 6521 // Check if the visible portion intersects the rectangle of interest. 6522 if (boundInView != null) { 6523 visibleRect.offset(-offset.x, -offset.y); 6524 return boundInView.intersect(visibleRect); 6525 } 6526 return true; 6527 } 6528 return false; 6529 } 6530 6531 /** 6532 * Returns the delegate for implementing accessibility support via 6533 * composition. For more details see {@link AccessibilityDelegate}. 6534 * 6535 * @return The delegate, or null if none set. 6536 * 6537 * @hide 6538 */ 6539 public AccessibilityDelegate getAccessibilityDelegate() { 6540 return mAccessibilityDelegate; 6541 } 6542 6543 /** 6544 * Sets a delegate for implementing accessibility support via composition as 6545 * opposed to inheritance. The delegate's primary use is for implementing 6546 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 6547 * 6548 * @param delegate The delegate instance. 6549 * 6550 * @see AccessibilityDelegate 6551 */ 6552 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 6553 mAccessibilityDelegate = delegate; 6554 } 6555 6556 /** 6557 * Gets the provider for managing a virtual view hierarchy rooted at this View 6558 * and reported to {@link android.accessibilityservice.AccessibilityService}s 6559 * that explore the window content. 6560 * <p> 6561 * If this method returns an instance, this instance is responsible for managing 6562 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 6563 * View including the one representing the View itself. Similarly the returned 6564 * instance is responsible for performing accessibility actions on any virtual 6565 * view or the root view itself. 6566 * </p> 6567 * <p> 6568 * If an {@link AccessibilityDelegate} has been specified via calling 6569 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6570 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 6571 * is responsible for handling this call. 6572 * </p> 6573 * 6574 * @return The provider. 6575 * 6576 * @see AccessibilityNodeProvider 6577 */ 6578 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 6579 if (mAccessibilityDelegate != null) { 6580 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 6581 } else { 6582 return null; 6583 } 6584 } 6585 6586 /** 6587 * Gets the unique identifier of this view on the screen for accessibility purposes. 6588 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 6589 * 6590 * @return The view accessibility id. 6591 * 6592 * @hide 6593 */ 6594 public int getAccessibilityViewId() { 6595 if (mAccessibilityViewId == NO_ID) { 6596 mAccessibilityViewId = sNextAccessibilityViewId++; 6597 } 6598 return mAccessibilityViewId; 6599 } 6600 6601 /** 6602 * Gets the unique identifier of the window in which this View reseides. 6603 * 6604 * @return The window accessibility id. 6605 * 6606 * @hide 6607 */ 6608 public int getAccessibilityWindowId() { 6609 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 6610 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 6611 } 6612 6613 /** 6614 * Gets the {@link View} description. It briefly describes the view and is 6615 * primarily used for accessibility support. Set this property to enable 6616 * better accessibility support for your application. This is especially 6617 * true for views that do not have textual representation (For example, 6618 * ImageButton). 6619 * 6620 * @return The content description. 6621 * 6622 * @attr ref android.R.styleable#View_contentDescription 6623 */ 6624 @ViewDebug.ExportedProperty(category = "accessibility") 6625 public CharSequence getContentDescription() { 6626 return mContentDescription; 6627 } 6628 6629 /** 6630 * Sets the {@link View} description. It briefly describes the view and is 6631 * primarily used for accessibility support. Set this property to enable 6632 * better accessibility support for your application. This is especially 6633 * true for views that do not have textual representation (For example, 6634 * ImageButton). 6635 * 6636 * @param contentDescription The content description. 6637 * 6638 * @attr ref android.R.styleable#View_contentDescription 6639 */ 6640 @RemotableViewMethod 6641 public void setContentDescription(CharSequence contentDescription) { 6642 if (mContentDescription == null) { 6643 if (contentDescription == null) { 6644 return; 6645 } 6646 } else if (mContentDescription.equals(contentDescription)) { 6647 return; 6648 } 6649 mContentDescription = contentDescription; 6650 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 6651 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 6652 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 6653 notifySubtreeAccessibilityStateChangedIfNeeded(); 6654 } else { 6655 notifyViewAccessibilityStateChangedIfNeeded( 6656 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 6657 } 6658 } 6659 6660 /** 6661 * Sets the id of a view before which this one is visited in accessibility traversal. 6662 * A screen-reader must visit the content of this view before the content of the one 6663 * it precedes. For example, if view B is set to be before view A, then a screen-reader 6664 * will traverse the entire content of B before traversing the entire content of A, 6665 * regardles of what traversal strategy it is using. 6666 * <p> 6667 * Views that do not have specified before/after relationships are traversed in order 6668 * determined by the screen-reader. 6669 * </p> 6670 * <p> 6671 * Setting that this view is before a view that is not important for accessibility 6672 * or if this view is not important for accessibility will have no effect as the 6673 * screen-reader is not aware of unimportant views. 6674 * </p> 6675 * 6676 * @param beforeId The id of a view this one precedes in accessibility traversal. 6677 * 6678 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 6679 * 6680 * @see #setImportantForAccessibility(int) 6681 */ 6682 @RemotableViewMethod 6683 public void setAccessibilityTraversalBefore(int beforeId) { 6684 if (mAccessibilityTraversalBeforeId == beforeId) { 6685 return; 6686 } 6687 mAccessibilityTraversalBeforeId = beforeId; 6688 notifyViewAccessibilityStateChangedIfNeeded( 6689 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6690 } 6691 6692 /** 6693 * Gets the id of a view before which this one is visited in accessibility traversal. 6694 * 6695 * @return The id of a view this one precedes in accessibility traversal if 6696 * specified, otherwise {@link #NO_ID}. 6697 * 6698 * @see #setAccessibilityTraversalBefore(int) 6699 */ 6700 public int getAccessibilityTraversalBefore() { 6701 return mAccessibilityTraversalBeforeId; 6702 } 6703 6704 /** 6705 * Sets the id of a view after which this one is visited in accessibility traversal. 6706 * A screen-reader must visit the content of the other view before the content of this 6707 * one. For example, if view B is set to be after view A, then a screen-reader 6708 * will traverse the entire content of A before traversing the entire content of B, 6709 * regardles of what traversal strategy it is using. 6710 * <p> 6711 * Views that do not have specified before/after relationships are traversed in order 6712 * determined by the screen-reader. 6713 * </p> 6714 * <p> 6715 * Setting that this view is after a view that is not important for accessibility 6716 * or if this view is not important for accessibility will have no effect as the 6717 * screen-reader is not aware of unimportant views. 6718 * </p> 6719 * 6720 * @param afterId The id of a view this one succedees in accessibility traversal. 6721 * 6722 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 6723 * 6724 * @see #setImportantForAccessibility(int) 6725 */ 6726 @RemotableViewMethod 6727 public void setAccessibilityTraversalAfter(int afterId) { 6728 if (mAccessibilityTraversalAfterId == afterId) { 6729 return; 6730 } 6731 mAccessibilityTraversalAfterId = afterId; 6732 notifyViewAccessibilityStateChangedIfNeeded( 6733 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6734 } 6735 6736 /** 6737 * Gets the id of a view after which this one is visited in accessibility traversal. 6738 * 6739 * @return The id of a view this one succeedes in accessibility traversal if 6740 * specified, otherwise {@link #NO_ID}. 6741 * 6742 * @see #setAccessibilityTraversalAfter(int) 6743 */ 6744 public int getAccessibilityTraversalAfter() { 6745 return mAccessibilityTraversalAfterId; 6746 } 6747 6748 /** 6749 * Gets the id of a view for which this view serves as a label for 6750 * accessibility purposes. 6751 * 6752 * @return The labeled view id. 6753 */ 6754 @ViewDebug.ExportedProperty(category = "accessibility") 6755 public int getLabelFor() { 6756 return mLabelForId; 6757 } 6758 6759 /** 6760 * Sets the id of a view for which this view serves as a label for 6761 * accessibility purposes. 6762 * 6763 * @param id The labeled view id. 6764 */ 6765 @RemotableViewMethod 6766 public void setLabelFor(@IdRes int id) { 6767 if (mLabelForId == id) { 6768 return; 6769 } 6770 mLabelForId = id; 6771 if (mLabelForId != View.NO_ID 6772 && mID == View.NO_ID) { 6773 mID = generateViewId(); 6774 } 6775 notifyViewAccessibilityStateChangedIfNeeded( 6776 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6777 } 6778 6779 /** 6780 * Invoked whenever this view loses focus, either by losing window focus or by losing 6781 * focus within its window. This method can be used to clear any state tied to the 6782 * focus. For instance, if a button is held pressed with the trackball and the window 6783 * loses focus, this method can be used to cancel the press. 6784 * 6785 * Subclasses of View overriding this method should always call super.onFocusLost(). 6786 * 6787 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6788 * @see #onWindowFocusChanged(boolean) 6789 * 6790 * @hide pending API council approval 6791 */ 6792 @CallSuper 6793 protected void onFocusLost() { 6794 resetPressedState(); 6795 } 6796 6797 private void resetPressedState() { 6798 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6799 return; 6800 } 6801 6802 if (isPressed()) { 6803 setPressed(false); 6804 6805 if (!mHasPerformedLongPress) { 6806 removeLongPressCallback(); 6807 } 6808 } 6809 } 6810 6811 /** 6812 * Returns true if this view has focus 6813 * 6814 * @return True if this view has focus, false otherwise. 6815 */ 6816 @ViewDebug.ExportedProperty(category = "focus") 6817 public boolean isFocused() { 6818 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6819 } 6820 6821 /** 6822 * Find the view in the hierarchy rooted at this view that currently has 6823 * focus. 6824 * 6825 * @return The view that currently has focus, or null if no focused view can 6826 * be found. 6827 */ 6828 public View findFocus() { 6829 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6830 } 6831 6832 /** 6833 * Indicates whether this view is one of the set of scrollable containers in 6834 * its window. 6835 * 6836 * @return whether this view is one of the set of scrollable containers in 6837 * its window 6838 * 6839 * @attr ref android.R.styleable#View_isScrollContainer 6840 */ 6841 public boolean isScrollContainer() { 6842 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6843 } 6844 6845 /** 6846 * Change whether this view is one of the set of scrollable containers in 6847 * its window. This will be used to determine whether the window can 6848 * resize or must pan when a soft input area is open -- scrollable 6849 * containers allow the window to use resize mode since the container 6850 * will appropriately shrink. 6851 * 6852 * @attr ref android.R.styleable#View_isScrollContainer 6853 */ 6854 public void setScrollContainer(boolean isScrollContainer) { 6855 if (isScrollContainer) { 6856 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6857 mAttachInfo.mScrollContainers.add(this); 6858 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6859 } 6860 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6861 } else { 6862 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6863 mAttachInfo.mScrollContainers.remove(this); 6864 } 6865 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6866 } 6867 } 6868 6869 /** 6870 * Returns the quality of the drawing cache. 6871 * 6872 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6873 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6874 * 6875 * @see #setDrawingCacheQuality(int) 6876 * @see #setDrawingCacheEnabled(boolean) 6877 * @see #isDrawingCacheEnabled() 6878 * 6879 * @attr ref android.R.styleable#View_drawingCacheQuality 6880 */ 6881 @DrawingCacheQuality 6882 public int getDrawingCacheQuality() { 6883 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6884 } 6885 6886 /** 6887 * Set the drawing cache quality of this view. This value is used only when the 6888 * drawing cache is enabled 6889 * 6890 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6891 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6892 * 6893 * @see #getDrawingCacheQuality() 6894 * @see #setDrawingCacheEnabled(boolean) 6895 * @see #isDrawingCacheEnabled() 6896 * 6897 * @attr ref android.R.styleable#View_drawingCacheQuality 6898 */ 6899 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6900 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6901 } 6902 6903 /** 6904 * Returns whether the screen should remain on, corresponding to the current 6905 * value of {@link #KEEP_SCREEN_ON}. 6906 * 6907 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6908 * 6909 * @see #setKeepScreenOn(boolean) 6910 * 6911 * @attr ref android.R.styleable#View_keepScreenOn 6912 */ 6913 public boolean getKeepScreenOn() { 6914 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6915 } 6916 6917 /** 6918 * Controls whether the screen should remain on, modifying the 6919 * value of {@link #KEEP_SCREEN_ON}. 6920 * 6921 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6922 * 6923 * @see #getKeepScreenOn() 6924 * 6925 * @attr ref android.R.styleable#View_keepScreenOn 6926 */ 6927 public void setKeepScreenOn(boolean keepScreenOn) { 6928 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6929 } 6930 6931 /** 6932 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6933 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6934 * 6935 * @attr ref android.R.styleable#View_nextFocusLeft 6936 */ 6937 public int getNextFocusLeftId() { 6938 return mNextFocusLeftId; 6939 } 6940 6941 /** 6942 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6943 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6944 * decide automatically. 6945 * 6946 * @attr ref android.R.styleable#View_nextFocusLeft 6947 */ 6948 public void setNextFocusLeftId(int nextFocusLeftId) { 6949 mNextFocusLeftId = nextFocusLeftId; 6950 } 6951 6952 /** 6953 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6954 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6955 * 6956 * @attr ref android.R.styleable#View_nextFocusRight 6957 */ 6958 public int getNextFocusRightId() { 6959 return mNextFocusRightId; 6960 } 6961 6962 /** 6963 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6964 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6965 * decide automatically. 6966 * 6967 * @attr ref android.R.styleable#View_nextFocusRight 6968 */ 6969 public void setNextFocusRightId(int nextFocusRightId) { 6970 mNextFocusRightId = nextFocusRightId; 6971 } 6972 6973 /** 6974 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6975 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6976 * 6977 * @attr ref android.R.styleable#View_nextFocusUp 6978 */ 6979 public int getNextFocusUpId() { 6980 return mNextFocusUpId; 6981 } 6982 6983 /** 6984 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6985 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6986 * decide automatically. 6987 * 6988 * @attr ref android.R.styleable#View_nextFocusUp 6989 */ 6990 public void setNextFocusUpId(int nextFocusUpId) { 6991 mNextFocusUpId = nextFocusUpId; 6992 } 6993 6994 /** 6995 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6996 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6997 * 6998 * @attr ref android.R.styleable#View_nextFocusDown 6999 */ 7000 public int getNextFocusDownId() { 7001 return mNextFocusDownId; 7002 } 7003 7004 /** 7005 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7006 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7007 * decide automatically. 7008 * 7009 * @attr ref android.R.styleable#View_nextFocusDown 7010 */ 7011 public void setNextFocusDownId(int nextFocusDownId) { 7012 mNextFocusDownId = nextFocusDownId; 7013 } 7014 7015 /** 7016 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7017 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7018 * 7019 * @attr ref android.R.styleable#View_nextFocusForward 7020 */ 7021 public int getNextFocusForwardId() { 7022 return mNextFocusForwardId; 7023 } 7024 7025 /** 7026 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7027 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7028 * decide automatically. 7029 * 7030 * @attr ref android.R.styleable#View_nextFocusForward 7031 */ 7032 public void setNextFocusForwardId(int nextFocusForwardId) { 7033 mNextFocusForwardId = nextFocusForwardId; 7034 } 7035 7036 /** 7037 * Returns the visibility of this view and all of its ancestors 7038 * 7039 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7040 */ 7041 public boolean isShown() { 7042 View current = this; 7043 //noinspection ConstantConditions 7044 do { 7045 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7046 return false; 7047 } 7048 ViewParent parent = current.mParent; 7049 if (parent == null) { 7050 return false; // We are not attached to the view root 7051 } 7052 if (!(parent instanceof View)) { 7053 return true; 7054 } 7055 current = (View) parent; 7056 } while (current != null); 7057 7058 return false; 7059 } 7060 7061 /** 7062 * Called by the view hierarchy when the content insets for a window have 7063 * changed, to allow it to adjust its content to fit within those windows. 7064 * The content insets tell you the space that the status bar, input method, 7065 * and other system windows infringe on the application's window. 7066 * 7067 * <p>You do not normally need to deal with this function, since the default 7068 * window decoration given to applications takes care of applying it to the 7069 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7070 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7071 * and your content can be placed under those system elements. You can then 7072 * use this method within your view hierarchy if you have parts of your UI 7073 * which you would like to ensure are not being covered. 7074 * 7075 * <p>The default implementation of this method simply applies the content 7076 * insets to the view's padding, consuming that content (modifying the 7077 * insets to be 0), and returning true. This behavior is off by default, but can 7078 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7079 * 7080 * <p>This function's traversal down the hierarchy is depth-first. The same content 7081 * insets object is propagated down the hierarchy, so any changes made to it will 7082 * be seen by all following views (including potentially ones above in 7083 * the hierarchy since this is a depth-first traversal). The first view 7084 * that returns true will abort the entire traversal. 7085 * 7086 * <p>The default implementation works well for a situation where it is 7087 * used with a container that covers the entire window, allowing it to 7088 * apply the appropriate insets to its content on all edges. If you need 7089 * a more complicated layout (such as two different views fitting system 7090 * windows, one on the top of the window, and one on the bottom), 7091 * you can override the method and handle the insets however you would like. 7092 * Note that the insets provided by the framework are always relative to the 7093 * far edges of the window, not accounting for the location of the called view 7094 * within that window. (In fact when this method is called you do not yet know 7095 * where the layout will place the view, as it is done before layout happens.) 7096 * 7097 * <p>Note: unlike many View methods, there is no dispatch phase to this 7098 * call. If you are overriding it in a ViewGroup and want to allow the 7099 * call to continue to your children, you must be sure to call the super 7100 * implementation. 7101 * 7102 * <p>Here is a sample layout that makes use of fitting system windows 7103 * to have controls for a video view placed inside of the window decorations 7104 * that it hides and shows. This can be used with code like the second 7105 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7106 * 7107 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7108 * 7109 * @param insets Current content insets of the window. Prior to 7110 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7111 * the insets or else you and Android will be unhappy. 7112 * 7113 * @return {@code true} if this view applied the insets and it should not 7114 * continue propagating further down the hierarchy, {@code false} otherwise. 7115 * @see #getFitsSystemWindows() 7116 * @see #setFitsSystemWindows(boolean) 7117 * @see #setSystemUiVisibility(int) 7118 * 7119 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7120 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7121 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7122 * to implement handling their own insets. 7123 */ 7124 protected boolean fitSystemWindows(Rect insets) { 7125 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7126 if (insets == null) { 7127 // Null insets by definition have already been consumed. 7128 // This call cannot apply insets since there are none to apply, 7129 // so return false. 7130 return false; 7131 } 7132 // If we're not in the process of dispatching the newer apply insets call, 7133 // that means we're not in the compatibility path. Dispatch into the newer 7134 // apply insets path and take things from there. 7135 try { 7136 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7137 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7138 } finally { 7139 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7140 } 7141 } else { 7142 // We're being called from the newer apply insets path. 7143 // Perform the standard fallback behavior. 7144 return fitSystemWindowsInt(insets); 7145 } 7146 } 7147 7148 private boolean fitSystemWindowsInt(Rect insets) { 7149 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7150 mUserPaddingStart = UNDEFINED_PADDING; 7151 mUserPaddingEnd = UNDEFINED_PADDING; 7152 Rect localInsets = sThreadLocal.get(); 7153 if (localInsets == null) { 7154 localInsets = new Rect(); 7155 sThreadLocal.set(localInsets); 7156 } 7157 boolean res = computeFitSystemWindows(insets, localInsets); 7158 mUserPaddingLeftInitial = localInsets.left; 7159 mUserPaddingRightInitial = localInsets.right; 7160 internalSetPadding(localInsets.left, localInsets.top, 7161 localInsets.right, localInsets.bottom); 7162 return res; 7163 } 7164 return false; 7165 } 7166 7167 /** 7168 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7169 * 7170 * <p>This method should be overridden by views that wish to apply a policy different from or 7171 * in addition to the default behavior. Clients that wish to force a view subtree 7172 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7173 * 7174 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7175 * it will be called during dispatch instead of this method. The listener may optionally 7176 * call this method from its own implementation if it wishes to apply the view's default 7177 * insets policy in addition to its own.</p> 7178 * 7179 * <p>Implementations of this method should either return the insets parameter unchanged 7180 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7181 * that this view applied itself. This allows new inset types added in future platform 7182 * versions to pass through existing implementations unchanged without being erroneously 7183 * consumed.</p> 7184 * 7185 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7186 * property is set then the view will consume the system window insets and apply them 7187 * as padding for the view.</p> 7188 * 7189 * @param insets Insets to apply 7190 * @return The supplied insets with any applied insets consumed 7191 */ 7192 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7193 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7194 // We weren't called from within a direct call to fitSystemWindows, 7195 // call into it as a fallback in case we're in a class that overrides it 7196 // and has logic to perform. 7197 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7198 return insets.consumeSystemWindowInsets(); 7199 } 7200 } else { 7201 // We were called from within a direct call to fitSystemWindows. 7202 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7203 return insets.consumeSystemWindowInsets(); 7204 } 7205 } 7206 return insets; 7207 } 7208 7209 /** 7210 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7211 * window insets to this view. The listener's 7212 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7213 * method will be called instead of the view's 7214 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7215 * 7216 * @param listener Listener to set 7217 * 7218 * @see #onApplyWindowInsets(WindowInsets) 7219 */ 7220 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7221 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7222 } 7223 7224 /** 7225 * Request to apply the given window insets to this view or another view in its subtree. 7226 * 7227 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7228 * obscured by window decorations or overlays. This can include the status and navigation bars, 7229 * action bars, input methods and more. New inset categories may be added in the future. 7230 * The method returns the insets provided minus any that were applied by this view or its 7231 * children.</p> 7232 * 7233 * <p>Clients wishing to provide custom behavior should override the 7234 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7235 * {@link OnApplyWindowInsetsListener} via the 7236 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7237 * method.</p> 7238 * 7239 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7240 * </p> 7241 * 7242 * @param insets Insets to apply 7243 * @return The provided insets minus the insets that were consumed 7244 */ 7245 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7246 try { 7247 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7248 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7249 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7250 } else { 7251 return onApplyWindowInsets(insets); 7252 } 7253 } finally { 7254 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7255 } 7256 } 7257 7258 /** 7259 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7260 * only available if the view is attached. 7261 * 7262 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7263 */ 7264 public WindowInsets getRootWindowInsets() { 7265 if (mAttachInfo != null) { 7266 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7267 } 7268 return null; 7269 } 7270 7271 /** 7272 * @hide Compute the insets that should be consumed by this view and the ones 7273 * that should propagate to those under it. 7274 */ 7275 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7276 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7277 || mAttachInfo == null 7278 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7279 && !mAttachInfo.mOverscanRequested)) { 7280 outLocalInsets.set(inoutInsets); 7281 inoutInsets.set(0, 0, 0, 0); 7282 return true; 7283 } else { 7284 // The application wants to take care of fitting system window for 7285 // the content... however we still need to take care of any overscan here. 7286 final Rect overscan = mAttachInfo.mOverscanInsets; 7287 outLocalInsets.set(overscan); 7288 inoutInsets.left -= overscan.left; 7289 inoutInsets.top -= overscan.top; 7290 inoutInsets.right -= overscan.right; 7291 inoutInsets.bottom -= overscan.bottom; 7292 return false; 7293 } 7294 } 7295 7296 /** 7297 * Compute insets that should be consumed by this view and the ones that should propagate 7298 * to those under it. 7299 * 7300 * @param in Insets currently being processed by this View, likely received as a parameter 7301 * to {@link #onApplyWindowInsets(WindowInsets)}. 7302 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7303 * by this view 7304 * @return Insets that should be passed along to views under this one 7305 */ 7306 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7307 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7308 || mAttachInfo == null 7309 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7310 outLocalInsets.set(in.getSystemWindowInsets()); 7311 return in.consumeSystemWindowInsets(); 7312 } else { 7313 outLocalInsets.set(0, 0, 0, 0); 7314 return in; 7315 } 7316 } 7317 7318 /** 7319 * Sets whether or not this view should account for system screen decorations 7320 * such as the status bar and inset its content; that is, controlling whether 7321 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7322 * executed. See that method for more details. 7323 * 7324 * <p>Note that if you are providing your own implementation of 7325 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7326 * flag to true -- your implementation will be overriding the default 7327 * implementation that checks this flag. 7328 * 7329 * @param fitSystemWindows If true, then the default implementation of 7330 * {@link #fitSystemWindows(Rect)} will be executed. 7331 * 7332 * @attr ref android.R.styleable#View_fitsSystemWindows 7333 * @see #getFitsSystemWindows() 7334 * @see #fitSystemWindows(Rect) 7335 * @see #setSystemUiVisibility(int) 7336 */ 7337 public void setFitsSystemWindows(boolean fitSystemWindows) { 7338 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7339 } 7340 7341 /** 7342 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7343 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7344 * will be executed. 7345 * 7346 * @return {@code true} if the default implementation of 7347 * {@link #fitSystemWindows(Rect)} will be executed. 7348 * 7349 * @attr ref android.R.styleable#View_fitsSystemWindows 7350 * @see #setFitsSystemWindows(boolean) 7351 * @see #fitSystemWindows(Rect) 7352 * @see #setSystemUiVisibility(int) 7353 */ 7354 @ViewDebug.ExportedProperty 7355 public boolean getFitsSystemWindows() { 7356 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7357 } 7358 7359 /** @hide */ 7360 public boolean fitsSystemWindows() { 7361 return getFitsSystemWindows(); 7362 } 7363 7364 /** 7365 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7366 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7367 */ 7368 public void requestFitSystemWindows() { 7369 if (mParent != null) { 7370 mParent.requestFitSystemWindows(); 7371 } 7372 } 7373 7374 /** 7375 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7376 */ 7377 public void requestApplyInsets() { 7378 requestFitSystemWindows(); 7379 } 7380 7381 /** 7382 * For use by PhoneWindow to make its own system window fitting optional. 7383 * @hide 7384 */ 7385 public void makeOptionalFitsSystemWindows() { 7386 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 7387 } 7388 7389 /** 7390 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 7391 * treat them as such. 7392 * @hide 7393 */ 7394 public void getOutsets(Rect outOutsetRect) { 7395 if (mAttachInfo != null) { 7396 outOutsetRect.set(mAttachInfo.mOutsets); 7397 } else { 7398 outOutsetRect.setEmpty(); 7399 } 7400 } 7401 7402 /** 7403 * Returns the visibility status for this view. 7404 * 7405 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7406 * @attr ref android.R.styleable#View_visibility 7407 */ 7408 @ViewDebug.ExportedProperty(mapping = { 7409 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 7410 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 7411 @ViewDebug.IntToString(from = GONE, to = "GONE") 7412 }) 7413 @Visibility 7414 public int getVisibility() { 7415 return mViewFlags & VISIBILITY_MASK; 7416 } 7417 7418 /** 7419 * Set the enabled state of this view. 7420 * 7421 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7422 * @attr ref android.R.styleable#View_visibility 7423 */ 7424 @RemotableViewMethod 7425 public void setVisibility(@Visibility int visibility) { 7426 setFlags(visibility, VISIBILITY_MASK); 7427 } 7428 7429 /** 7430 * Returns the enabled status for this view. The interpretation of the 7431 * enabled state varies by subclass. 7432 * 7433 * @return True if this view is enabled, false otherwise. 7434 */ 7435 @ViewDebug.ExportedProperty 7436 public boolean isEnabled() { 7437 return (mViewFlags & ENABLED_MASK) == ENABLED; 7438 } 7439 7440 /** 7441 * Set the enabled state of this view. The interpretation of the enabled 7442 * state varies by subclass. 7443 * 7444 * @param enabled True if this view is enabled, false otherwise. 7445 */ 7446 @RemotableViewMethod 7447 public void setEnabled(boolean enabled) { 7448 if (enabled == isEnabled()) return; 7449 7450 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 7451 7452 /* 7453 * The View most likely has to change its appearance, so refresh 7454 * the drawable state. 7455 */ 7456 refreshDrawableState(); 7457 7458 // Invalidate too, since the default behavior for views is to be 7459 // be drawn at 50% alpha rather than to change the drawable. 7460 invalidate(true); 7461 7462 if (!enabled) { 7463 cancelPendingInputEvents(); 7464 } 7465 } 7466 7467 /** 7468 * Set whether this view can receive the focus. 7469 * 7470 * Setting this to false will also ensure that this view is not focusable 7471 * in touch mode. 7472 * 7473 * @param focusable If true, this view can receive the focus. 7474 * 7475 * @see #setFocusableInTouchMode(boolean) 7476 * @attr ref android.R.styleable#View_focusable 7477 */ 7478 public void setFocusable(boolean focusable) { 7479 if (!focusable) { 7480 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 7481 } 7482 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 7483 } 7484 7485 /** 7486 * Set whether this view can receive focus while in touch mode. 7487 * 7488 * Setting this to true will also ensure that this view is focusable. 7489 * 7490 * @param focusableInTouchMode If true, this view can receive the focus while 7491 * in touch mode. 7492 * 7493 * @see #setFocusable(boolean) 7494 * @attr ref android.R.styleable#View_focusableInTouchMode 7495 */ 7496 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 7497 // Focusable in touch mode should always be set before the focusable flag 7498 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 7499 // which, in touch mode, will not successfully request focus on this view 7500 // because the focusable in touch mode flag is not set 7501 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 7502 if (focusableInTouchMode) { 7503 setFlags(FOCUSABLE, FOCUSABLE_MASK); 7504 } 7505 } 7506 7507 /** 7508 * Set whether this view should have sound effects enabled for events such as 7509 * clicking and touching. 7510 * 7511 * <p>You may wish to disable sound effects for a view if you already play sounds, 7512 * for instance, a dial key that plays dtmf tones. 7513 * 7514 * @param soundEffectsEnabled whether sound effects are enabled for this view. 7515 * @see #isSoundEffectsEnabled() 7516 * @see #playSoundEffect(int) 7517 * @attr ref android.R.styleable#View_soundEffectsEnabled 7518 */ 7519 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 7520 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 7521 } 7522 7523 /** 7524 * @return whether this view should have sound effects enabled for events such as 7525 * clicking and touching. 7526 * 7527 * @see #setSoundEffectsEnabled(boolean) 7528 * @see #playSoundEffect(int) 7529 * @attr ref android.R.styleable#View_soundEffectsEnabled 7530 */ 7531 @ViewDebug.ExportedProperty 7532 public boolean isSoundEffectsEnabled() { 7533 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 7534 } 7535 7536 /** 7537 * Set whether this view should have haptic feedback for events such as 7538 * long presses. 7539 * 7540 * <p>You may wish to disable haptic feedback if your view already controls 7541 * its own haptic feedback. 7542 * 7543 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 7544 * @see #isHapticFeedbackEnabled() 7545 * @see #performHapticFeedback(int) 7546 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 7547 */ 7548 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 7549 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 7550 } 7551 7552 /** 7553 * @return whether this view should have haptic feedback enabled for events 7554 * long presses. 7555 * 7556 * @see #setHapticFeedbackEnabled(boolean) 7557 * @see #performHapticFeedback(int) 7558 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 7559 */ 7560 @ViewDebug.ExportedProperty 7561 public boolean isHapticFeedbackEnabled() { 7562 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 7563 } 7564 7565 /** 7566 * Returns the layout direction for this view. 7567 * 7568 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 7569 * {@link #LAYOUT_DIRECTION_RTL}, 7570 * {@link #LAYOUT_DIRECTION_INHERIT} or 7571 * {@link #LAYOUT_DIRECTION_LOCALE}. 7572 * 7573 * @attr ref android.R.styleable#View_layoutDirection 7574 * 7575 * @hide 7576 */ 7577 @ViewDebug.ExportedProperty(category = "layout", mapping = { 7578 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 7579 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 7580 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 7581 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 7582 }) 7583 @LayoutDir 7584 public int getRawLayoutDirection() { 7585 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 7586 } 7587 7588 /** 7589 * Set the layout direction for this view. This will propagate a reset of layout direction 7590 * resolution to the view's children and resolve layout direction for this view. 7591 * 7592 * @param layoutDirection the layout direction to set. Should be one of: 7593 * 7594 * {@link #LAYOUT_DIRECTION_LTR}, 7595 * {@link #LAYOUT_DIRECTION_RTL}, 7596 * {@link #LAYOUT_DIRECTION_INHERIT}, 7597 * {@link #LAYOUT_DIRECTION_LOCALE}. 7598 * 7599 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 7600 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 7601 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 7602 * 7603 * @attr ref android.R.styleable#View_layoutDirection 7604 */ 7605 @RemotableViewMethod 7606 public void setLayoutDirection(@LayoutDir int layoutDirection) { 7607 if (getRawLayoutDirection() != layoutDirection) { 7608 // Reset the current layout direction and the resolved one 7609 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 7610 resetRtlProperties(); 7611 // Set the new layout direction (filtered) 7612 mPrivateFlags2 |= 7613 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 7614 // We need to resolve all RTL properties as they all depend on layout direction 7615 resolveRtlPropertiesIfNeeded(); 7616 requestLayout(); 7617 invalidate(true); 7618 } 7619 } 7620 7621 /** 7622 * Returns the resolved layout direction for this view. 7623 * 7624 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 7625 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 7626 * 7627 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 7628 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 7629 * 7630 * @attr ref android.R.styleable#View_layoutDirection 7631 */ 7632 @ViewDebug.ExportedProperty(category = "layout", mapping = { 7633 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 7634 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 7635 }) 7636 @ResolvedLayoutDir 7637 public int getLayoutDirection() { 7638 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 7639 if (targetSdkVersion < JELLY_BEAN_MR1) { 7640 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 7641 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 7642 } 7643 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 7644 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 7645 } 7646 7647 /** 7648 * Indicates whether or not this view's layout is right-to-left. This is resolved from 7649 * layout attribute and/or the inherited value from the parent 7650 * 7651 * @return true if the layout is right-to-left. 7652 * 7653 * @hide 7654 */ 7655 @ViewDebug.ExportedProperty(category = "layout") 7656 public boolean isLayoutRtl() { 7657 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 7658 } 7659 7660 /** 7661 * Indicates whether the view is currently tracking transient state that the 7662 * app should not need to concern itself with saving and restoring, but that 7663 * the framework should take special note to preserve when possible. 7664 * 7665 * <p>A view with transient state cannot be trivially rebound from an external 7666 * data source, such as an adapter binding item views in a list. This may be 7667 * because the view is performing an animation, tracking user selection 7668 * of content, or similar.</p> 7669 * 7670 * @return true if the view has transient state 7671 */ 7672 @ViewDebug.ExportedProperty(category = "layout") 7673 public boolean hasTransientState() { 7674 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 7675 } 7676 7677 /** 7678 * Set whether this view is currently tracking transient state that the 7679 * framework should attempt to preserve when possible. This flag is reference counted, 7680 * so every call to setHasTransientState(true) should be paired with a later call 7681 * to setHasTransientState(false). 7682 * 7683 * <p>A view with transient state cannot be trivially rebound from an external 7684 * data source, such as an adapter binding item views in a list. This may be 7685 * because the view is performing an animation, tracking user selection 7686 * of content, or similar.</p> 7687 * 7688 * @param hasTransientState true if this view has transient state 7689 */ 7690 public void setHasTransientState(boolean hasTransientState) { 7691 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 7692 mTransientStateCount - 1; 7693 if (mTransientStateCount < 0) { 7694 mTransientStateCount = 0; 7695 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 7696 "unmatched pair of setHasTransientState calls"); 7697 } else if ((hasTransientState && mTransientStateCount == 1) || 7698 (!hasTransientState && mTransientStateCount == 0)) { 7699 // update flag if we've just incremented up from 0 or decremented down to 0 7700 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 7701 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 7702 if (mParent != null) { 7703 try { 7704 mParent.childHasTransientStateChanged(this, hasTransientState); 7705 } catch (AbstractMethodError e) { 7706 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7707 " does not fully implement ViewParent", e); 7708 } 7709 } 7710 } 7711 } 7712 7713 /** 7714 * Returns true if this view is currently attached to a window. 7715 */ 7716 public boolean isAttachedToWindow() { 7717 return mAttachInfo != null; 7718 } 7719 7720 /** 7721 * Returns true if this view has been through at least one layout since it 7722 * was last attached to or detached from a window. 7723 */ 7724 public boolean isLaidOut() { 7725 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 7726 } 7727 7728 /** 7729 * If this view doesn't do any drawing on its own, set this flag to 7730 * allow further optimizations. By default, this flag is not set on 7731 * View, but could be set on some View subclasses such as ViewGroup. 7732 * 7733 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 7734 * you should clear this flag. 7735 * 7736 * @param willNotDraw whether or not this View draw on its own 7737 */ 7738 public void setWillNotDraw(boolean willNotDraw) { 7739 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 7740 } 7741 7742 /** 7743 * Returns whether or not this View draws on its own. 7744 * 7745 * @return true if this view has nothing to draw, false otherwise 7746 */ 7747 @ViewDebug.ExportedProperty(category = "drawing") 7748 public boolean willNotDraw() { 7749 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 7750 } 7751 7752 /** 7753 * When a View's drawing cache is enabled, drawing is redirected to an 7754 * offscreen bitmap. Some views, like an ImageView, must be able to 7755 * bypass this mechanism if they already draw a single bitmap, to avoid 7756 * unnecessary usage of the memory. 7757 * 7758 * @param willNotCacheDrawing true if this view does not cache its 7759 * drawing, false otherwise 7760 */ 7761 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 7762 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7763 } 7764 7765 /** 7766 * Returns whether or not this View can cache its drawing or not. 7767 * 7768 * @return true if this view does not cache its drawing, false otherwise 7769 */ 7770 @ViewDebug.ExportedProperty(category = "drawing") 7771 public boolean willNotCacheDrawing() { 7772 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7773 } 7774 7775 /** 7776 * Indicates whether this view reacts to click events or not. 7777 * 7778 * @return true if the view is clickable, false otherwise 7779 * 7780 * @see #setClickable(boolean) 7781 * @attr ref android.R.styleable#View_clickable 7782 */ 7783 @ViewDebug.ExportedProperty 7784 public boolean isClickable() { 7785 return (mViewFlags & CLICKABLE) == CLICKABLE; 7786 } 7787 7788 /** 7789 * Enables or disables click events for this view. When a view 7790 * is clickable it will change its state to "pressed" on every click. 7791 * Subclasses should set the view clickable to visually react to 7792 * user's clicks. 7793 * 7794 * @param clickable true to make the view clickable, false otherwise 7795 * 7796 * @see #isClickable() 7797 * @attr ref android.R.styleable#View_clickable 7798 */ 7799 public void setClickable(boolean clickable) { 7800 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7801 } 7802 7803 /** 7804 * Indicates whether this view reacts to long click events or not. 7805 * 7806 * @return true if the view is long clickable, false otherwise 7807 * 7808 * @see #setLongClickable(boolean) 7809 * @attr ref android.R.styleable#View_longClickable 7810 */ 7811 public boolean isLongClickable() { 7812 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7813 } 7814 7815 /** 7816 * Enables or disables long click events for this view. When a view is long 7817 * clickable it reacts to the user holding down the button for a longer 7818 * duration than a tap. This event can either launch the listener or a 7819 * context menu. 7820 * 7821 * @param longClickable true to make the view long clickable, false otherwise 7822 * @see #isLongClickable() 7823 * @attr ref android.R.styleable#View_longClickable 7824 */ 7825 public void setLongClickable(boolean longClickable) { 7826 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7827 } 7828 7829 /** 7830 * Indicates whether this view reacts to context clicks or not. 7831 * 7832 * @return true if the view is context clickable, false otherwise 7833 * @see #setContextClickable(boolean) 7834 * @attr ref android.R.styleable#View_contextClickable 7835 */ 7836 public boolean isContextClickable() { 7837 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 7838 } 7839 7840 /** 7841 * Enables or disables context clicking for this view. This event can launch the listener. 7842 * 7843 * @param contextClickable true to make the view react to a context click, false otherwise 7844 * @see #isContextClickable() 7845 * @attr ref android.R.styleable#View_contextClickable 7846 */ 7847 public void setContextClickable(boolean contextClickable) { 7848 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 7849 } 7850 7851 /** 7852 * Sets the pressed state for this view and provides a touch coordinate for 7853 * animation hinting. 7854 * 7855 * @param pressed Pass true to set the View's internal state to "pressed", 7856 * or false to reverts the View's internal state from a 7857 * previously set "pressed" state. 7858 * @param x The x coordinate of the touch that caused the press 7859 * @param y The y coordinate of the touch that caused the press 7860 */ 7861 private void setPressed(boolean pressed, float x, float y) { 7862 if (pressed) { 7863 drawableHotspotChanged(x, y); 7864 } 7865 7866 setPressed(pressed); 7867 } 7868 7869 /** 7870 * Sets the pressed state for this view. 7871 * 7872 * @see #isClickable() 7873 * @see #setClickable(boolean) 7874 * 7875 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7876 * the View's internal state from a previously set "pressed" state. 7877 */ 7878 public void setPressed(boolean pressed) { 7879 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7880 7881 if (pressed) { 7882 mPrivateFlags |= PFLAG_PRESSED; 7883 } else { 7884 mPrivateFlags &= ~PFLAG_PRESSED; 7885 } 7886 7887 if (needsRefresh) { 7888 refreshDrawableState(); 7889 } 7890 dispatchSetPressed(pressed); 7891 } 7892 7893 /** 7894 * Dispatch setPressed to all of this View's children. 7895 * 7896 * @see #setPressed(boolean) 7897 * 7898 * @param pressed The new pressed state 7899 */ 7900 protected void dispatchSetPressed(boolean pressed) { 7901 } 7902 7903 /** 7904 * Indicates whether the view is currently in pressed state. Unless 7905 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7906 * the pressed state. 7907 * 7908 * @see #setPressed(boolean) 7909 * @see #isClickable() 7910 * @see #setClickable(boolean) 7911 * 7912 * @return true if the view is currently pressed, false otherwise 7913 */ 7914 @ViewDebug.ExportedProperty 7915 public boolean isPressed() { 7916 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7917 } 7918 7919 /** 7920 * @hide 7921 * Indicates whether this view will participate in data collection through 7922 * {@link ViewStructure}. If true, it will not provide any data 7923 * for itself or its children. If false, the normal data collection will be allowed. 7924 * 7925 * @return Returns false if assist data collection is not blocked, else true. 7926 * 7927 * @see #setAssistBlocked(boolean) 7928 * @attr ref android.R.styleable#View_assistBlocked 7929 */ 7930 public boolean isAssistBlocked() { 7931 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 7932 } 7933 7934 /** 7935 * @hide 7936 * Controls whether assist data collection from this view and its children is enabled 7937 * (that is, whether {@link #onProvideStructure} and 7938 * {@link #onProvideVirtualStructure} will be called). The default value is false, 7939 * allowing normal assist collection. Setting this to false will disable assist collection. 7940 * 7941 * @param enabled Set to true to <em>disable</em> assist data collection, or false 7942 * (the default) to allow it. 7943 * 7944 * @see #isAssistBlocked() 7945 * @see #onProvideStructure 7946 * @see #onProvideVirtualStructure 7947 * @attr ref android.R.styleable#View_assistBlocked 7948 */ 7949 public void setAssistBlocked(boolean enabled) { 7950 if (enabled) { 7951 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 7952 } else { 7953 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 7954 } 7955 } 7956 7957 /** 7958 * Indicates whether this view will save its state (that is, 7959 * whether its {@link #onSaveInstanceState} method will be called). 7960 * 7961 * @return Returns true if the view state saving is enabled, else false. 7962 * 7963 * @see #setSaveEnabled(boolean) 7964 * @attr ref android.R.styleable#View_saveEnabled 7965 */ 7966 public boolean isSaveEnabled() { 7967 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7968 } 7969 7970 /** 7971 * Controls whether the saving of this view's state is 7972 * enabled (that is, whether its {@link #onSaveInstanceState} method 7973 * will be called). Note that even if freezing is enabled, the 7974 * view still must have an id assigned to it (via {@link #setId(int)}) 7975 * for its state to be saved. This flag can only disable the 7976 * saving of this view; any child views may still have their state saved. 7977 * 7978 * @param enabled Set to false to <em>disable</em> state saving, or true 7979 * (the default) to allow it. 7980 * 7981 * @see #isSaveEnabled() 7982 * @see #setId(int) 7983 * @see #onSaveInstanceState() 7984 * @attr ref android.R.styleable#View_saveEnabled 7985 */ 7986 public void setSaveEnabled(boolean enabled) { 7987 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7988 } 7989 7990 /** 7991 * Gets whether the framework should discard touches when the view's 7992 * window is obscured by another visible window. 7993 * Refer to the {@link View} security documentation for more details. 7994 * 7995 * @return True if touch filtering is enabled. 7996 * 7997 * @see #setFilterTouchesWhenObscured(boolean) 7998 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7999 */ 8000 @ViewDebug.ExportedProperty 8001 public boolean getFilterTouchesWhenObscured() { 8002 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8003 } 8004 8005 /** 8006 * Sets whether the framework should discard touches when the view's 8007 * window is obscured by another visible window. 8008 * Refer to the {@link View} security documentation for more details. 8009 * 8010 * @param enabled True if touch filtering should be enabled. 8011 * 8012 * @see #getFilterTouchesWhenObscured 8013 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8014 */ 8015 public void setFilterTouchesWhenObscured(boolean enabled) { 8016 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8017 FILTER_TOUCHES_WHEN_OBSCURED); 8018 } 8019 8020 /** 8021 * Indicates whether the entire hierarchy under this view will save its 8022 * state when a state saving traversal occurs from its parent. The default 8023 * is true; if false, these views will not be saved unless 8024 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8025 * 8026 * @return Returns true if the view state saving from parent is enabled, else false. 8027 * 8028 * @see #setSaveFromParentEnabled(boolean) 8029 */ 8030 public boolean isSaveFromParentEnabled() { 8031 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8032 } 8033 8034 /** 8035 * Controls whether the entire hierarchy under this view will save its 8036 * state when a state saving traversal occurs from its parent. The default 8037 * is true; if false, these views will not be saved unless 8038 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8039 * 8040 * @param enabled Set to false to <em>disable</em> state saving, or true 8041 * (the default) to allow it. 8042 * 8043 * @see #isSaveFromParentEnabled() 8044 * @see #setId(int) 8045 * @see #onSaveInstanceState() 8046 */ 8047 public void setSaveFromParentEnabled(boolean enabled) { 8048 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8049 } 8050 8051 8052 /** 8053 * Returns whether this View is able to take focus. 8054 * 8055 * @return True if this view can take focus, or false otherwise. 8056 * @attr ref android.R.styleable#View_focusable 8057 */ 8058 @ViewDebug.ExportedProperty(category = "focus") 8059 public final boolean isFocusable() { 8060 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8061 } 8062 8063 /** 8064 * When a view is focusable, it may not want to take focus when in touch mode. 8065 * For example, a button would like focus when the user is navigating via a D-pad 8066 * so that the user can click on it, but once the user starts touching the screen, 8067 * the button shouldn't take focus 8068 * @return Whether the view is focusable in touch mode. 8069 * @attr ref android.R.styleable#View_focusableInTouchMode 8070 */ 8071 @ViewDebug.ExportedProperty 8072 public final boolean isFocusableInTouchMode() { 8073 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8074 } 8075 8076 /** 8077 * Find the nearest view in the specified direction that can take focus. 8078 * This does not actually give focus to that view. 8079 * 8080 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8081 * 8082 * @return The nearest focusable in the specified direction, or null if none 8083 * can be found. 8084 */ 8085 public View focusSearch(@FocusRealDirection int direction) { 8086 if (mParent != null) { 8087 return mParent.focusSearch(this, direction); 8088 } else { 8089 return null; 8090 } 8091 } 8092 8093 /** 8094 * This method is the last chance for the focused view and its ancestors to 8095 * respond to an arrow key. This is called when the focused view did not 8096 * consume the key internally, nor could the view system find a new view in 8097 * the requested direction to give focus to. 8098 * 8099 * @param focused The currently focused view. 8100 * @param direction The direction focus wants to move. One of FOCUS_UP, 8101 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8102 * @return True if the this view consumed this unhandled move. 8103 */ 8104 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8105 return false; 8106 } 8107 8108 /** 8109 * If a user manually specified the next view id for a particular direction, 8110 * use the root to look up the view. 8111 * @param root The root view of the hierarchy containing this view. 8112 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8113 * or FOCUS_BACKWARD. 8114 * @return The user specified next view, or null if there is none. 8115 */ 8116 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8117 switch (direction) { 8118 case FOCUS_LEFT: 8119 if (mNextFocusLeftId == View.NO_ID) return null; 8120 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8121 case FOCUS_RIGHT: 8122 if (mNextFocusRightId == View.NO_ID) return null; 8123 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8124 case FOCUS_UP: 8125 if (mNextFocusUpId == View.NO_ID) return null; 8126 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8127 case FOCUS_DOWN: 8128 if (mNextFocusDownId == View.NO_ID) return null; 8129 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8130 case FOCUS_FORWARD: 8131 if (mNextFocusForwardId == View.NO_ID) return null; 8132 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8133 case FOCUS_BACKWARD: { 8134 if (mID == View.NO_ID) return null; 8135 final int id = mID; 8136 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8137 @Override 8138 public boolean apply(View t) { 8139 return t.mNextFocusForwardId == id; 8140 } 8141 }); 8142 } 8143 } 8144 return null; 8145 } 8146 8147 private View findViewInsideOutShouldExist(View root, int id) { 8148 if (mMatchIdPredicate == null) { 8149 mMatchIdPredicate = new MatchIdPredicate(); 8150 } 8151 mMatchIdPredicate.mId = id; 8152 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8153 if (result == null) { 8154 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8155 } 8156 return result; 8157 } 8158 8159 /** 8160 * Find and return all focusable views that are descendants of this view, 8161 * possibly including this view if it is focusable itself. 8162 * 8163 * @param direction The direction of the focus 8164 * @return A list of focusable views 8165 */ 8166 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8167 ArrayList<View> result = new ArrayList<View>(24); 8168 addFocusables(result, direction); 8169 return result; 8170 } 8171 8172 /** 8173 * Add any focusable views that are descendants of this view (possibly 8174 * including this view if it is focusable itself) to views. If we are in touch mode, 8175 * only add views that are also focusable in touch mode. 8176 * 8177 * @param views Focusable views found so far 8178 * @param direction The direction of the focus 8179 */ 8180 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8181 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 8182 } 8183 8184 /** 8185 * Adds any focusable views that are descendants of this view (possibly 8186 * including this view if it is focusable itself) to views. This method 8187 * adds all focusable views regardless if we are in touch mode or 8188 * only views focusable in touch mode if we are in touch mode or 8189 * only views that can take accessibility focus if accessibility is enabled 8190 * depending on the focusable mode parameter. 8191 * 8192 * @param views Focusable views found so far or null if all we are interested is 8193 * the number of focusables. 8194 * @param direction The direction of the focus. 8195 * @param focusableMode The type of focusables to be added. 8196 * 8197 * @see #FOCUSABLES_ALL 8198 * @see #FOCUSABLES_TOUCH_MODE 8199 */ 8200 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8201 @FocusableMode int focusableMode) { 8202 if (views == null) { 8203 return; 8204 } 8205 if (!isFocusable()) { 8206 return; 8207 } 8208 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8209 && isInTouchMode() && !isFocusableInTouchMode()) { 8210 return; 8211 } 8212 views.add(this); 8213 } 8214 8215 /** 8216 * Finds the Views that contain given text. The containment is case insensitive. 8217 * The search is performed by either the text that the View renders or the content 8218 * description that describes the view for accessibility purposes and the view does 8219 * not render or both. Clients can specify how the search is to be performed via 8220 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8221 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8222 * 8223 * @param outViews The output list of matching Views. 8224 * @param searched The text to match against. 8225 * 8226 * @see #FIND_VIEWS_WITH_TEXT 8227 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8228 * @see #setContentDescription(CharSequence) 8229 */ 8230 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8231 @FindViewFlags int flags) { 8232 if (getAccessibilityNodeProvider() != null) { 8233 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8234 outViews.add(this); 8235 } 8236 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8237 && (searched != null && searched.length() > 0) 8238 && (mContentDescription != null && mContentDescription.length() > 0)) { 8239 String searchedLowerCase = searched.toString().toLowerCase(); 8240 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8241 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8242 outViews.add(this); 8243 } 8244 } 8245 } 8246 8247 /** 8248 * Find and return all touchable views that are descendants of this view, 8249 * possibly including this view if it is touchable itself. 8250 * 8251 * @return A list of touchable views 8252 */ 8253 public ArrayList<View> getTouchables() { 8254 ArrayList<View> result = new ArrayList<View>(); 8255 addTouchables(result); 8256 return result; 8257 } 8258 8259 /** 8260 * Add any touchable views that are descendants of this view (possibly 8261 * including this view if it is touchable itself) to views. 8262 * 8263 * @param views Touchable views found so far 8264 */ 8265 public void addTouchables(ArrayList<View> views) { 8266 final int viewFlags = mViewFlags; 8267 8268 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8269 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8270 && (viewFlags & ENABLED_MASK) == ENABLED) { 8271 views.add(this); 8272 } 8273 } 8274 8275 /** 8276 * Returns whether this View is accessibility focused. 8277 * 8278 * @return True if this View is accessibility focused. 8279 */ 8280 public boolean isAccessibilityFocused() { 8281 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8282 } 8283 8284 /** 8285 * Call this to try to give accessibility focus to this view. 8286 * 8287 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8288 * returns false or the view is no visible or the view already has accessibility 8289 * focus. 8290 * 8291 * See also {@link #focusSearch(int)}, which is what you call to say that you 8292 * have focus, and you want your parent to look for the next one. 8293 * 8294 * @return Whether this view actually took accessibility focus. 8295 * 8296 * @hide 8297 */ 8298 public boolean requestAccessibilityFocus() { 8299 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8300 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8301 return false; 8302 } 8303 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8304 return false; 8305 } 8306 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8307 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8308 ViewRootImpl viewRootImpl = getViewRootImpl(); 8309 if (viewRootImpl != null) { 8310 viewRootImpl.setAccessibilityFocus(this, null); 8311 } 8312 invalidate(); 8313 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8314 return true; 8315 } 8316 return false; 8317 } 8318 8319 /** 8320 * Call this to try to clear accessibility focus of this view. 8321 * 8322 * See also {@link #focusSearch(int)}, which is what you call to say that you 8323 * have focus, and you want your parent to look for the next one. 8324 * 8325 * @hide 8326 */ 8327 public void clearAccessibilityFocus() { 8328 clearAccessibilityFocusNoCallbacks(); 8329 // Clear the global reference of accessibility focus if this 8330 // view or any of its descendants had accessibility focus. 8331 ViewRootImpl viewRootImpl = getViewRootImpl(); 8332 if (viewRootImpl != null) { 8333 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8334 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8335 viewRootImpl.setAccessibilityFocus(null, null); 8336 } 8337 } 8338 } 8339 8340 private void sendAccessibilityHoverEvent(int eventType) { 8341 // Since we are not delivering to a client accessibility events from not 8342 // important views (unless the clinet request that) we need to fire the 8343 // event from the deepest view exposed to the client. As a consequence if 8344 // the user crosses a not exposed view the client will see enter and exit 8345 // of the exposed predecessor followed by and enter and exit of that same 8346 // predecessor when entering and exiting the not exposed descendant. This 8347 // is fine since the client has a clear idea which view is hovered at the 8348 // price of a couple more events being sent. This is a simple and 8349 // working solution. 8350 View source = this; 8351 while (true) { 8352 if (source.includeForAccessibility()) { 8353 source.sendAccessibilityEvent(eventType); 8354 return; 8355 } 8356 ViewParent parent = source.getParent(); 8357 if (parent instanceof View) { 8358 source = (View) parent; 8359 } else { 8360 return; 8361 } 8362 } 8363 } 8364 8365 /** 8366 * Clears accessibility focus without calling any callback methods 8367 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8368 * is used for clearing accessibility focus when giving this focus to 8369 * another view. 8370 */ 8371 void clearAccessibilityFocusNoCallbacks() { 8372 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8373 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8374 invalidate(); 8375 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8376 } 8377 } 8378 8379 /** 8380 * Call this to try to give focus to a specific view or to one of its 8381 * descendants. 8382 * 8383 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8384 * false), or if it is focusable and it is not focusable in touch mode 8385 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8386 * 8387 * See also {@link #focusSearch(int)}, which is what you call to say that you 8388 * have focus, and you want your parent to look for the next one. 8389 * 8390 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 8391 * {@link #FOCUS_DOWN} and <code>null</code>. 8392 * 8393 * @return Whether this view or one of its descendants actually took focus. 8394 */ 8395 public final boolean requestFocus() { 8396 return requestFocus(View.FOCUS_DOWN); 8397 } 8398 8399 /** 8400 * Call this to try to give focus to a specific view or to one of its 8401 * descendants and give it a hint about what direction focus is heading. 8402 * 8403 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8404 * false), or if it is focusable and it is not focusable in touch mode 8405 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8406 * 8407 * See also {@link #focusSearch(int)}, which is what you call to say that you 8408 * have focus, and you want your parent to look for the next one. 8409 * 8410 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 8411 * <code>null</code> set for the previously focused rectangle. 8412 * 8413 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8414 * @return Whether this view or one of its descendants actually took focus. 8415 */ 8416 public final boolean requestFocus(int direction) { 8417 return requestFocus(direction, null); 8418 } 8419 8420 /** 8421 * Call this to try to give focus to a specific view or to one of its descendants 8422 * and give it hints about the direction and a specific rectangle that the focus 8423 * is coming from. The rectangle can help give larger views a finer grained hint 8424 * about where focus is coming from, and therefore, where to show selection, or 8425 * forward focus change internally. 8426 * 8427 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8428 * false), or if it is focusable and it is not focusable in touch mode 8429 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8430 * 8431 * A View will not take focus if it is not visible. 8432 * 8433 * A View will not take focus if one of its parents has 8434 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 8435 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 8436 * 8437 * See also {@link #focusSearch(int)}, which is what you call to say that you 8438 * have focus, and you want your parent to look for the next one. 8439 * 8440 * You may wish to override this method if your custom {@link View} has an internal 8441 * {@link View} that it wishes to forward the request to. 8442 * 8443 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8444 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 8445 * to give a finer grained hint about where focus is coming from. May be null 8446 * if there is no hint. 8447 * @return Whether this view or one of its descendants actually took focus. 8448 */ 8449 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 8450 return requestFocusNoSearch(direction, previouslyFocusedRect); 8451 } 8452 8453 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 8454 // need to be focusable 8455 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 8456 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8457 return false; 8458 } 8459 8460 // need to be focusable in touch mode if in touch mode 8461 if (isInTouchMode() && 8462 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 8463 return false; 8464 } 8465 8466 // need to not have any parents blocking us 8467 if (hasAncestorThatBlocksDescendantFocus()) { 8468 return false; 8469 } 8470 8471 handleFocusGainInternal(direction, previouslyFocusedRect); 8472 return true; 8473 } 8474 8475 /** 8476 * Call this to try to give focus to a specific view or to one of its descendants. This is a 8477 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 8478 * touch mode to request focus when they are touched. 8479 * 8480 * @return Whether this view or one of its descendants actually took focus. 8481 * 8482 * @see #isInTouchMode() 8483 * 8484 */ 8485 public final boolean requestFocusFromTouch() { 8486 // Leave touch mode if we need to 8487 if (isInTouchMode()) { 8488 ViewRootImpl viewRoot = getViewRootImpl(); 8489 if (viewRoot != null) { 8490 viewRoot.ensureTouchMode(false); 8491 } 8492 } 8493 return requestFocus(View.FOCUS_DOWN); 8494 } 8495 8496 /** 8497 * @return Whether any ancestor of this view blocks descendant focus. 8498 */ 8499 private boolean hasAncestorThatBlocksDescendantFocus() { 8500 final boolean focusableInTouchMode = isFocusableInTouchMode(); 8501 ViewParent ancestor = mParent; 8502 while (ancestor instanceof ViewGroup) { 8503 final ViewGroup vgAncestor = (ViewGroup) ancestor; 8504 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 8505 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 8506 return true; 8507 } else { 8508 ancestor = vgAncestor.getParent(); 8509 } 8510 } 8511 return false; 8512 } 8513 8514 /** 8515 * Gets the mode for determining whether this View is important for accessibility 8516 * which is if it fires accessibility events and if it is reported to 8517 * accessibility services that query the screen. 8518 * 8519 * @return The mode for determining whether a View is important for accessibility. 8520 * 8521 * @attr ref android.R.styleable#View_importantForAccessibility 8522 * 8523 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 8524 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 8525 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 8526 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 8527 */ 8528 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 8529 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 8530 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 8531 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 8532 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 8533 to = "noHideDescendants") 8534 }) 8535 public int getImportantForAccessibility() { 8536 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 8537 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 8538 } 8539 8540 /** 8541 * Sets the live region mode for this view. This indicates to accessibility 8542 * services whether they should automatically notify the user about changes 8543 * to the view's content description or text, or to the content descriptions 8544 * or text of the view's children (where applicable). 8545 * <p> 8546 * For example, in a login screen with a TextView that displays an "incorrect 8547 * password" notification, that view should be marked as a live region with 8548 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 8549 * <p> 8550 * To disable change notifications for this view, use 8551 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 8552 * mode for most views. 8553 * <p> 8554 * To indicate that the user should be notified of changes, use 8555 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 8556 * <p> 8557 * If the view's changes should interrupt ongoing speech and notify the user 8558 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 8559 * 8560 * @param mode The live region mode for this view, one of: 8561 * <ul> 8562 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 8563 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 8564 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 8565 * </ul> 8566 * @attr ref android.R.styleable#View_accessibilityLiveRegion 8567 */ 8568 public void setAccessibilityLiveRegion(int mode) { 8569 if (mode != getAccessibilityLiveRegion()) { 8570 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 8571 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 8572 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 8573 notifyViewAccessibilityStateChangedIfNeeded( 8574 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8575 } 8576 } 8577 8578 /** 8579 * Gets the live region mode for this View. 8580 * 8581 * @return The live region mode for the view. 8582 * 8583 * @attr ref android.R.styleable#View_accessibilityLiveRegion 8584 * 8585 * @see #setAccessibilityLiveRegion(int) 8586 */ 8587 public int getAccessibilityLiveRegion() { 8588 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 8589 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 8590 } 8591 8592 /** 8593 * Sets how to determine whether this view is important for accessibility 8594 * which is if it fires accessibility events and if it is reported to 8595 * accessibility services that query the screen. 8596 * 8597 * @param mode How to determine whether this view is important for accessibility. 8598 * 8599 * @attr ref android.R.styleable#View_importantForAccessibility 8600 * 8601 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 8602 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 8603 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 8604 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 8605 */ 8606 public void setImportantForAccessibility(int mode) { 8607 final int oldMode = getImportantForAccessibility(); 8608 if (mode != oldMode) { 8609 // If we're moving between AUTO and another state, we might not need 8610 // to send a subtree changed notification. We'll store the computed 8611 // importance, since we'll need to check it later to make sure. 8612 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 8613 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 8614 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 8615 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 8616 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 8617 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 8618 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 8619 notifySubtreeAccessibilityStateChangedIfNeeded(); 8620 } else { 8621 notifyViewAccessibilityStateChangedIfNeeded( 8622 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8623 } 8624 } 8625 } 8626 8627 /** 8628 * Computes whether this view should be exposed for accessibility. In 8629 * general, views that are interactive or provide information are exposed 8630 * while views that serve only as containers are hidden. 8631 * <p> 8632 * If an ancestor of this view has importance 8633 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 8634 * returns <code>false</code>. 8635 * <p> 8636 * Otherwise, the value is computed according to the view's 8637 * {@link #getImportantForAccessibility()} value: 8638 * <ol> 8639 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 8640 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 8641 * </code> 8642 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 8643 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 8644 * view satisfies any of the following: 8645 * <ul> 8646 * <li>Is actionable, e.g. {@link #isClickable()}, 8647 * {@link #isLongClickable()}, or {@link #isFocusable()} 8648 * <li>Has an {@link AccessibilityDelegate} 8649 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 8650 * {@link OnKeyListener}, etc. 8651 * <li>Is an accessibility live region, e.g. 8652 * {@link #getAccessibilityLiveRegion()} is not 8653 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 8654 * </ul> 8655 * </ol> 8656 * 8657 * @return Whether the view is exposed for accessibility. 8658 * @see #setImportantForAccessibility(int) 8659 * @see #getImportantForAccessibility() 8660 */ 8661 public boolean isImportantForAccessibility() { 8662 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 8663 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 8664 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 8665 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8666 return false; 8667 } 8668 8669 // Check parent mode to ensure we're not hidden. 8670 ViewParent parent = mParent; 8671 while (parent instanceof View) { 8672 if (((View) parent).getImportantForAccessibility() 8673 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 8674 return false; 8675 } 8676 parent = parent.getParent(); 8677 } 8678 8679 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 8680 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 8681 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 8682 } 8683 8684 /** 8685 * Gets the parent for accessibility purposes. Note that the parent for 8686 * accessibility is not necessary the immediate parent. It is the first 8687 * predecessor that is important for accessibility. 8688 * 8689 * @return The parent for accessibility purposes. 8690 */ 8691 public ViewParent getParentForAccessibility() { 8692 if (mParent instanceof View) { 8693 View parentView = (View) mParent; 8694 if (parentView.includeForAccessibility()) { 8695 return mParent; 8696 } else { 8697 return mParent.getParentForAccessibility(); 8698 } 8699 } 8700 return null; 8701 } 8702 8703 /** 8704 * Adds the children of a given View for accessibility. Since some Views are 8705 * not important for accessibility the children for accessibility are not 8706 * necessarily direct children of the view, rather they are the first level of 8707 * descendants important for accessibility. 8708 * 8709 * @param children The list of children for accessibility. 8710 */ 8711 public void addChildrenForAccessibility(ArrayList<View> children) { 8712 8713 } 8714 8715 /** 8716 * Whether to regard this view for accessibility. A view is regarded for 8717 * accessibility if it is important for accessibility or the querying 8718 * accessibility service has explicitly requested that view not 8719 * important for accessibility are regarded. 8720 * 8721 * @return Whether to regard the view for accessibility. 8722 * 8723 * @hide 8724 */ 8725 public boolean includeForAccessibility() { 8726 if (mAttachInfo != null) { 8727 return (mAttachInfo.mAccessibilityFetchFlags 8728 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 8729 || isImportantForAccessibility(); 8730 } 8731 return false; 8732 } 8733 8734 /** 8735 * Returns whether the View is considered actionable from 8736 * accessibility perspective. Such view are important for 8737 * accessibility. 8738 * 8739 * @return True if the view is actionable for accessibility. 8740 * 8741 * @hide 8742 */ 8743 public boolean isActionableForAccessibility() { 8744 return (isClickable() || isLongClickable() || isFocusable()); 8745 } 8746 8747 /** 8748 * Returns whether the View has registered callbacks which makes it 8749 * important for accessibility. 8750 * 8751 * @return True if the view is actionable for accessibility. 8752 */ 8753 private boolean hasListenersForAccessibility() { 8754 ListenerInfo info = getListenerInfo(); 8755 return mTouchDelegate != null || info.mOnKeyListener != null 8756 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 8757 || info.mOnHoverListener != null || info.mOnDragListener != null; 8758 } 8759 8760 /** 8761 * Notifies that the accessibility state of this view changed. The change 8762 * is local to this view and does not represent structural changes such 8763 * as children and parent. For example, the view became focusable. The 8764 * notification is at at most once every 8765 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8766 * to avoid unnecessary load to the system. Also once a view has a pending 8767 * notification this method is a NOP until the notification has been sent. 8768 * 8769 * @hide 8770 */ 8771 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 8772 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 8773 return; 8774 } 8775 if (mSendViewStateChangedAccessibilityEvent == null) { 8776 mSendViewStateChangedAccessibilityEvent = 8777 new SendViewStateChangedAccessibilityEvent(); 8778 } 8779 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 8780 } 8781 8782 /** 8783 * Notifies that the accessibility state of this view changed. The change 8784 * is *not* local to this view and does represent structural changes such 8785 * as children and parent. For example, the view size changed. The 8786 * notification is at at most once every 8787 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 8788 * to avoid unnecessary load to the system. Also once a view has a pending 8789 * notification this method is a NOP until the notification has been sent. 8790 * 8791 * @hide 8792 */ 8793 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 8794 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 8795 return; 8796 } 8797 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 8798 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8799 if (mParent != null) { 8800 try { 8801 mParent.notifySubtreeAccessibilityStateChanged( 8802 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 8803 } catch (AbstractMethodError e) { 8804 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8805 " does not fully implement ViewParent", e); 8806 } 8807 } 8808 } 8809 } 8810 8811 /** 8812 * Change the visibility of the View without triggering any other changes. This is 8813 * important for transitions, where visibility changes should not adjust focus or 8814 * trigger a new layout. This is only used when the visibility has already been changed 8815 * and we need a transient value during an animation. When the animation completes, 8816 * the original visibility value is always restored. 8817 * 8818 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 8819 * @hide 8820 */ 8821 public void setTransitionVisibility(@Visibility int visibility) { 8822 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 8823 } 8824 8825 /** 8826 * Reset the flag indicating the accessibility state of the subtree rooted 8827 * at this view changed. 8828 */ 8829 void resetSubtreeAccessibilityStateChanged() { 8830 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 8831 } 8832 8833 /** 8834 * Report an accessibility action to this view's parents for delegated processing. 8835 * 8836 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 8837 * call this method to delegate an accessibility action to a supporting parent. If the parent 8838 * returns true from its 8839 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 8840 * method this method will return true to signify that the action was consumed.</p> 8841 * 8842 * <p>This method is useful for implementing nested scrolling child views. If 8843 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 8844 * a custom view implementation may invoke this method to allow a parent to consume the 8845 * scroll first. If this method returns true the custom view should skip its own scrolling 8846 * behavior.</p> 8847 * 8848 * @param action Accessibility action to delegate 8849 * @param arguments Optional action arguments 8850 * @return true if the action was consumed by a parent 8851 */ 8852 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 8853 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 8854 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 8855 return true; 8856 } 8857 } 8858 return false; 8859 } 8860 8861 /** 8862 * Performs the specified accessibility action on the view. For 8863 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 8864 * <p> 8865 * If an {@link AccessibilityDelegate} has been specified via calling 8866 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8867 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8868 * is responsible for handling this call. 8869 * </p> 8870 * 8871 * <p>The default implementation will delegate 8872 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 8873 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 8874 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 8875 * 8876 * @param action The action to perform. 8877 * @param arguments Optional action arguments. 8878 * @return Whether the action was performed. 8879 */ 8880 public boolean performAccessibilityAction(int action, Bundle arguments) { 8881 if (mAccessibilityDelegate != null) { 8882 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8883 } else { 8884 return performAccessibilityActionInternal(action, arguments); 8885 } 8886 } 8887 8888 /** 8889 * @see #performAccessibilityAction(int, Bundle) 8890 * 8891 * Note: Called from the default {@link AccessibilityDelegate}. 8892 * 8893 * @hide 8894 */ 8895 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8896 if (isNestedScrollingEnabled() 8897 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 8898 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 8899 || action == R.id.accessibilityActionScrollUp 8900 || action == R.id.accessibilityActionScrollLeft 8901 || action == R.id.accessibilityActionScrollDown 8902 || action == R.id.accessibilityActionScrollRight)) { 8903 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 8904 return true; 8905 } 8906 } 8907 8908 switch (action) { 8909 case AccessibilityNodeInfo.ACTION_CLICK: { 8910 if (isClickable()) { 8911 performClick(); 8912 return true; 8913 } 8914 } break; 8915 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8916 if (isLongClickable()) { 8917 performLongClick(); 8918 return true; 8919 } 8920 } break; 8921 case AccessibilityNodeInfo.ACTION_FOCUS: { 8922 if (!hasFocus()) { 8923 // Get out of touch mode since accessibility 8924 // wants to move focus around. 8925 getViewRootImpl().ensureTouchMode(false); 8926 return requestFocus(); 8927 } 8928 } break; 8929 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8930 if (hasFocus()) { 8931 clearFocus(); 8932 return !isFocused(); 8933 } 8934 } break; 8935 case AccessibilityNodeInfo.ACTION_SELECT: { 8936 if (!isSelected()) { 8937 setSelected(true); 8938 return isSelected(); 8939 } 8940 } break; 8941 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8942 if (isSelected()) { 8943 setSelected(false); 8944 return !isSelected(); 8945 } 8946 } break; 8947 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8948 if (!isAccessibilityFocused()) { 8949 return requestAccessibilityFocus(); 8950 } 8951 } break; 8952 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8953 if (isAccessibilityFocused()) { 8954 clearAccessibilityFocus(); 8955 return true; 8956 } 8957 } break; 8958 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8959 if (arguments != null) { 8960 final int granularity = arguments.getInt( 8961 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8962 final boolean extendSelection = arguments.getBoolean( 8963 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8964 return traverseAtGranularity(granularity, true, extendSelection); 8965 } 8966 } break; 8967 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8968 if (arguments != null) { 8969 final int granularity = arguments.getInt( 8970 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8971 final boolean extendSelection = arguments.getBoolean( 8972 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8973 return traverseAtGranularity(granularity, false, extendSelection); 8974 } 8975 } break; 8976 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8977 CharSequence text = getIterableTextForAccessibility(); 8978 if (text == null) { 8979 return false; 8980 } 8981 final int start = (arguments != null) ? arguments.getInt( 8982 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8983 final int end = (arguments != null) ? arguments.getInt( 8984 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8985 // Only cursor position can be specified (selection length == 0) 8986 if ((getAccessibilitySelectionStart() != start 8987 || getAccessibilitySelectionEnd() != end) 8988 && (start == end)) { 8989 setAccessibilitySelection(start, end); 8990 notifyViewAccessibilityStateChangedIfNeeded( 8991 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8992 return true; 8993 } 8994 } break; 8995 case R.id.accessibilityActionShowOnScreen: { 8996 if (mAttachInfo != null) { 8997 final Rect r = mAttachInfo.mTmpInvalRect; 8998 getDrawingRect(r); 8999 return requestRectangleOnScreen(r, true); 9000 } 9001 } break; 9002 case R.id.accessibilityActionContextClick: { 9003 if (isContextClickable()) { 9004 performContextClick(); 9005 return true; 9006 } 9007 } break; 9008 } 9009 return false; 9010 } 9011 9012 private boolean traverseAtGranularity(int granularity, boolean forward, 9013 boolean extendSelection) { 9014 CharSequence text = getIterableTextForAccessibility(); 9015 if (text == null || text.length() == 0) { 9016 return false; 9017 } 9018 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9019 if (iterator == null) { 9020 return false; 9021 } 9022 int current = getAccessibilitySelectionEnd(); 9023 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9024 current = forward ? 0 : text.length(); 9025 } 9026 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9027 if (range == null) { 9028 return false; 9029 } 9030 final int segmentStart = range[0]; 9031 final int segmentEnd = range[1]; 9032 int selectionStart; 9033 int selectionEnd; 9034 if (extendSelection && isAccessibilitySelectionExtendable()) { 9035 selectionStart = getAccessibilitySelectionStart(); 9036 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9037 selectionStart = forward ? segmentStart : segmentEnd; 9038 } 9039 selectionEnd = forward ? segmentEnd : segmentStart; 9040 } else { 9041 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9042 } 9043 setAccessibilitySelection(selectionStart, selectionEnd); 9044 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9045 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9046 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9047 return true; 9048 } 9049 9050 /** 9051 * Gets the text reported for accessibility purposes. 9052 * 9053 * @return The accessibility text. 9054 * 9055 * @hide 9056 */ 9057 public CharSequence getIterableTextForAccessibility() { 9058 return getContentDescription(); 9059 } 9060 9061 /** 9062 * Gets whether accessibility selection can be extended. 9063 * 9064 * @return If selection is extensible. 9065 * 9066 * @hide 9067 */ 9068 public boolean isAccessibilitySelectionExtendable() { 9069 return false; 9070 } 9071 9072 /** 9073 * @hide 9074 */ 9075 public int getAccessibilitySelectionStart() { 9076 return mAccessibilityCursorPosition; 9077 } 9078 9079 /** 9080 * @hide 9081 */ 9082 public int getAccessibilitySelectionEnd() { 9083 return getAccessibilitySelectionStart(); 9084 } 9085 9086 /** 9087 * @hide 9088 */ 9089 public void setAccessibilitySelection(int start, int end) { 9090 if (start == end && end == mAccessibilityCursorPosition) { 9091 return; 9092 } 9093 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9094 mAccessibilityCursorPosition = start; 9095 } else { 9096 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9097 } 9098 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9099 } 9100 9101 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9102 int fromIndex, int toIndex) { 9103 if (mParent == null) { 9104 return; 9105 } 9106 AccessibilityEvent event = AccessibilityEvent.obtain( 9107 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9108 onInitializeAccessibilityEvent(event); 9109 onPopulateAccessibilityEvent(event); 9110 event.setFromIndex(fromIndex); 9111 event.setToIndex(toIndex); 9112 event.setAction(action); 9113 event.setMovementGranularity(granularity); 9114 mParent.requestSendAccessibilityEvent(this, event); 9115 } 9116 9117 /** 9118 * @hide 9119 */ 9120 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9121 switch (granularity) { 9122 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9123 CharSequence text = getIterableTextForAccessibility(); 9124 if (text != null && text.length() > 0) { 9125 CharacterTextSegmentIterator iterator = 9126 CharacterTextSegmentIterator.getInstance( 9127 mContext.getResources().getConfiguration().locale); 9128 iterator.initialize(text.toString()); 9129 return iterator; 9130 } 9131 } break; 9132 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9133 CharSequence text = getIterableTextForAccessibility(); 9134 if (text != null && text.length() > 0) { 9135 WordTextSegmentIterator iterator = 9136 WordTextSegmentIterator.getInstance( 9137 mContext.getResources().getConfiguration().locale); 9138 iterator.initialize(text.toString()); 9139 return iterator; 9140 } 9141 } break; 9142 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9143 CharSequence text = getIterableTextForAccessibility(); 9144 if (text != null && text.length() > 0) { 9145 ParagraphTextSegmentIterator iterator = 9146 ParagraphTextSegmentIterator.getInstance(); 9147 iterator.initialize(text.toString()); 9148 return iterator; 9149 } 9150 } break; 9151 } 9152 return null; 9153 } 9154 9155 /** 9156 * @hide 9157 */ 9158 public void dispatchStartTemporaryDetach() { 9159 onStartTemporaryDetach(); 9160 } 9161 9162 /** 9163 * This is called when a container is going to temporarily detach a child, with 9164 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9165 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9166 * {@link #onDetachedFromWindow()} when the container is done. 9167 */ 9168 public void onStartTemporaryDetach() { 9169 removeUnsetPressCallback(); 9170 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9171 } 9172 9173 /** 9174 * @hide 9175 */ 9176 public void dispatchFinishTemporaryDetach() { 9177 onFinishTemporaryDetach(); 9178 } 9179 9180 /** 9181 * Called after {@link #onStartTemporaryDetach} when the container is done 9182 * changing the view. 9183 */ 9184 public void onFinishTemporaryDetach() { 9185 } 9186 9187 /** 9188 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9189 * for this view's window. Returns null if the view is not currently attached 9190 * to the window. Normally you will not need to use this directly, but 9191 * just use the standard high-level event callbacks like 9192 * {@link #onKeyDown(int, KeyEvent)}. 9193 */ 9194 public KeyEvent.DispatcherState getKeyDispatcherState() { 9195 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9196 } 9197 9198 /** 9199 * Dispatch a key event before it is processed by any input method 9200 * associated with the view hierarchy. This can be used to intercept 9201 * key events in special situations before the IME consumes them; a 9202 * typical example would be handling the BACK key to update the application's 9203 * UI instead of allowing the IME to see it and close itself. 9204 * 9205 * @param event The key event to be dispatched. 9206 * @return True if the event was handled, false otherwise. 9207 */ 9208 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9209 return onKeyPreIme(event.getKeyCode(), event); 9210 } 9211 9212 /** 9213 * Dispatch a key event to the next view on the focus path. This path runs 9214 * from the top of the view tree down to the currently focused view. If this 9215 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9216 * the next node down the focus path. This method also fires any key 9217 * listeners. 9218 * 9219 * @param event The key event to be dispatched. 9220 * @return True if the event was handled, false otherwise. 9221 */ 9222 public boolean dispatchKeyEvent(KeyEvent event) { 9223 if (mInputEventConsistencyVerifier != null) { 9224 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9225 } 9226 9227 // Give any attached key listener a first crack at the event. 9228 //noinspection SimplifiableIfStatement 9229 ListenerInfo li = mListenerInfo; 9230 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9231 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9232 return true; 9233 } 9234 9235 if (event.dispatch(this, mAttachInfo != null 9236 ? mAttachInfo.mKeyDispatchState : null, this)) { 9237 return true; 9238 } 9239 9240 if (mInputEventConsistencyVerifier != null) { 9241 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9242 } 9243 return false; 9244 } 9245 9246 /** 9247 * Dispatches a key shortcut event. 9248 * 9249 * @param event The key event to be dispatched. 9250 * @return True if the event was handled by the view, false otherwise. 9251 */ 9252 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9253 return onKeyShortcut(event.getKeyCode(), event); 9254 } 9255 9256 /** 9257 * Pass the touch screen motion event down to the target view, or this 9258 * view if it is the target. 9259 * 9260 * @param event The motion event to be dispatched. 9261 * @return True if the event was handled by the view, false otherwise. 9262 */ 9263 public boolean dispatchTouchEvent(MotionEvent event) { 9264 // If the event should be handled by accessibility focus first. 9265 if (event.isTargetAccessibilityFocus()) { 9266 // We don't have focus or no virtual descendant has it, do not handle the event. 9267 if (!isAccessibilityFocusedViewOrHost()) { 9268 return false; 9269 } 9270 // We have focus and got the event, then use normal event dispatch. 9271 event.setTargetAccessibilityFocus(false); 9272 } 9273 9274 boolean result = false; 9275 9276 if (mInputEventConsistencyVerifier != null) { 9277 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9278 } 9279 9280 final int actionMasked = event.getActionMasked(); 9281 if (actionMasked == MotionEvent.ACTION_DOWN) { 9282 // Defensive cleanup for new gesture 9283 stopNestedScroll(); 9284 } 9285 9286 if (onFilterTouchEventForSecurity(event)) { 9287 //noinspection SimplifiableIfStatement 9288 ListenerInfo li = mListenerInfo; 9289 if (li != null && li.mOnTouchListener != null 9290 && (mViewFlags & ENABLED_MASK) == ENABLED 9291 && li.mOnTouchListener.onTouch(this, event)) { 9292 result = true; 9293 } 9294 9295 if (!result && onTouchEvent(event)) { 9296 result = true; 9297 } 9298 } 9299 9300 if (!result && mInputEventConsistencyVerifier != null) { 9301 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9302 } 9303 9304 // Clean up after nested scrolls if this is the end of a gesture; 9305 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 9306 // of the gesture. 9307 if (actionMasked == MotionEvent.ACTION_UP || 9308 actionMasked == MotionEvent.ACTION_CANCEL || 9309 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 9310 stopNestedScroll(); 9311 } 9312 9313 return result; 9314 } 9315 9316 boolean isAccessibilityFocusedViewOrHost() { 9317 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 9318 .getAccessibilityFocusedHost() == this); 9319 } 9320 9321 /** 9322 * Filter the touch event to apply security policies. 9323 * 9324 * @param event The motion event to be filtered. 9325 * @return True if the event should be dispatched, false if the event should be dropped. 9326 * 9327 * @see #getFilterTouchesWhenObscured 9328 */ 9329 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 9330 //noinspection RedundantIfStatement 9331 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 9332 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 9333 // Window is obscured, drop this touch. 9334 return false; 9335 } 9336 return true; 9337 } 9338 9339 /** 9340 * Pass a trackball motion event down to the focused view. 9341 * 9342 * @param event The motion event to be dispatched. 9343 * @return True if the event was handled by the view, false otherwise. 9344 */ 9345 public boolean dispatchTrackballEvent(MotionEvent event) { 9346 if (mInputEventConsistencyVerifier != null) { 9347 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 9348 } 9349 9350 return onTrackballEvent(event); 9351 } 9352 9353 /** 9354 * Dispatch a generic motion event. 9355 * <p> 9356 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9357 * are delivered to the view under the pointer. All other generic motion events are 9358 * delivered to the focused view. Hover events are handled specially and are delivered 9359 * to {@link #onHoverEvent(MotionEvent)}. 9360 * </p> 9361 * 9362 * @param event The motion event to be dispatched. 9363 * @return True if the event was handled by the view, false otherwise. 9364 */ 9365 public boolean dispatchGenericMotionEvent(MotionEvent event) { 9366 if (mInputEventConsistencyVerifier != null) { 9367 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 9368 } 9369 9370 final int source = event.getSource(); 9371 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 9372 final int action = event.getAction(); 9373 if (action == MotionEvent.ACTION_HOVER_ENTER 9374 || action == MotionEvent.ACTION_HOVER_MOVE 9375 || action == MotionEvent.ACTION_HOVER_EXIT) { 9376 if (dispatchHoverEvent(event)) { 9377 return true; 9378 } 9379 } else if (dispatchGenericPointerEvent(event)) { 9380 return true; 9381 } 9382 } else if (dispatchGenericFocusedEvent(event)) { 9383 return true; 9384 } 9385 9386 if (dispatchGenericMotionEventInternal(event)) { 9387 return true; 9388 } 9389 9390 if (mInputEventConsistencyVerifier != null) { 9391 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9392 } 9393 return false; 9394 } 9395 9396 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 9397 //noinspection SimplifiableIfStatement 9398 ListenerInfo li = mListenerInfo; 9399 if (li != null && li.mOnGenericMotionListener != null 9400 && (mViewFlags & ENABLED_MASK) == ENABLED 9401 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 9402 return true; 9403 } 9404 9405 if (onGenericMotionEvent(event)) { 9406 return true; 9407 } 9408 9409 final int actionButton = event.getActionButton(); 9410 switch (event.getActionMasked()) { 9411 case MotionEvent.ACTION_BUTTON_PRESS: 9412 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 9413 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 9414 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 9415 if (performContextClick()) { 9416 mInContextButtonPress = true; 9417 setPressed(true, event.getX(), event.getY()); 9418 removeTapCallback(); 9419 removeLongPressCallback(); 9420 return true; 9421 } 9422 } 9423 break; 9424 9425 case MotionEvent.ACTION_BUTTON_RELEASE: 9426 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 9427 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 9428 mInContextButtonPress = false; 9429 mIgnoreNextUpEvent = true; 9430 } 9431 break; 9432 } 9433 9434 if (mInputEventConsistencyVerifier != null) { 9435 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9436 } 9437 return false; 9438 } 9439 9440 /** 9441 * Dispatch a hover event. 9442 * <p> 9443 * Do not call this method directly. 9444 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 9445 * </p> 9446 * 9447 * @param event The motion event to be dispatched. 9448 * @return True if the event was handled by the view, false otherwise. 9449 */ 9450 protected boolean dispatchHoverEvent(MotionEvent event) { 9451 ListenerInfo li = mListenerInfo; 9452 //noinspection SimplifiableIfStatement 9453 if (li != null && li.mOnHoverListener != null 9454 && (mViewFlags & ENABLED_MASK) == ENABLED 9455 && li.mOnHoverListener.onHover(this, event)) { 9456 return true; 9457 } 9458 9459 return onHoverEvent(event); 9460 } 9461 9462 /** 9463 * Returns true if the view has a child to which it has recently sent 9464 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 9465 * it does not have a hovered child, then it must be the innermost hovered view. 9466 * @hide 9467 */ 9468 protected boolean hasHoveredChild() { 9469 return false; 9470 } 9471 9472 /** 9473 * Dispatch a generic motion event to the view under the first pointer. 9474 * <p> 9475 * Do not call this method directly. 9476 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 9477 * </p> 9478 * 9479 * @param event The motion event to be dispatched. 9480 * @return True if the event was handled by the view, false otherwise. 9481 */ 9482 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 9483 return false; 9484 } 9485 9486 /** 9487 * Dispatch a generic motion event to the currently focused view. 9488 * <p> 9489 * Do not call this method directly. 9490 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 9491 * </p> 9492 * 9493 * @param event The motion event to be dispatched. 9494 * @return True if the event was handled by the view, false otherwise. 9495 */ 9496 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 9497 return false; 9498 } 9499 9500 /** 9501 * Dispatch a pointer event. 9502 * <p> 9503 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 9504 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 9505 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 9506 * and should not be expected to handle other pointing device features. 9507 * </p> 9508 * 9509 * @param event The motion event to be dispatched. 9510 * @return True if the event was handled by the view, false otherwise. 9511 * @hide 9512 */ 9513 public final boolean dispatchPointerEvent(MotionEvent event) { 9514 if (event.isTouchEvent()) { 9515 return dispatchTouchEvent(event); 9516 } else { 9517 return dispatchGenericMotionEvent(event); 9518 } 9519 } 9520 9521 /** 9522 * Called when the window containing this view gains or loses window focus. 9523 * ViewGroups should override to route to their children. 9524 * 9525 * @param hasFocus True if the window containing this view now has focus, 9526 * false otherwise. 9527 */ 9528 public void dispatchWindowFocusChanged(boolean hasFocus) { 9529 onWindowFocusChanged(hasFocus); 9530 } 9531 9532 /** 9533 * Called when the window containing this view gains or loses focus. Note 9534 * that this is separate from view focus: to receive key events, both 9535 * your view and its window must have focus. If a window is displayed 9536 * on top of yours that takes input focus, then your own window will lose 9537 * focus but the view focus will remain unchanged. 9538 * 9539 * @param hasWindowFocus True if the window containing this view now has 9540 * focus, false otherwise. 9541 */ 9542 public void onWindowFocusChanged(boolean hasWindowFocus) { 9543 InputMethodManager imm = InputMethodManager.peekInstance(); 9544 if (!hasWindowFocus) { 9545 if (isPressed()) { 9546 setPressed(false); 9547 } 9548 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 9549 imm.focusOut(this); 9550 } 9551 removeLongPressCallback(); 9552 removeTapCallback(); 9553 onFocusLost(); 9554 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 9555 imm.focusIn(this); 9556 } 9557 refreshDrawableState(); 9558 } 9559 9560 /** 9561 * Returns true if this view is in a window that currently has window focus. 9562 * Note that this is not the same as the view itself having focus. 9563 * 9564 * @return True if this view is in a window that currently has window focus. 9565 */ 9566 public boolean hasWindowFocus() { 9567 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 9568 } 9569 9570 /** 9571 * Dispatch a view visibility change down the view hierarchy. 9572 * ViewGroups should override to route to their children. 9573 * @param changedView The view whose visibility changed. Could be 'this' or 9574 * an ancestor view. 9575 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 9576 * {@link #INVISIBLE} or {@link #GONE}. 9577 */ 9578 protected void dispatchVisibilityChanged(@NonNull View changedView, 9579 @Visibility int visibility) { 9580 onVisibilityChanged(changedView, visibility); 9581 } 9582 9583 /** 9584 * Called when the visibility of the view or an ancestor of the view has 9585 * changed. 9586 * 9587 * @param changedView The view whose visibility changed. May be 9588 * {@code this} or an ancestor view. 9589 * @param visibility The new visibility, one of {@link #VISIBLE}, 9590 * {@link #INVISIBLE} or {@link #GONE}. 9591 */ 9592 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 9593 final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE; 9594 if (visible && mAttachInfo != null) { 9595 initialAwakenScrollBars(); 9596 } 9597 9598 final Drawable dr = mBackground; 9599 if (dr != null && visible != dr.isVisible()) { 9600 dr.setVisible(visible, false); 9601 } 9602 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 9603 if (fg != null && visible != fg.isVisible()) { 9604 fg.setVisible(visible, false); 9605 } 9606 } 9607 9608 /** 9609 * Dispatch a hint about whether this view is displayed. For instance, when 9610 * a View moves out of the screen, it might receives a display hint indicating 9611 * the view is not displayed. Applications should not <em>rely</em> on this hint 9612 * as there is no guarantee that they will receive one. 9613 * 9614 * @param hint A hint about whether or not this view is displayed: 9615 * {@link #VISIBLE} or {@link #INVISIBLE}. 9616 */ 9617 public void dispatchDisplayHint(@Visibility int hint) { 9618 onDisplayHint(hint); 9619 } 9620 9621 /** 9622 * Gives this view a hint about whether is displayed or not. For instance, when 9623 * a View moves out of the screen, it might receives a display hint indicating 9624 * the view is not displayed. Applications should not <em>rely</em> on this hint 9625 * as there is no guarantee that they will receive one. 9626 * 9627 * @param hint A hint about whether or not this view is displayed: 9628 * {@link #VISIBLE} or {@link #INVISIBLE}. 9629 */ 9630 protected void onDisplayHint(@Visibility int hint) { 9631 } 9632 9633 /** 9634 * Dispatch a window visibility change down the view hierarchy. 9635 * ViewGroups should override to route to their children. 9636 * 9637 * @param visibility The new visibility of the window. 9638 * 9639 * @see #onWindowVisibilityChanged(int) 9640 */ 9641 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 9642 onWindowVisibilityChanged(visibility); 9643 } 9644 9645 /** 9646 * Called when the window containing has change its visibility 9647 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 9648 * that this tells you whether or not your window is being made visible 9649 * to the window manager; this does <em>not</em> tell you whether or not 9650 * your window is obscured by other windows on the screen, even if it 9651 * is itself visible. 9652 * 9653 * @param visibility The new visibility of the window. 9654 */ 9655 protected void onWindowVisibilityChanged(@Visibility int visibility) { 9656 if (visibility == VISIBLE) { 9657 initialAwakenScrollBars(); 9658 } 9659 } 9660 9661 /** 9662 * Returns the current visibility of the window this view is attached to 9663 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 9664 * 9665 * @return Returns the current visibility of the view's window. 9666 */ 9667 @Visibility 9668 public int getWindowVisibility() { 9669 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 9670 } 9671 9672 /** 9673 * Retrieve the overall visible display size in which the window this view is 9674 * attached to has been positioned in. This takes into account screen 9675 * decorations above the window, for both cases where the window itself 9676 * is being position inside of them or the window is being placed under 9677 * then and covered insets are used for the window to position its content 9678 * inside. In effect, this tells you the available area where content can 9679 * be placed and remain visible to users. 9680 * 9681 * <p>This function requires an IPC back to the window manager to retrieve 9682 * the requested information, so should not be used in performance critical 9683 * code like drawing. 9684 * 9685 * @param outRect Filled in with the visible display frame. If the view 9686 * is not attached to a window, this is simply the raw display size. 9687 */ 9688 public void getWindowVisibleDisplayFrame(Rect outRect) { 9689 if (mAttachInfo != null) { 9690 try { 9691 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 9692 } catch (RemoteException e) { 9693 return; 9694 } 9695 // XXX This is really broken, and probably all needs to be done 9696 // in the window manager, and we need to know more about whether 9697 // we want the area behind or in front of the IME. 9698 final Rect insets = mAttachInfo.mVisibleInsets; 9699 outRect.left += insets.left; 9700 outRect.top += insets.top; 9701 outRect.right -= insets.right; 9702 outRect.bottom -= insets.bottom; 9703 return; 9704 } 9705 // The view is not attached to a display so we don't have a context. 9706 // Make a best guess about the display size. 9707 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 9708 d.getRectSize(outRect); 9709 } 9710 9711 /** 9712 * Dispatch a notification about a resource configuration change down 9713 * the view hierarchy. 9714 * ViewGroups should override to route to their children. 9715 * 9716 * @param newConfig The new resource configuration. 9717 * 9718 * @see #onConfigurationChanged(android.content.res.Configuration) 9719 */ 9720 public void dispatchConfigurationChanged(Configuration newConfig) { 9721 onConfigurationChanged(newConfig); 9722 } 9723 9724 /** 9725 * Called when the current configuration of the resources being used 9726 * by the application have changed. You can use this to decide when 9727 * to reload resources that can changed based on orientation and other 9728 * configuration characteristics. You only need to use this if you are 9729 * not relying on the normal {@link android.app.Activity} mechanism of 9730 * recreating the activity instance upon a configuration change. 9731 * 9732 * @param newConfig The new resource configuration. 9733 */ 9734 protected void onConfigurationChanged(Configuration newConfig) { 9735 } 9736 9737 /** 9738 * Private function to aggregate all per-view attributes in to the view 9739 * root. 9740 */ 9741 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 9742 performCollectViewAttributes(attachInfo, visibility); 9743 } 9744 9745 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 9746 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 9747 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 9748 attachInfo.mKeepScreenOn = true; 9749 } 9750 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 9751 ListenerInfo li = mListenerInfo; 9752 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 9753 attachInfo.mHasSystemUiListeners = true; 9754 } 9755 } 9756 } 9757 9758 void needGlobalAttributesUpdate(boolean force) { 9759 final AttachInfo ai = mAttachInfo; 9760 if (ai != null && !ai.mRecomputeGlobalAttributes) { 9761 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 9762 || ai.mHasSystemUiListeners) { 9763 ai.mRecomputeGlobalAttributes = true; 9764 } 9765 } 9766 } 9767 9768 /** 9769 * Returns whether the device is currently in touch mode. Touch mode is entered 9770 * once the user begins interacting with the device by touch, and affects various 9771 * things like whether focus is always visible to the user. 9772 * 9773 * @return Whether the device is in touch mode. 9774 */ 9775 @ViewDebug.ExportedProperty 9776 public boolean isInTouchMode() { 9777 if (mAttachInfo != null) { 9778 return mAttachInfo.mInTouchMode; 9779 } else { 9780 return ViewRootImpl.isInTouchMode(); 9781 } 9782 } 9783 9784 /** 9785 * Returns the context the view is running in, through which it can 9786 * access the current theme, resources, etc. 9787 * 9788 * @return The view's Context. 9789 */ 9790 @ViewDebug.CapturedViewProperty 9791 public final Context getContext() { 9792 return mContext; 9793 } 9794 9795 /** 9796 * Handle a key event before it is processed by any input method 9797 * associated with the view hierarchy. This can be used to intercept 9798 * key events in special situations before the IME consumes them; a 9799 * typical example would be handling the BACK key to update the application's 9800 * UI instead of allowing the IME to see it and close itself. 9801 * 9802 * @param keyCode The value in event.getKeyCode(). 9803 * @param event Description of the key event. 9804 * @return If you handled the event, return true. If you want to allow the 9805 * event to be handled by the next receiver, return false. 9806 */ 9807 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 9808 return false; 9809 } 9810 9811 /** 9812 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 9813 * KeyEvent.Callback.onKeyDown()}: perform press of the view 9814 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 9815 * is released, if the view is enabled and clickable. 9816 * 9817 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9818 * although some may elect to do so in some situations. Do not rely on this to 9819 * catch software key presses. 9820 * 9821 * @param keyCode A key code that represents the button pressed, from 9822 * {@link android.view.KeyEvent}. 9823 * @param event The KeyEvent object that defines the button action. 9824 */ 9825 public boolean onKeyDown(int keyCode, KeyEvent event) { 9826 boolean result = false; 9827 9828 if (KeyEvent.isConfirmKey(keyCode)) { 9829 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9830 return true; 9831 } 9832 // Long clickable items don't necessarily have to be clickable 9833 if (((mViewFlags & CLICKABLE) == CLICKABLE || 9834 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 9835 (event.getRepeatCount() == 0)) { 9836 setPressed(true); 9837 checkForLongClick(0); 9838 return true; 9839 } 9840 } 9841 return result; 9842 } 9843 9844 /** 9845 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 9846 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 9847 * the event). 9848 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9849 * although some may elect to do so in some situations. Do not rely on this to 9850 * catch software key presses. 9851 */ 9852 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 9853 return false; 9854 } 9855 9856 /** 9857 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 9858 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 9859 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 9860 * {@link KeyEvent#KEYCODE_ENTER} is released. 9861 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9862 * although some may elect to do so in some situations. Do not rely on this to 9863 * catch software key presses. 9864 * 9865 * @param keyCode A key code that represents the button pressed, from 9866 * {@link android.view.KeyEvent}. 9867 * @param event The KeyEvent object that defines the button action. 9868 */ 9869 public boolean onKeyUp(int keyCode, KeyEvent event) { 9870 if (KeyEvent.isConfirmKey(keyCode)) { 9871 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 9872 return true; 9873 } 9874 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 9875 setPressed(false); 9876 9877 if (!mHasPerformedLongPress) { 9878 // This is a tap, so remove the longpress check 9879 removeLongPressCallback(); 9880 return performClick(); 9881 } 9882 } 9883 } 9884 return false; 9885 } 9886 9887 /** 9888 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 9889 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 9890 * the event). 9891 * <p>Key presses in software keyboards will generally NOT trigger this listener, 9892 * although some may elect to do so in some situations. Do not rely on this to 9893 * catch software key presses. 9894 * 9895 * @param keyCode A key code that represents the button pressed, from 9896 * {@link android.view.KeyEvent}. 9897 * @param repeatCount The number of times the action was made. 9898 * @param event The KeyEvent object that defines the button action. 9899 */ 9900 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 9901 return false; 9902 } 9903 9904 /** 9905 * Called on the focused view when a key shortcut event is not handled. 9906 * Override this method to implement local key shortcuts for the View. 9907 * Key shortcuts can also be implemented by setting the 9908 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 9909 * 9910 * @param keyCode The value in event.getKeyCode(). 9911 * @param event Description of the key event. 9912 * @return If you handled the event, return true. If you want to allow the 9913 * event to be handled by the next receiver, return false. 9914 */ 9915 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 9916 return false; 9917 } 9918 9919 /** 9920 * Check whether the called view is a text editor, in which case it 9921 * would make sense to automatically display a soft input window for 9922 * it. Subclasses should override this if they implement 9923 * {@link #onCreateInputConnection(EditorInfo)} to return true if 9924 * a call on that method would return a non-null InputConnection, and 9925 * they are really a first-class editor that the user would normally 9926 * start typing on when the go into a window containing your view. 9927 * 9928 * <p>The default implementation always returns false. This does 9929 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 9930 * will not be called or the user can not otherwise perform edits on your 9931 * view; it is just a hint to the system that this is not the primary 9932 * purpose of this view. 9933 * 9934 * @return Returns true if this view is a text editor, else false. 9935 */ 9936 public boolean onCheckIsTextEditor() { 9937 return false; 9938 } 9939 9940 /** 9941 * Create a new InputConnection for an InputMethod to interact 9942 * with the view. The default implementation returns null, since it doesn't 9943 * support input methods. You can override this to implement such support. 9944 * This is only needed for views that take focus and text input. 9945 * 9946 * <p>When implementing this, you probably also want to implement 9947 * {@link #onCheckIsTextEditor()} to indicate you will return a 9948 * non-null InputConnection.</p> 9949 * 9950 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9951 * object correctly and in its entirety, so that the connected IME can rely 9952 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9953 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9954 * must be filled in with the correct cursor position for IMEs to work correctly 9955 * with your application.</p> 9956 * 9957 * @param outAttrs Fill in with attribute information about the connection. 9958 */ 9959 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9960 return null; 9961 } 9962 9963 /** 9964 * Called by the {@link android.view.inputmethod.InputMethodManager} 9965 * when a view who is not the current 9966 * input connection target is trying to make a call on the manager. The 9967 * default implementation returns false; you can override this to return 9968 * true for certain views if you are performing InputConnection proxying 9969 * to them. 9970 * @param view The View that is making the InputMethodManager call. 9971 * @return Return true to allow the call, false to reject. 9972 */ 9973 public boolean checkInputConnectionProxy(View view) { 9974 return false; 9975 } 9976 9977 /** 9978 * Show the context menu for this view. It is not safe to hold on to the 9979 * menu after returning from this method. 9980 * 9981 * You should normally not overload this method. Overload 9982 * {@link #onCreateContextMenu(ContextMenu)} or define an 9983 * {@link OnCreateContextMenuListener} to add items to the context menu. 9984 * 9985 * @param menu The context menu to populate 9986 */ 9987 public void createContextMenu(ContextMenu menu) { 9988 ContextMenuInfo menuInfo = getContextMenuInfo(); 9989 9990 // Sets the current menu info so all items added to menu will have 9991 // my extra info set. 9992 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9993 9994 onCreateContextMenu(menu); 9995 ListenerInfo li = mListenerInfo; 9996 if (li != null && li.mOnCreateContextMenuListener != null) { 9997 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9998 } 9999 10000 // Clear the extra information so subsequent items that aren't mine don't 10001 // have my extra info. 10002 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10003 10004 if (mParent != null) { 10005 mParent.createContextMenu(menu); 10006 } 10007 } 10008 10009 /** 10010 * Views should implement this if they have extra information to associate 10011 * with the context menu. The return result is supplied as a parameter to 10012 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10013 * callback. 10014 * 10015 * @return Extra information about the item for which the context menu 10016 * should be shown. This information will vary across different 10017 * subclasses of View. 10018 */ 10019 protected ContextMenuInfo getContextMenuInfo() { 10020 return null; 10021 } 10022 10023 /** 10024 * Views should implement this if the view itself is going to add items to 10025 * the context menu. 10026 * 10027 * @param menu the context menu to populate 10028 */ 10029 protected void onCreateContextMenu(ContextMenu menu) { 10030 } 10031 10032 /** 10033 * Implement this method to handle trackball motion events. The 10034 * <em>relative</em> movement of the trackball since the last event 10035 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10036 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10037 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10038 * they will often be fractional values, representing the more fine-grained 10039 * movement information available from a trackball). 10040 * 10041 * @param event The motion event. 10042 * @return True if the event was handled, false otherwise. 10043 */ 10044 public boolean onTrackballEvent(MotionEvent event) { 10045 return false; 10046 } 10047 10048 /** 10049 * Implement this method to handle generic motion events. 10050 * <p> 10051 * Generic motion events describe joystick movements, mouse hovers, track pad 10052 * touches, scroll wheel movements and other input events. The 10053 * {@link MotionEvent#getSource() source} of the motion event specifies 10054 * the class of input that was received. Implementations of this method 10055 * must examine the bits in the source before processing the event. 10056 * The following code example shows how this is done. 10057 * </p><p> 10058 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10059 * are delivered to the view under the pointer. All other generic motion events are 10060 * delivered to the focused view. 10061 * </p> 10062 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10063 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10064 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10065 * // process the joystick movement... 10066 * return true; 10067 * } 10068 * } 10069 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10070 * switch (event.getAction()) { 10071 * case MotionEvent.ACTION_HOVER_MOVE: 10072 * // process the mouse hover movement... 10073 * return true; 10074 * case MotionEvent.ACTION_SCROLL: 10075 * // process the scroll wheel movement... 10076 * return true; 10077 * } 10078 * } 10079 * return super.onGenericMotionEvent(event); 10080 * }</pre> 10081 * 10082 * @param event The generic motion event being processed. 10083 * @return True if the event was handled, false otherwise. 10084 */ 10085 public boolean onGenericMotionEvent(MotionEvent event) { 10086 return false; 10087 } 10088 10089 /** 10090 * Implement this method to handle hover events. 10091 * <p> 10092 * This method is called whenever a pointer is hovering into, over, or out of the 10093 * bounds of a view and the view is not currently being touched. 10094 * Hover events are represented as pointer events with action 10095 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10096 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10097 * </p> 10098 * <ul> 10099 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10100 * when the pointer enters the bounds of the view.</li> 10101 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10102 * when the pointer has already entered the bounds of the view and has moved.</li> 10103 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10104 * when the pointer has exited the bounds of the view or when the pointer is 10105 * about to go down due to a button click, tap, or similar user action that 10106 * causes the view to be touched.</li> 10107 * </ul> 10108 * <p> 10109 * The view should implement this method to return true to indicate that it is 10110 * handling the hover event, such as by changing its drawable state. 10111 * </p><p> 10112 * The default implementation calls {@link #setHovered} to update the hovered state 10113 * of the view when a hover enter or hover exit event is received, if the view 10114 * is enabled and is clickable. The default implementation also sends hover 10115 * accessibility events. 10116 * </p> 10117 * 10118 * @param event The motion event that describes the hover. 10119 * @return True if the view handled the hover event. 10120 * 10121 * @see #isHovered 10122 * @see #setHovered 10123 * @see #onHoverChanged 10124 */ 10125 public boolean onHoverEvent(MotionEvent event) { 10126 // The root view may receive hover (or touch) events that are outside the bounds of 10127 // the window. This code ensures that we only send accessibility events for 10128 // hovers that are actually within the bounds of the root view. 10129 final int action = event.getActionMasked(); 10130 if (!mSendingHoverAccessibilityEvents) { 10131 if ((action == MotionEvent.ACTION_HOVER_ENTER 10132 || action == MotionEvent.ACTION_HOVER_MOVE) 10133 && !hasHoveredChild() 10134 && pointInView(event.getX(), event.getY())) { 10135 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10136 mSendingHoverAccessibilityEvents = true; 10137 } 10138 } else { 10139 if (action == MotionEvent.ACTION_HOVER_EXIT 10140 || (action == MotionEvent.ACTION_MOVE 10141 && !pointInView(event.getX(), event.getY()))) { 10142 mSendingHoverAccessibilityEvents = false; 10143 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10144 } 10145 } 10146 10147 if (isHoverable()) { 10148 switch (action) { 10149 case MotionEvent.ACTION_HOVER_ENTER: 10150 setHovered(true); 10151 break; 10152 case MotionEvent.ACTION_HOVER_EXIT: 10153 setHovered(false); 10154 break; 10155 } 10156 10157 // Dispatch the event to onGenericMotionEvent before returning true. 10158 // This is to provide compatibility with existing applications that 10159 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10160 // break because of the new default handling for hoverable views 10161 // in onHoverEvent. 10162 // Note that onGenericMotionEvent will be called by default when 10163 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10164 dispatchGenericMotionEventInternal(event); 10165 // The event was already handled by calling setHovered(), so always 10166 // return true. 10167 return true; 10168 } 10169 10170 return false; 10171 } 10172 10173 /** 10174 * Returns true if the view should handle {@link #onHoverEvent} 10175 * by calling {@link #setHovered} to change its hovered state. 10176 * 10177 * @return True if the view is hoverable. 10178 */ 10179 private boolean isHoverable() { 10180 final int viewFlags = mViewFlags; 10181 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10182 return false; 10183 } 10184 10185 return (viewFlags & CLICKABLE) == CLICKABLE 10186 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10187 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10188 } 10189 10190 /** 10191 * Returns true if the view is currently hovered. 10192 * 10193 * @return True if the view is currently hovered. 10194 * 10195 * @see #setHovered 10196 * @see #onHoverChanged 10197 */ 10198 @ViewDebug.ExportedProperty 10199 public boolean isHovered() { 10200 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10201 } 10202 10203 /** 10204 * Sets whether the view is currently hovered. 10205 * <p> 10206 * Calling this method also changes the drawable state of the view. This 10207 * enables the view to react to hover by using different drawable resources 10208 * to change its appearance. 10209 * </p><p> 10210 * The {@link #onHoverChanged} method is called when the hovered state changes. 10211 * </p> 10212 * 10213 * @param hovered True if the view is hovered. 10214 * 10215 * @see #isHovered 10216 * @see #onHoverChanged 10217 */ 10218 public void setHovered(boolean hovered) { 10219 if (hovered) { 10220 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10221 mPrivateFlags |= PFLAG_HOVERED; 10222 refreshDrawableState(); 10223 onHoverChanged(true); 10224 } 10225 } else { 10226 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10227 mPrivateFlags &= ~PFLAG_HOVERED; 10228 refreshDrawableState(); 10229 onHoverChanged(false); 10230 } 10231 } 10232 } 10233 10234 /** 10235 * Implement this method to handle hover state changes. 10236 * <p> 10237 * This method is called whenever the hover state changes as a result of a 10238 * call to {@link #setHovered}. 10239 * </p> 10240 * 10241 * @param hovered The current hover state, as returned by {@link #isHovered}. 10242 * 10243 * @see #isHovered 10244 * @see #setHovered 10245 */ 10246 public void onHoverChanged(boolean hovered) { 10247 } 10248 10249 /** 10250 * Implement this method to handle touch screen motion events. 10251 * <p> 10252 * If this method is used to detect click actions, it is recommended that 10253 * the actions be performed by implementing and calling 10254 * {@link #performClick()}. This will ensure consistent system behavior, 10255 * including: 10256 * <ul> 10257 * <li>obeying click sound preferences 10258 * <li>dispatching OnClickListener calls 10259 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 10260 * accessibility features are enabled 10261 * </ul> 10262 * 10263 * @param event The motion event. 10264 * @return True if the event was handled, false otherwise. 10265 */ 10266 public boolean onTouchEvent(MotionEvent event) { 10267 final float x = event.getX(); 10268 final float y = event.getY(); 10269 final int viewFlags = mViewFlags; 10270 final int action = event.getAction(); 10271 10272 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10273 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 10274 setPressed(false); 10275 } 10276 // A disabled view that is clickable still consumes the touch 10277 // events, it just doesn't respond to them. 10278 return (((viewFlags & CLICKABLE) == CLICKABLE 10279 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10280 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 10281 } 10282 10283 if (mTouchDelegate != null) { 10284 if (mTouchDelegate.onTouchEvent(event)) { 10285 return true; 10286 } 10287 } 10288 10289 if (((viewFlags & CLICKABLE) == CLICKABLE || 10290 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 10291 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 10292 switch (action) { 10293 case MotionEvent.ACTION_UP: 10294 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 10295 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 10296 // take focus if we don't have it already and we should in 10297 // touch mode. 10298 boolean focusTaken = false; 10299 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 10300 focusTaken = requestFocus(); 10301 } 10302 10303 if (prepressed) { 10304 // The button is being released before we actually 10305 // showed it as pressed. Make it show the pressed 10306 // state now (before scheduling the click) to ensure 10307 // the user sees it. 10308 setPressed(true, x, y); 10309 } 10310 10311 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 10312 // This is a tap, so remove the longpress check 10313 removeLongPressCallback(); 10314 10315 // Only perform take click actions if we were in the pressed state 10316 if (!focusTaken) { 10317 // Use a Runnable and post this rather than calling 10318 // performClick directly. This lets other visual state 10319 // of the view update before click actions start. 10320 if (mPerformClick == null) { 10321 mPerformClick = new PerformClick(); 10322 } 10323 if (!post(mPerformClick)) { 10324 performClick(); 10325 } 10326 } 10327 } 10328 10329 if (mUnsetPressedState == null) { 10330 mUnsetPressedState = new UnsetPressedState(); 10331 } 10332 10333 if (prepressed) { 10334 postDelayed(mUnsetPressedState, 10335 ViewConfiguration.getPressedStateDuration()); 10336 } else if (!post(mUnsetPressedState)) { 10337 // If the post failed, unpress right now 10338 mUnsetPressedState.run(); 10339 } 10340 10341 removeTapCallback(); 10342 } 10343 mIgnoreNextUpEvent = false; 10344 break; 10345 10346 case MotionEvent.ACTION_DOWN: 10347 mHasPerformedLongPress = false; 10348 10349 if (performButtonActionOnTouchDown(event)) { 10350 break; 10351 } 10352 10353 // Walk up the hierarchy to determine if we're inside a scrolling container. 10354 boolean isInScrollingContainer = isInScrollingContainer(); 10355 10356 // For views inside a scrolling container, delay the pressed feedback for 10357 // a short period in case this is a scroll. 10358 if (isInScrollingContainer) { 10359 mPrivateFlags |= PFLAG_PREPRESSED; 10360 if (mPendingCheckForTap == null) { 10361 mPendingCheckForTap = new CheckForTap(); 10362 } 10363 mPendingCheckForTap.x = event.getX(); 10364 mPendingCheckForTap.y = event.getY(); 10365 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 10366 } else { 10367 // Not inside a scrolling container, so show the feedback right away 10368 setPressed(true, x, y); 10369 checkForLongClick(0); 10370 } 10371 break; 10372 10373 case MotionEvent.ACTION_CANCEL: 10374 setPressed(false); 10375 removeTapCallback(); 10376 removeLongPressCallback(); 10377 mInContextButtonPress = false; 10378 mHasPerformedLongPress = false; 10379 mIgnoreNextUpEvent = false; 10380 break; 10381 10382 case MotionEvent.ACTION_MOVE: 10383 drawableHotspotChanged(x, y); 10384 10385 // Be lenient about moving outside of buttons 10386 if (!pointInView(x, y, mTouchSlop)) { 10387 // Outside button 10388 removeTapCallback(); 10389 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 10390 // Remove any future long press/tap checks 10391 removeLongPressCallback(); 10392 10393 setPressed(false); 10394 } 10395 } 10396 break; 10397 } 10398 10399 return true; 10400 } 10401 10402 return false; 10403 } 10404 10405 /** 10406 * @hide 10407 */ 10408 public boolean isInScrollingContainer() { 10409 ViewParent p = getParent(); 10410 while (p != null && p instanceof ViewGroup) { 10411 if (((ViewGroup) p).shouldDelayChildPressedState()) { 10412 return true; 10413 } 10414 p = p.getParent(); 10415 } 10416 return false; 10417 } 10418 10419 /** 10420 * Remove the longpress detection timer. 10421 */ 10422 private void removeLongPressCallback() { 10423 if (mPendingCheckForLongPress != null) { 10424 removeCallbacks(mPendingCheckForLongPress); 10425 } 10426 } 10427 10428 /** 10429 * Remove the pending click action 10430 */ 10431 private void removePerformClickCallback() { 10432 if (mPerformClick != null) { 10433 removeCallbacks(mPerformClick); 10434 } 10435 } 10436 10437 /** 10438 * Remove the prepress detection timer. 10439 */ 10440 private void removeUnsetPressCallback() { 10441 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 10442 setPressed(false); 10443 removeCallbacks(mUnsetPressedState); 10444 } 10445 } 10446 10447 /** 10448 * Remove the tap detection timer. 10449 */ 10450 private void removeTapCallback() { 10451 if (mPendingCheckForTap != null) { 10452 mPrivateFlags &= ~PFLAG_PREPRESSED; 10453 removeCallbacks(mPendingCheckForTap); 10454 } 10455 } 10456 10457 /** 10458 * Cancels a pending long press. Your subclass can use this if you 10459 * want the context menu to come up if the user presses and holds 10460 * at the same place, but you don't want it to come up if they press 10461 * and then move around enough to cause scrolling. 10462 */ 10463 public void cancelLongPress() { 10464 removeLongPressCallback(); 10465 10466 /* 10467 * The prepressed state handled by the tap callback is a display 10468 * construct, but the tap callback will post a long press callback 10469 * less its own timeout. Remove it here. 10470 */ 10471 removeTapCallback(); 10472 } 10473 10474 /** 10475 * Remove the pending callback for sending a 10476 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 10477 */ 10478 private void removeSendViewScrolledAccessibilityEventCallback() { 10479 if (mSendViewScrolledAccessibilityEvent != null) { 10480 removeCallbacks(mSendViewScrolledAccessibilityEvent); 10481 mSendViewScrolledAccessibilityEvent.mIsPending = false; 10482 } 10483 } 10484 10485 /** 10486 * Sets the TouchDelegate for this View. 10487 */ 10488 public void setTouchDelegate(TouchDelegate delegate) { 10489 mTouchDelegate = delegate; 10490 } 10491 10492 /** 10493 * Gets the TouchDelegate for this View. 10494 */ 10495 public TouchDelegate getTouchDelegate() { 10496 return mTouchDelegate; 10497 } 10498 10499 /** 10500 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 10501 * 10502 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 10503 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 10504 * available. This method should only be called for touch events. 10505 * 10506 * <p class="note">This api is not intended for most applications. Buffered dispatch 10507 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 10508 * streams will not improve your input latency. Side effects include: increased latency, 10509 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 10510 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 10511 * you.</p> 10512 */ 10513 public final void requestUnbufferedDispatch(MotionEvent event) { 10514 final int action = event.getAction(); 10515 if (mAttachInfo == null 10516 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 10517 || !event.isTouchEvent()) { 10518 return; 10519 } 10520 mAttachInfo.mUnbufferedDispatchRequested = true; 10521 } 10522 10523 /** 10524 * Set flags controlling behavior of this view. 10525 * 10526 * @param flags Constant indicating the value which should be set 10527 * @param mask Constant indicating the bit range that should be changed 10528 */ 10529 void setFlags(int flags, int mask) { 10530 final boolean accessibilityEnabled = 10531 AccessibilityManager.getInstance(mContext).isEnabled(); 10532 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 10533 10534 int old = mViewFlags; 10535 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 10536 10537 int changed = mViewFlags ^ old; 10538 if (changed == 0) { 10539 return; 10540 } 10541 int privateFlags = mPrivateFlags; 10542 10543 /* Check if the FOCUSABLE bit has changed */ 10544 if (((changed & FOCUSABLE_MASK) != 0) && 10545 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 10546 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 10547 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 10548 /* Give up focus if we are no longer focusable */ 10549 clearFocus(); 10550 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 10551 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 10552 /* 10553 * Tell the view system that we are now available to take focus 10554 * if no one else already has it. 10555 */ 10556 if (mParent != null) mParent.focusableViewAvailable(this); 10557 } 10558 } 10559 10560 final int newVisibility = flags & VISIBILITY_MASK; 10561 if (newVisibility == VISIBLE) { 10562 if ((changed & VISIBILITY_MASK) != 0) { 10563 /* 10564 * If this view is becoming visible, invalidate it in case it changed while 10565 * it was not visible. Marking it drawn ensures that the invalidation will 10566 * go through. 10567 */ 10568 mPrivateFlags |= PFLAG_DRAWN; 10569 invalidate(true); 10570 10571 needGlobalAttributesUpdate(true); 10572 10573 // a view becoming visible is worth notifying the parent 10574 // about in case nothing has focus. even if this specific view 10575 // isn't focusable, it may contain something that is, so let 10576 // the root view try to give this focus if nothing else does. 10577 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 10578 mParent.focusableViewAvailable(this); 10579 } 10580 } 10581 } 10582 10583 /* Check if the GONE bit has changed */ 10584 if ((changed & GONE) != 0) { 10585 needGlobalAttributesUpdate(false); 10586 requestLayout(); 10587 10588 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 10589 if (hasFocus()) clearFocus(); 10590 clearAccessibilityFocus(); 10591 destroyDrawingCache(); 10592 if (mParent instanceof View) { 10593 // GONE views noop invalidation, so invalidate the parent 10594 ((View) mParent).invalidate(true); 10595 } 10596 // Mark the view drawn to ensure that it gets invalidated properly the next 10597 // time it is visible and gets invalidated 10598 mPrivateFlags |= PFLAG_DRAWN; 10599 } 10600 if (mAttachInfo != null) { 10601 mAttachInfo.mViewVisibilityChanged = true; 10602 } 10603 } 10604 10605 /* Check if the VISIBLE bit has changed */ 10606 if ((changed & INVISIBLE) != 0) { 10607 needGlobalAttributesUpdate(false); 10608 /* 10609 * If this view is becoming invisible, set the DRAWN flag so that 10610 * the next invalidate() will not be skipped. 10611 */ 10612 mPrivateFlags |= PFLAG_DRAWN; 10613 10614 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 10615 // root view becoming invisible shouldn't clear focus and accessibility focus 10616 if (getRootView() != this) { 10617 if (hasFocus()) clearFocus(); 10618 clearAccessibilityFocus(); 10619 } 10620 } 10621 if (mAttachInfo != null) { 10622 mAttachInfo.mViewVisibilityChanged = true; 10623 } 10624 } 10625 10626 if ((changed & VISIBILITY_MASK) != 0) { 10627 // If the view is invisible, cleanup its display list to free up resources 10628 if (newVisibility != VISIBLE && mAttachInfo != null) { 10629 cleanupDraw(); 10630 } 10631 10632 if (mParent instanceof ViewGroup) { 10633 ((ViewGroup) mParent).onChildVisibilityChanged(this, 10634 (changed & VISIBILITY_MASK), newVisibility); 10635 ((View) mParent).invalidate(true); 10636 } else if (mParent != null) { 10637 mParent.invalidateChild(this, null); 10638 } 10639 10640 if (mAttachInfo != null) { 10641 dispatchVisibilityChanged(this, newVisibility); 10642 notifySubtreeAccessibilityStateChangedIfNeeded(); 10643 } 10644 } 10645 10646 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 10647 destroyDrawingCache(); 10648 } 10649 10650 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 10651 destroyDrawingCache(); 10652 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10653 invalidateParentCaches(); 10654 } 10655 10656 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 10657 destroyDrawingCache(); 10658 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 10659 } 10660 10661 if ((changed & DRAW_MASK) != 0) { 10662 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 10663 if (mBackground != null 10664 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 10665 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 10666 } else { 10667 mPrivateFlags |= PFLAG_SKIP_DRAW; 10668 } 10669 } else { 10670 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 10671 } 10672 requestLayout(); 10673 invalidate(true); 10674 } 10675 10676 if ((changed & KEEP_SCREEN_ON) != 0) { 10677 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 10678 mParent.recomputeViewAttributes(this); 10679 } 10680 } 10681 10682 if (accessibilityEnabled) { 10683 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 10684 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 10685 || (changed & CONTEXT_CLICKABLE) != 0) { 10686 if (oldIncludeForAccessibility != includeForAccessibility()) { 10687 notifySubtreeAccessibilityStateChangedIfNeeded(); 10688 } else { 10689 notifyViewAccessibilityStateChangedIfNeeded( 10690 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10691 } 10692 } else if ((changed & ENABLED_MASK) != 0) { 10693 notifyViewAccessibilityStateChangedIfNeeded( 10694 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10695 } 10696 } 10697 } 10698 10699 /** 10700 * Change the view's z order in the tree, so it's on top of other sibling 10701 * views. This ordering change may affect layout, if the parent container 10702 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 10703 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 10704 * method should be followed by calls to {@link #requestLayout()} and 10705 * {@link View#invalidate()} on the view's parent to force the parent to redraw 10706 * with the new child ordering. 10707 * 10708 * @see ViewGroup#bringChildToFront(View) 10709 */ 10710 public void bringToFront() { 10711 if (mParent != null) { 10712 mParent.bringChildToFront(this); 10713 } 10714 } 10715 10716 /** 10717 * This is called in response to an internal scroll in this view (i.e., the 10718 * view scrolled its own contents). This is typically as a result of 10719 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 10720 * called. 10721 * 10722 * @param l Current horizontal scroll origin. 10723 * @param t Current vertical scroll origin. 10724 * @param oldl Previous horizontal scroll origin. 10725 * @param oldt Previous vertical scroll origin. 10726 */ 10727 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 10728 notifySubtreeAccessibilityStateChangedIfNeeded(); 10729 10730 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 10731 postSendViewScrolledAccessibilityEventCallback(); 10732 } 10733 10734 mBackgroundSizeChanged = true; 10735 if (mForegroundInfo != null) { 10736 mForegroundInfo.mBoundsChanged = true; 10737 } 10738 10739 final AttachInfo ai = mAttachInfo; 10740 if (ai != null) { 10741 ai.mViewScrollChanged = true; 10742 } 10743 10744 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 10745 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 10746 } 10747 } 10748 10749 /** 10750 * Interface definition for a callback to be invoked when the scroll 10751 * X or Y positions of a view change. 10752 * <p> 10753 * <b>Note:</b> Some views handle scrolling independently from View and may 10754 * have their own separate listeners for scroll-type events. For example, 10755 * {@link android.widget.ListView ListView} allows clients to register an 10756 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 10757 * to listen for changes in list scroll position. 10758 * 10759 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 10760 */ 10761 public interface OnScrollChangeListener { 10762 /** 10763 * Called when the scroll position of a view changes. 10764 * 10765 * @param v The view whose scroll position has changed. 10766 * @param scrollX Current horizontal scroll origin. 10767 * @param scrollY Current vertical scroll origin. 10768 * @param oldScrollX Previous horizontal scroll origin. 10769 * @param oldScrollY Previous vertical scroll origin. 10770 */ 10771 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 10772 } 10773 10774 /** 10775 * Interface definition for a callback to be invoked when the layout bounds of a view 10776 * changes due to layout processing. 10777 */ 10778 public interface OnLayoutChangeListener { 10779 /** 10780 * Called when the layout bounds of a view changes due to layout processing. 10781 * 10782 * @param v The view whose bounds have changed. 10783 * @param left The new value of the view's left property. 10784 * @param top The new value of the view's top property. 10785 * @param right The new value of the view's right property. 10786 * @param bottom The new value of the view's bottom property. 10787 * @param oldLeft The previous value of the view's left property. 10788 * @param oldTop The previous value of the view's top property. 10789 * @param oldRight The previous value of the view's right property. 10790 * @param oldBottom The previous value of the view's bottom property. 10791 */ 10792 void onLayoutChange(View v, int left, int top, int right, int bottom, 10793 int oldLeft, int oldTop, int oldRight, int oldBottom); 10794 } 10795 10796 /** 10797 * This is called during layout when the size of this view has changed. If 10798 * you were just added to the view hierarchy, you're called with the old 10799 * values of 0. 10800 * 10801 * @param w Current width of this view. 10802 * @param h Current height of this view. 10803 * @param oldw Old width of this view. 10804 * @param oldh Old height of this view. 10805 */ 10806 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 10807 } 10808 10809 /** 10810 * Called by draw to draw the child views. This may be overridden 10811 * by derived classes to gain control just before its children are drawn 10812 * (but after its own view has been drawn). 10813 * @param canvas the canvas on which to draw the view 10814 */ 10815 protected void dispatchDraw(Canvas canvas) { 10816 10817 } 10818 10819 /** 10820 * Gets the parent of this view. Note that the parent is a 10821 * ViewParent and not necessarily a View. 10822 * 10823 * @return Parent of this view. 10824 */ 10825 public final ViewParent getParent() { 10826 return mParent; 10827 } 10828 10829 /** 10830 * Set the horizontal scrolled position of your view. This will cause a call to 10831 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10832 * invalidated. 10833 * @param value the x position to scroll to 10834 */ 10835 public void setScrollX(int value) { 10836 scrollTo(value, mScrollY); 10837 } 10838 10839 /** 10840 * Set the vertical scrolled position of your view. This will cause a call to 10841 * {@link #onScrollChanged(int, int, int, int)} and the view will be 10842 * invalidated. 10843 * @param value the y position to scroll to 10844 */ 10845 public void setScrollY(int value) { 10846 scrollTo(mScrollX, value); 10847 } 10848 10849 /** 10850 * Return the scrolled left position of this view. This is the left edge of 10851 * the displayed part of your view. You do not need to draw any pixels 10852 * farther left, since those are outside of the frame of your view on 10853 * screen. 10854 * 10855 * @return The left edge of the displayed part of your view, in pixels. 10856 */ 10857 public final int getScrollX() { 10858 return mScrollX; 10859 } 10860 10861 /** 10862 * Return the scrolled top position of this view. This is the top edge of 10863 * the displayed part of your view. You do not need to draw any pixels above 10864 * it, since those are outside of the frame of your view on screen. 10865 * 10866 * @return The top edge of the displayed part of your view, in pixels. 10867 */ 10868 public final int getScrollY() { 10869 return mScrollY; 10870 } 10871 10872 /** 10873 * Return the width of the your view. 10874 * 10875 * @return The width of your view, in pixels. 10876 */ 10877 @ViewDebug.ExportedProperty(category = "layout") 10878 public final int getWidth() { 10879 return mRight - mLeft; 10880 } 10881 10882 /** 10883 * Return the height of your view. 10884 * 10885 * @return The height of your view, in pixels. 10886 */ 10887 @ViewDebug.ExportedProperty(category = "layout") 10888 public final int getHeight() { 10889 return mBottom - mTop; 10890 } 10891 10892 /** 10893 * Return the visible drawing bounds of your view. Fills in the output 10894 * rectangle with the values from getScrollX(), getScrollY(), 10895 * getWidth(), and getHeight(). These bounds do not account for any 10896 * transformation properties currently set on the view, such as 10897 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 10898 * 10899 * @param outRect The (scrolled) drawing bounds of the view. 10900 */ 10901 public void getDrawingRect(Rect outRect) { 10902 outRect.left = mScrollX; 10903 outRect.top = mScrollY; 10904 outRect.right = mScrollX + (mRight - mLeft); 10905 outRect.bottom = mScrollY + (mBottom - mTop); 10906 } 10907 10908 /** 10909 * Like {@link #getMeasuredWidthAndState()}, but only returns the 10910 * raw width component (that is the result is masked by 10911 * {@link #MEASURED_SIZE_MASK}). 10912 * 10913 * @return The raw measured width of this view. 10914 */ 10915 public final int getMeasuredWidth() { 10916 return mMeasuredWidth & MEASURED_SIZE_MASK; 10917 } 10918 10919 /** 10920 * Return the full width measurement information for this view as computed 10921 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10922 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10923 * This should be used during measurement and layout calculations only. Use 10924 * {@link #getWidth()} to see how wide a view is after layout. 10925 * 10926 * @return The measured width of this view as a bit mask. 10927 */ 10928 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 10929 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 10930 name = "MEASURED_STATE_TOO_SMALL"), 10931 }) 10932 public final int getMeasuredWidthAndState() { 10933 return mMeasuredWidth; 10934 } 10935 10936 /** 10937 * Like {@link #getMeasuredHeightAndState()}, but only returns the 10938 * raw width component (that is the result is masked by 10939 * {@link #MEASURED_SIZE_MASK}). 10940 * 10941 * @return The raw measured height of this view. 10942 */ 10943 public final int getMeasuredHeight() { 10944 return mMeasuredHeight & MEASURED_SIZE_MASK; 10945 } 10946 10947 /** 10948 * Return the full height measurement information for this view as computed 10949 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 10950 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 10951 * This should be used during measurement and layout calculations only. Use 10952 * {@link #getHeight()} to see how wide a view is after layout. 10953 * 10954 * @return The measured width of this view as a bit mask. 10955 */ 10956 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 10957 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 10958 name = "MEASURED_STATE_TOO_SMALL"), 10959 }) 10960 public final int getMeasuredHeightAndState() { 10961 return mMeasuredHeight; 10962 } 10963 10964 /** 10965 * Return only the state bits of {@link #getMeasuredWidthAndState()} 10966 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 10967 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 10968 * and the height component is at the shifted bits 10969 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 10970 */ 10971 public final int getMeasuredState() { 10972 return (mMeasuredWidth&MEASURED_STATE_MASK) 10973 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 10974 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 10975 } 10976 10977 /** 10978 * The transform matrix of this view, which is calculated based on the current 10979 * rotation, scale, and pivot properties. 10980 * 10981 * @see #getRotation() 10982 * @see #getScaleX() 10983 * @see #getScaleY() 10984 * @see #getPivotX() 10985 * @see #getPivotY() 10986 * @return The current transform matrix for the view 10987 */ 10988 public Matrix getMatrix() { 10989 ensureTransformationInfo(); 10990 final Matrix matrix = mTransformationInfo.mMatrix; 10991 mRenderNode.getMatrix(matrix); 10992 return matrix; 10993 } 10994 10995 /** 10996 * Returns true if the transform matrix is the identity matrix. 10997 * Recomputes the matrix if necessary. 10998 * 10999 * @return True if the transform matrix is the identity matrix, false otherwise. 11000 */ 11001 final boolean hasIdentityMatrix() { 11002 return mRenderNode.hasIdentityMatrix(); 11003 } 11004 11005 void ensureTransformationInfo() { 11006 if (mTransformationInfo == null) { 11007 mTransformationInfo = new TransformationInfo(); 11008 } 11009 } 11010 11011 /** 11012 * Utility method to retrieve the inverse of the current mMatrix property. 11013 * We cache the matrix to avoid recalculating it when transform properties 11014 * have not changed. 11015 * 11016 * @return The inverse of the current matrix of this view. 11017 * @hide 11018 */ 11019 public final Matrix getInverseMatrix() { 11020 ensureTransformationInfo(); 11021 if (mTransformationInfo.mInverseMatrix == null) { 11022 mTransformationInfo.mInverseMatrix = new Matrix(); 11023 } 11024 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11025 mRenderNode.getInverseMatrix(matrix); 11026 return matrix; 11027 } 11028 11029 /** 11030 * Gets the distance along the Z axis from the camera to this view. 11031 * 11032 * @see #setCameraDistance(float) 11033 * 11034 * @return The distance along the Z axis. 11035 */ 11036 public float getCameraDistance() { 11037 final float dpi = mResources.getDisplayMetrics().densityDpi; 11038 return -(mRenderNode.getCameraDistance() * dpi); 11039 } 11040 11041 /** 11042 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11043 * views are drawn) from the camera to this view. The camera's distance 11044 * affects 3D transformations, for instance rotations around the X and Y 11045 * axis. If the rotationX or rotationY properties are changed and this view is 11046 * large (more than half the size of the screen), it is recommended to always 11047 * use a camera distance that's greater than the height (X axis rotation) or 11048 * the width (Y axis rotation) of this view.</p> 11049 * 11050 * <p>The distance of the camera from the view plane can have an affect on the 11051 * perspective distortion of the view when it is rotated around the x or y axis. 11052 * For example, a large distance will result in a large viewing angle, and there 11053 * will not be much perspective distortion of the view as it rotates. A short 11054 * distance may cause much more perspective distortion upon rotation, and can 11055 * also result in some drawing artifacts if the rotated view ends up partially 11056 * behind the camera (which is why the recommendation is to use a distance at 11057 * least as far as the size of the view, if the view is to be rotated.)</p> 11058 * 11059 * <p>The distance is expressed in "depth pixels." The default distance depends 11060 * on the screen density. For instance, on a medium density display, the 11061 * default distance is 1280. On a high density display, the default distance 11062 * is 1920.</p> 11063 * 11064 * <p>If you want to specify a distance that leads to visually consistent 11065 * results across various densities, use the following formula:</p> 11066 * <pre> 11067 * float scale = context.getResources().getDisplayMetrics().density; 11068 * view.setCameraDistance(distance * scale); 11069 * </pre> 11070 * 11071 * <p>The density scale factor of a high density display is 1.5, 11072 * and 1920 = 1280 * 1.5.</p> 11073 * 11074 * @param distance The distance in "depth pixels", if negative the opposite 11075 * value is used 11076 * 11077 * @see #setRotationX(float) 11078 * @see #setRotationY(float) 11079 */ 11080 public void setCameraDistance(float distance) { 11081 final float dpi = mResources.getDisplayMetrics().densityDpi; 11082 11083 invalidateViewProperty(true, false); 11084 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11085 invalidateViewProperty(false, false); 11086 11087 invalidateParentIfNeededAndWasQuickRejected(); 11088 } 11089 11090 /** 11091 * The degrees that the view is rotated around the pivot point. 11092 * 11093 * @see #setRotation(float) 11094 * @see #getPivotX() 11095 * @see #getPivotY() 11096 * 11097 * @return The degrees of rotation. 11098 */ 11099 @ViewDebug.ExportedProperty(category = "drawing") 11100 public float getRotation() { 11101 return mRenderNode.getRotation(); 11102 } 11103 11104 /** 11105 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11106 * result in clockwise rotation. 11107 * 11108 * @param rotation The degrees of rotation. 11109 * 11110 * @see #getRotation() 11111 * @see #getPivotX() 11112 * @see #getPivotY() 11113 * @see #setRotationX(float) 11114 * @see #setRotationY(float) 11115 * 11116 * @attr ref android.R.styleable#View_rotation 11117 */ 11118 public void setRotation(float rotation) { 11119 if (rotation != getRotation()) { 11120 // Double-invalidation is necessary to capture view's old and new areas 11121 invalidateViewProperty(true, false); 11122 mRenderNode.setRotation(rotation); 11123 invalidateViewProperty(false, true); 11124 11125 invalidateParentIfNeededAndWasQuickRejected(); 11126 notifySubtreeAccessibilityStateChangedIfNeeded(); 11127 } 11128 } 11129 11130 /** 11131 * The degrees that the view is rotated around the vertical axis through the pivot point. 11132 * 11133 * @see #getPivotX() 11134 * @see #getPivotY() 11135 * @see #setRotationY(float) 11136 * 11137 * @return The degrees of Y rotation. 11138 */ 11139 @ViewDebug.ExportedProperty(category = "drawing") 11140 public float getRotationY() { 11141 return mRenderNode.getRotationY(); 11142 } 11143 11144 /** 11145 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 11146 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 11147 * down the y axis. 11148 * 11149 * When rotating large views, it is recommended to adjust the camera distance 11150 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11151 * 11152 * @param rotationY The degrees of Y rotation. 11153 * 11154 * @see #getRotationY() 11155 * @see #getPivotX() 11156 * @see #getPivotY() 11157 * @see #setRotation(float) 11158 * @see #setRotationX(float) 11159 * @see #setCameraDistance(float) 11160 * 11161 * @attr ref android.R.styleable#View_rotationY 11162 */ 11163 public void setRotationY(float rotationY) { 11164 if (rotationY != getRotationY()) { 11165 invalidateViewProperty(true, false); 11166 mRenderNode.setRotationY(rotationY); 11167 invalidateViewProperty(false, true); 11168 11169 invalidateParentIfNeededAndWasQuickRejected(); 11170 notifySubtreeAccessibilityStateChangedIfNeeded(); 11171 } 11172 } 11173 11174 /** 11175 * The degrees that the view is rotated around the horizontal axis through the pivot point. 11176 * 11177 * @see #getPivotX() 11178 * @see #getPivotY() 11179 * @see #setRotationX(float) 11180 * 11181 * @return The degrees of X rotation. 11182 */ 11183 @ViewDebug.ExportedProperty(category = "drawing") 11184 public float getRotationX() { 11185 return mRenderNode.getRotationX(); 11186 } 11187 11188 /** 11189 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 11190 * Increasing values result in clockwise rotation from the viewpoint of looking down the 11191 * x axis. 11192 * 11193 * When rotating large views, it is recommended to adjust the camera distance 11194 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11195 * 11196 * @param rotationX The degrees of X rotation. 11197 * 11198 * @see #getRotationX() 11199 * @see #getPivotX() 11200 * @see #getPivotY() 11201 * @see #setRotation(float) 11202 * @see #setRotationY(float) 11203 * @see #setCameraDistance(float) 11204 * 11205 * @attr ref android.R.styleable#View_rotationX 11206 */ 11207 public void setRotationX(float rotationX) { 11208 if (rotationX != getRotationX()) { 11209 invalidateViewProperty(true, false); 11210 mRenderNode.setRotationX(rotationX); 11211 invalidateViewProperty(false, true); 11212 11213 invalidateParentIfNeededAndWasQuickRejected(); 11214 notifySubtreeAccessibilityStateChangedIfNeeded(); 11215 } 11216 } 11217 11218 /** 11219 * The amount that the view is scaled in x around the pivot point, as a proportion of 11220 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 11221 * 11222 * <p>By default, this is 1.0f. 11223 * 11224 * @see #getPivotX() 11225 * @see #getPivotY() 11226 * @return The scaling factor. 11227 */ 11228 @ViewDebug.ExportedProperty(category = "drawing") 11229 public float getScaleX() { 11230 return mRenderNode.getScaleX(); 11231 } 11232 11233 /** 11234 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 11235 * the view's unscaled width. A value of 1 means that no scaling is applied. 11236 * 11237 * @param scaleX The scaling factor. 11238 * @see #getPivotX() 11239 * @see #getPivotY() 11240 * 11241 * @attr ref android.R.styleable#View_scaleX 11242 */ 11243 public void setScaleX(float scaleX) { 11244 if (scaleX != getScaleX()) { 11245 invalidateViewProperty(true, false); 11246 mRenderNode.setScaleX(scaleX); 11247 invalidateViewProperty(false, true); 11248 11249 invalidateParentIfNeededAndWasQuickRejected(); 11250 notifySubtreeAccessibilityStateChangedIfNeeded(); 11251 } 11252 } 11253 11254 /** 11255 * The amount that the view is scaled in y around the pivot point, as a proportion of 11256 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 11257 * 11258 * <p>By default, this is 1.0f. 11259 * 11260 * @see #getPivotX() 11261 * @see #getPivotY() 11262 * @return The scaling factor. 11263 */ 11264 @ViewDebug.ExportedProperty(category = "drawing") 11265 public float getScaleY() { 11266 return mRenderNode.getScaleY(); 11267 } 11268 11269 /** 11270 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 11271 * the view's unscaled width. A value of 1 means that no scaling is applied. 11272 * 11273 * @param scaleY The scaling factor. 11274 * @see #getPivotX() 11275 * @see #getPivotY() 11276 * 11277 * @attr ref android.R.styleable#View_scaleY 11278 */ 11279 public void setScaleY(float scaleY) { 11280 if (scaleY != getScaleY()) { 11281 invalidateViewProperty(true, false); 11282 mRenderNode.setScaleY(scaleY); 11283 invalidateViewProperty(false, true); 11284 11285 invalidateParentIfNeededAndWasQuickRejected(); 11286 notifySubtreeAccessibilityStateChangedIfNeeded(); 11287 } 11288 } 11289 11290 /** 11291 * The x location of the point around which the view is {@link #setRotation(float) rotated} 11292 * and {@link #setScaleX(float) scaled}. 11293 * 11294 * @see #getRotation() 11295 * @see #getScaleX() 11296 * @see #getScaleY() 11297 * @see #getPivotY() 11298 * @return The x location of the pivot point. 11299 * 11300 * @attr ref android.R.styleable#View_transformPivotX 11301 */ 11302 @ViewDebug.ExportedProperty(category = "drawing") 11303 public float getPivotX() { 11304 return mRenderNode.getPivotX(); 11305 } 11306 11307 /** 11308 * Sets the x location of the point around which the view is 11309 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 11310 * By default, the pivot point is centered on the object. 11311 * Setting this property disables this behavior and causes the view to use only the 11312 * explicitly set pivotX and pivotY values. 11313 * 11314 * @param pivotX The x location of the pivot point. 11315 * @see #getRotation() 11316 * @see #getScaleX() 11317 * @see #getScaleY() 11318 * @see #getPivotY() 11319 * 11320 * @attr ref android.R.styleable#View_transformPivotX 11321 */ 11322 public void setPivotX(float pivotX) { 11323 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 11324 invalidateViewProperty(true, false); 11325 mRenderNode.setPivotX(pivotX); 11326 invalidateViewProperty(false, true); 11327 11328 invalidateParentIfNeededAndWasQuickRejected(); 11329 } 11330 } 11331 11332 /** 11333 * The y location of the point around which the view is {@link #setRotation(float) rotated} 11334 * and {@link #setScaleY(float) scaled}. 11335 * 11336 * @see #getRotation() 11337 * @see #getScaleX() 11338 * @see #getScaleY() 11339 * @see #getPivotY() 11340 * @return The y location of the pivot point. 11341 * 11342 * @attr ref android.R.styleable#View_transformPivotY 11343 */ 11344 @ViewDebug.ExportedProperty(category = "drawing") 11345 public float getPivotY() { 11346 return mRenderNode.getPivotY(); 11347 } 11348 11349 /** 11350 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 11351 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 11352 * Setting this property disables this behavior and causes the view to use only the 11353 * explicitly set pivotX and pivotY values. 11354 * 11355 * @param pivotY The y location of the pivot point. 11356 * @see #getRotation() 11357 * @see #getScaleX() 11358 * @see #getScaleY() 11359 * @see #getPivotY() 11360 * 11361 * @attr ref android.R.styleable#View_transformPivotY 11362 */ 11363 public void setPivotY(float pivotY) { 11364 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 11365 invalidateViewProperty(true, false); 11366 mRenderNode.setPivotY(pivotY); 11367 invalidateViewProperty(false, true); 11368 11369 invalidateParentIfNeededAndWasQuickRejected(); 11370 } 11371 } 11372 11373 /** 11374 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 11375 * completely transparent and 1 means the view is completely opaque. 11376 * 11377 * <p>By default this is 1.0f. 11378 * @return The opacity of the view. 11379 */ 11380 @ViewDebug.ExportedProperty(category = "drawing") 11381 public float getAlpha() { 11382 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 11383 } 11384 11385 /** 11386 * Returns whether this View has content which overlaps. 11387 * 11388 * <p>This function, intended to be overridden by specific View types, is an optimization when 11389 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 11390 * an offscreen buffer and then composited into place, which can be expensive. If the view has 11391 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 11392 * directly. An example of overlapping rendering is a TextView with a background image, such as 11393 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 11394 * ImageView with only the foreground image. The default implementation returns true; subclasses 11395 * should override if they have cases which can be optimized.</p> 11396 * 11397 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 11398 * necessitates that a View return true if it uses the methods internally without passing the 11399 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 11400 * 11401 * @return true if the content in this view might overlap, false otherwise. 11402 */ 11403 @ViewDebug.ExportedProperty(category = "drawing") 11404 public boolean hasOverlappingRendering() { 11405 return true; 11406 } 11407 11408 /** 11409 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 11410 * completely transparent and 1 means the view is completely opaque. 11411 * 11412 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 11413 * can have significant performance implications, especially for large views. It is best to use 11414 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 11415 * 11416 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 11417 * strongly recommended for performance reasons to either override 11418 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 11419 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 11420 * of the animation. On versions {@link android.os.Build.VERSION_CODES#MNC} and below, 11421 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 11422 * of rendering cost, even for simple or small views. Starting with 11423 * {@link android.os.Build.VERSION_CODES#MNC}, {@link #LAYER_TYPE_HARDWARE} is automatically 11424 * applied to the view at the rendering level.</p> 11425 * 11426 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 11427 * responsible for applying the opacity itself.</p> 11428 * 11429 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 11430 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 11431 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 11432 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 11433 * 11434 * <p>Starting with {@link android.os.Build.VERSION_CODES#MNC}, setting a translucent alpha 11435 * value will clip a View to its bounds, unless the View returns <code>false</code> from 11436 * {@link #hasOverlappingRendering}.</p> 11437 * 11438 * @param alpha The opacity of the view. 11439 * 11440 * @see #hasOverlappingRendering() 11441 * @see #setLayerType(int, android.graphics.Paint) 11442 * 11443 * @attr ref android.R.styleable#View_alpha 11444 */ 11445 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 11446 ensureTransformationInfo(); 11447 if (mTransformationInfo.mAlpha != alpha) { 11448 mTransformationInfo.mAlpha = alpha; 11449 if (onSetAlpha((int) (alpha * 255))) { 11450 mPrivateFlags |= PFLAG_ALPHA_SET; 11451 // subclass is handling alpha - don't optimize rendering cache invalidation 11452 invalidateParentCaches(); 11453 invalidate(true); 11454 } else { 11455 mPrivateFlags &= ~PFLAG_ALPHA_SET; 11456 invalidateViewProperty(true, false); 11457 mRenderNode.setAlpha(getFinalAlpha()); 11458 notifyViewAccessibilityStateChangedIfNeeded( 11459 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11460 } 11461 } 11462 } 11463 11464 /** 11465 * Faster version of setAlpha() which performs the same steps except there are 11466 * no calls to invalidate(). The caller of this function should perform proper invalidation 11467 * on the parent and this object. The return value indicates whether the subclass handles 11468 * alpha (the return value for onSetAlpha()). 11469 * 11470 * @param alpha The new value for the alpha property 11471 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 11472 * the new value for the alpha property is different from the old value 11473 */ 11474 boolean setAlphaNoInvalidation(float alpha) { 11475 ensureTransformationInfo(); 11476 if (mTransformationInfo.mAlpha != alpha) { 11477 mTransformationInfo.mAlpha = alpha; 11478 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 11479 if (subclassHandlesAlpha) { 11480 mPrivateFlags |= PFLAG_ALPHA_SET; 11481 return true; 11482 } else { 11483 mPrivateFlags &= ~PFLAG_ALPHA_SET; 11484 mRenderNode.setAlpha(getFinalAlpha()); 11485 } 11486 } 11487 return false; 11488 } 11489 11490 /** 11491 * This property is hidden and intended only for use by the Fade transition, which 11492 * animates it to produce a visual translucency that does not side-effect (or get 11493 * affected by) the real alpha property. This value is composited with the other 11494 * alpha value (and the AlphaAnimation value, when that is present) to produce 11495 * a final visual translucency result, which is what is passed into the DisplayList. 11496 * 11497 * @hide 11498 */ 11499 public void setTransitionAlpha(float alpha) { 11500 ensureTransformationInfo(); 11501 if (mTransformationInfo.mTransitionAlpha != alpha) { 11502 mTransformationInfo.mTransitionAlpha = alpha; 11503 mPrivateFlags &= ~PFLAG_ALPHA_SET; 11504 invalidateViewProperty(true, false); 11505 mRenderNode.setAlpha(getFinalAlpha()); 11506 } 11507 } 11508 11509 /** 11510 * Calculates the visual alpha of this view, which is a combination of the actual 11511 * alpha value and the transitionAlpha value (if set). 11512 */ 11513 private float getFinalAlpha() { 11514 if (mTransformationInfo != null) { 11515 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 11516 } 11517 return 1; 11518 } 11519 11520 /** 11521 * This property is hidden and intended only for use by the Fade transition, which 11522 * animates it to produce a visual translucency that does not side-effect (or get 11523 * affected by) the real alpha property. This value is composited with the other 11524 * alpha value (and the AlphaAnimation value, when that is present) to produce 11525 * a final visual translucency result, which is what is passed into the DisplayList. 11526 * 11527 * @hide 11528 */ 11529 @ViewDebug.ExportedProperty(category = "drawing") 11530 public float getTransitionAlpha() { 11531 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 11532 } 11533 11534 /** 11535 * Top position of this view relative to its parent. 11536 * 11537 * @return The top of this view, in pixels. 11538 */ 11539 @ViewDebug.CapturedViewProperty 11540 public final int getTop() { 11541 return mTop; 11542 } 11543 11544 /** 11545 * Sets the top position of this view relative to its parent. This method is meant to be called 11546 * by the layout system and should not generally be called otherwise, because the property 11547 * may be changed at any time by the layout. 11548 * 11549 * @param top The top of this view, in pixels. 11550 */ 11551 public final void setTop(int top) { 11552 if (top != mTop) { 11553 final boolean matrixIsIdentity = hasIdentityMatrix(); 11554 if (matrixIsIdentity) { 11555 if (mAttachInfo != null) { 11556 int minTop; 11557 int yLoc; 11558 if (top < mTop) { 11559 minTop = top; 11560 yLoc = top - mTop; 11561 } else { 11562 minTop = mTop; 11563 yLoc = 0; 11564 } 11565 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 11566 } 11567 } else { 11568 // Double-invalidation is necessary to capture view's old and new areas 11569 invalidate(true); 11570 } 11571 11572 int width = mRight - mLeft; 11573 int oldHeight = mBottom - mTop; 11574 11575 mTop = top; 11576 mRenderNode.setTop(mTop); 11577 11578 sizeChange(width, mBottom - mTop, width, oldHeight); 11579 11580 if (!matrixIsIdentity) { 11581 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11582 invalidate(true); 11583 } 11584 mBackgroundSizeChanged = true; 11585 if (mForegroundInfo != null) { 11586 mForegroundInfo.mBoundsChanged = true; 11587 } 11588 invalidateParentIfNeeded(); 11589 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11590 // View was rejected last time it was drawn by its parent; this may have changed 11591 invalidateParentIfNeeded(); 11592 } 11593 } 11594 } 11595 11596 /** 11597 * Bottom position of this view relative to its parent. 11598 * 11599 * @return The bottom of this view, in pixels. 11600 */ 11601 @ViewDebug.CapturedViewProperty 11602 public final int getBottom() { 11603 return mBottom; 11604 } 11605 11606 /** 11607 * True if this view has changed since the last time being drawn. 11608 * 11609 * @return The dirty state of this view. 11610 */ 11611 public boolean isDirty() { 11612 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 11613 } 11614 11615 /** 11616 * Sets the bottom position of this view relative to its parent. This method is meant to be 11617 * called by the layout system and should not generally be called otherwise, because the 11618 * property may be changed at any time by the layout. 11619 * 11620 * @param bottom The bottom of this view, in pixels. 11621 */ 11622 public final void setBottom(int bottom) { 11623 if (bottom != mBottom) { 11624 final boolean matrixIsIdentity = hasIdentityMatrix(); 11625 if (matrixIsIdentity) { 11626 if (mAttachInfo != null) { 11627 int maxBottom; 11628 if (bottom < mBottom) { 11629 maxBottom = mBottom; 11630 } else { 11631 maxBottom = bottom; 11632 } 11633 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 11634 } 11635 } else { 11636 // Double-invalidation is necessary to capture view's old and new areas 11637 invalidate(true); 11638 } 11639 11640 int width = mRight - mLeft; 11641 int oldHeight = mBottom - mTop; 11642 11643 mBottom = bottom; 11644 mRenderNode.setBottom(mBottom); 11645 11646 sizeChange(width, mBottom - mTop, width, oldHeight); 11647 11648 if (!matrixIsIdentity) { 11649 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11650 invalidate(true); 11651 } 11652 mBackgroundSizeChanged = true; 11653 if (mForegroundInfo != null) { 11654 mForegroundInfo.mBoundsChanged = true; 11655 } 11656 invalidateParentIfNeeded(); 11657 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11658 // View was rejected last time it was drawn by its parent; this may have changed 11659 invalidateParentIfNeeded(); 11660 } 11661 } 11662 } 11663 11664 /** 11665 * Left position of this view relative to its parent. 11666 * 11667 * @return The left edge of this view, in pixels. 11668 */ 11669 @ViewDebug.CapturedViewProperty 11670 public final int getLeft() { 11671 return mLeft; 11672 } 11673 11674 /** 11675 * Sets the left position of this view relative to its parent. This method is meant to be called 11676 * by the layout system and should not generally be called otherwise, because the property 11677 * may be changed at any time by the layout. 11678 * 11679 * @param left The left of this view, in pixels. 11680 */ 11681 public final void setLeft(int left) { 11682 if (left != mLeft) { 11683 final boolean matrixIsIdentity = hasIdentityMatrix(); 11684 if (matrixIsIdentity) { 11685 if (mAttachInfo != null) { 11686 int minLeft; 11687 int xLoc; 11688 if (left < mLeft) { 11689 minLeft = left; 11690 xLoc = left - mLeft; 11691 } else { 11692 minLeft = mLeft; 11693 xLoc = 0; 11694 } 11695 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 11696 } 11697 } else { 11698 // Double-invalidation is necessary to capture view's old and new areas 11699 invalidate(true); 11700 } 11701 11702 int oldWidth = mRight - mLeft; 11703 int height = mBottom - mTop; 11704 11705 mLeft = left; 11706 mRenderNode.setLeft(left); 11707 11708 sizeChange(mRight - mLeft, height, oldWidth, height); 11709 11710 if (!matrixIsIdentity) { 11711 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11712 invalidate(true); 11713 } 11714 mBackgroundSizeChanged = true; 11715 if (mForegroundInfo != null) { 11716 mForegroundInfo.mBoundsChanged = true; 11717 } 11718 invalidateParentIfNeeded(); 11719 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11720 // View was rejected last time it was drawn by its parent; this may have changed 11721 invalidateParentIfNeeded(); 11722 } 11723 } 11724 } 11725 11726 /** 11727 * Right position of this view relative to its parent. 11728 * 11729 * @return The right edge of this view, in pixels. 11730 */ 11731 @ViewDebug.CapturedViewProperty 11732 public final int getRight() { 11733 return mRight; 11734 } 11735 11736 /** 11737 * Sets the right position of this view relative to its parent. This method is meant to be called 11738 * by the layout system and should not generally be called otherwise, because the property 11739 * may be changed at any time by the layout. 11740 * 11741 * @param right The right of this view, in pixels. 11742 */ 11743 public final void setRight(int right) { 11744 if (right != mRight) { 11745 final boolean matrixIsIdentity = hasIdentityMatrix(); 11746 if (matrixIsIdentity) { 11747 if (mAttachInfo != null) { 11748 int maxRight; 11749 if (right < mRight) { 11750 maxRight = mRight; 11751 } else { 11752 maxRight = right; 11753 } 11754 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 11755 } 11756 } else { 11757 // Double-invalidation is necessary to capture view's old and new areas 11758 invalidate(true); 11759 } 11760 11761 int oldWidth = mRight - mLeft; 11762 int height = mBottom - mTop; 11763 11764 mRight = right; 11765 mRenderNode.setRight(mRight); 11766 11767 sizeChange(mRight - mLeft, height, oldWidth, height); 11768 11769 if (!matrixIsIdentity) { 11770 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11771 invalidate(true); 11772 } 11773 mBackgroundSizeChanged = true; 11774 if (mForegroundInfo != null) { 11775 mForegroundInfo.mBoundsChanged = true; 11776 } 11777 invalidateParentIfNeeded(); 11778 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 11779 // View was rejected last time it was drawn by its parent; this may have changed 11780 invalidateParentIfNeeded(); 11781 } 11782 } 11783 } 11784 11785 /** 11786 * The visual x position of this view, in pixels. This is equivalent to the 11787 * {@link #setTranslationX(float) translationX} property plus the current 11788 * {@link #getLeft() left} property. 11789 * 11790 * @return The visual x position of this view, in pixels. 11791 */ 11792 @ViewDebug.ExportedProperty(category = "drawing") 11793 public float getX() { 11794 return mLeft + getTranslationX(); 11795 } 11796 11797 /** 11798 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 11799 * {@link #setTranslationX(float) translationX} property to be the difference between 11800 * the x value passed in and the current {@link #getLeft() left} property. 11801 * 11802 * @param x The visual x position of this view, in pixels. 11803 */ 11804 public void setX(float x) { 11805 setTranslationX(x - mLeft); 11806 } 11807 11808 /** 11809 * The visual y position of this view, in pixels. This is equivalent to the 11810 * {@link #setTranslationY(float) translationY} property plus the current 11811 * {@link #getTop() top} property. 11812 * 11813 * @return The visual y position of this view, in pixels. 11814 */ 11815 @ViewDebug.ExportedProperty(category = "drawing") 11816 public float getY() { 11817 return mTop + getTranslationY(); 11818 } 11819 11820 /** 11821 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 11822 * {@link #setTranslationY(float) translationY} property to be the difference between 11823 * the y value passed in and the current {@link #getTop() top} property. 11824 * 11825 * @param y The visual y position of this view, in pixels. 11826 */ 11827 public void setY(float y) { 11828 setTranslationY(y - mTop); 11829 } 11830 11831 /** 11832 * The visual z position of this view, in pixels. This is equivalent to the 11833 * {@link #setTranslationZ(float) translationZ} property plus the current 11834 * {@link #getElevation() elevation} property. 11835 * 11836 * @return The visual z position of this view, in pixels. 11837 */ 11838 @ViewDebug.ExportedProperty(category = "drawing") 11839 public float getZ() { 11840 return getElevation() + getTranslationZ(); 11841 } 11842 11843 /** 11844 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 11845 * {@link #setTranslationZ(float) translationZ} property to be the difference between 11846 * the x value passed in and the current {@link #getElevation() elevation} property. 11847 * 11848 * @param z The visual z position of this view, in pixels. 11849 */ 11850 public void setZ(float z) { 11851 setTranslationZ(z - getElevation()); 11852 } 11853 11854 /** 11855 * The base elevation of this view relative to its parent, in pixels. 11856 * 11857 * @return The base depth position of the view, in pixels. 11858 */ 11859 @ViewDebug.ExportedProperty(category = "drawing") 11860 public float getElevation() { 11861 return mRenderNode.getElevation(); 11862 } 11863 11864 /** 11865 * Sets the base elevation of this view, in pixels. 11866 * 11867 * @attr ref android.R.styleable#View_elevation 11868 */ 11869 public void setElevation(float elevation) { 11870 if (elevation != getElevation()) { 11871 invalidateViewProperty(true, false); 11872 mRenderNode.setElevation(elevation); 11873 invalidateViewProperty(false, true); 11874 11875 invalidateParentIfNeededAndWasQuickRejected(); 11876 } 11877 } 11878 11879 /** 11880 * The horizontal location of this view relative to its {@link #getLeft() left} position. 11881 * This position is post-layout, in addition to wherever the object's 11882 * layout placed it. 11883 * 11884 * @return The horizontal position of this view relative to its left position, in pixels. 11885 */ 11886 @ViewDebug.ExportedProperty(category = "drawing") 11887 public float getTranslationX() { 11888 return mRenderNode.getTranslationX(); 11889 } 11890 11891 /** 11892 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 11893 * This effectively positions the object post-layout, in addition to wherever the object's 11894 * layout placed it. 11895 * 11896 * @param translationX The horizontal position of this view relative to its left position, 11897 * in pixels. 11898 * 11899 * @attr ref android.R.styleable#View_translationX 11900 */ 11901 public void setTranslationX(float translationX) { 11902 if (translationX != getTranslationX()) { 11903 invalidateViewProperty(true, false); 11904 mRenderNode.setTranslationX(translationX); 11905 invalidateViewProperty(false, true); 11906 11907 invalidateParentIfNeededAndWasQuickRejected(); 11908 notifySubtreeAccessibilityStateChangedIfNeeded(); 11909 } 11910 } 11911 11912 /** 11913 * The vertical location of this view relative to its {@link #getTop() top} position. 11914 * This position is post-layout, in addition to wherever the object's 11915 * layout placed it. 11916 * 11917 * @return The vertical position of this view relative to its top position, 11918 * in pixels. 11919 */ 11920 @ViewDebug.ExportedProperty(category = "drawing") 11921 public float getTranslationY() { 11922 return mRenderNode.getTranslationY(); 11923 } 11924 11925 /** 11926 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 11927 * This effectively positions the object post-layout, in addition to wherever the object's 11928 * layout placed it. 11929 * 11930 * @param translationY The vertical position of this view relative to its top position, 11931 * in pixels. 11932 * 11933 * @attr ref android.R.styleable#View_translationY 11934 */ 11935 public void setTranslationY(float translationY) { 11936 if (translationY != getTranslationY()) { 11937 invalidateViewProperty(true, false); 11938 mRenderNode.setTranslationY(translationY); 11939 invalidateViewProperty(false, true); 11940 11941 invalidateParentIfNeededAndWasQuickRejected(); 11942 notifySubtreeAccessibilityStateChangedIfNeeded(); 11943 } 11944 } 11945 11946 /** 11947 * The depth location of this view relative to its {@link #getElevation() elevation}. 11948 * 11949 * @return The depth of this view relative to its elevation. 11950 */ 11951 @ViewDebug.ExportedProperty(category = "drawing") 11952 public float getTranslationZ() { 11953 return mRenderNode.getTranslationZ(); 11954 } 11955 11956 /** 11957 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 11958 * 11959 * @attr ref android.R.styleable#View_translationZ 11960 */ 11961 public void setTranslationZ(float translationZ) { 11962 if (translationZ != getTranslationZ()) { 11963 invalidateViewProperty(true, false); 11964 mRenderNode.setTranslationZ(translationZ); 11965 invalidateViewProperty(false, true); 11966 11967 invalidateParentIfNeededAndWasQuickRejected(); 11968 } 11969 } 11970 11971 /** @hide */ 11972 public void setAnimationMatrix(Matrix matrix) { 11973 invalidateViewProperty(true, false); 11974 mRenderNode.setAnimationMatrix(matrix); 11975 invalidateViewProperty(false, true); 11976 11977 invalidateParentIfNeededAndWasQuickRejected(); 11978 } 11979 11980 /** 11981 * Returns the current StateListAnimator if exists. 11982 * 11983 * @return StateListAnimator or null if it does not exists 11984 * @see #setStateListAnimator(android.animation.StateListAnimator) 11985 */ 11986 public StateListAnimator getStateListAnimator() { 11987 return mStateListAnimator; 11988 } 11989 11990 /** 11991 * Attaches the provided StateListAnimator to this View. 11992 * <p> 11993 * Any previously attached StateListAnimator will be detached. 11994 * 11995 * @param stateListAnimator The StateListAnimator to update the view 11996 * @see {@link android.animation.StateListAnimator} 11997 */ 11998 public void setStateListAnimator(StateListAnimator stateListAnimator) { 11999 if (mStateListAnimator == stateListAnimator) { 12000 return; 12001 } 12002 if (mStateListAnimator != null) { 12003 mStateListAnimator.setTarget(null); 12004 } 12005 mStateListAnimator = stateListAnimator; 12006 if (stateListAnimator != null) { 12007 stateListAnimator.setTarget(this); 12008 if (isAttachedToWindow()) { 12009 stateListAnimator.setState(getDrawableState()); 12010 } 12011 } 12012 } 12013 12014 /** 12015 * Returns whether the Outline should be used to clip the contents of the View. 12016 * <p> 12017 * Note that this flag will only be respected if the View's Outline returns true from 12018 * {@link Outline#canClip()}. 12019 * 12020 * @see #setOutlineProvider(ViewOutlineProvider) 12021 * @see #setClipToOutline(boolean) 12022 */ 12023 public final boolean getClipToOutline() { 12024 return mRenderNode.getClipToOutline(); 12025 } 12026 12027 /** 12028 * Sets whether the View's Outline should be used to clip the contents of the View. 12029 * <p> 12030 * Only a single non-rectangular clip can be applied on a View at any time. 12031 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12032 * circular reveal} animation take priority over Outline clipping, and 12033 * child Outline clipping takes priority over Outline clipping done by a 12034 * parent. 12035 * <p> 12036 * Note that this flag will only be respected if the View's Outline returns true from 12037 * {@link Outline#canClip()}. 12038 * 12039 * @see #setOutlineProvider(ViewOutlineProvider) 12040 * @see #getClipToOutline() 12041 */ 12042 public void setClipToOutline(boolean clipToOutline) { 12043 damageInParent(); 12044 if (getClipToOutline() != clipToOutline) { 12045 mRenderNode.setClipToOutline(clipToOutline); 12046 } 12047 } 12048 12049 // correspond to the enum values of View_outlineProvider 12050 private static final int PROVIDER_BACKGROUND = 0; 12051 private static final int PROVIDER_NONE = 1; 12052 private static final int PROVIDER_BOUNDS = 2; 12053 private static final int PROVIDER_PADDED_BOUNDS = 3; 12054 private void setOutlineProviderFromAttribute(int providerInt) { 12055 switch (providerInt) { 12056 case PROVIDER_BACKGROUND: 12057 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12058 break; 12059 case PROVIDER_NONE: 12060 setOutlineProvider(null); 12061 break; 12062 case PROVIDER_BOUNDS: 12063 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12064 break; 12065 case PROVIDER_PADDED_BOUNDS: 12066 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12067 break; 12068 } 12069 } 12070 12071 /** 12072 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12073 * the shape of the shadow it casts, and enables outline clipping. 12074 * <p> 12075 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12076 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12077 * outline provider with this method allows this behavior to be overridden. 12078 * <p> 12079 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12080 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12081 * <p> 12082 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 12083 * 12084 * @see #setClipToOutline(boolean) 12085 * @see #getClipToOutline() 12086 * @see #getOutlineProvider() 12087 */ 12088 public void setOutlineProvider(ViewOutlineProvider provider) { 12089 mOutlineProvider = provider; 12090 invalidateOutline(); 12091 } 12092 12093 /** 12094 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 12095 * that defines the shape of the shadow it casts, and enables outline clipping. 12096 * 12097 * @see #setOutlineProvider(ViewOutlineProvider) 12098 */ 12099 public ViewOutlineProvider getOutlineProvider() { 12100 return mOutlineProvider; 12101 } 12102 12103 /** 12104 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 12105 * 12106 * @see #setOutlineProvider(ViewOutlineProvider) 12107 */ 12108 public void invalidateOutline() { 12109 rebuildOutline(); 12110 12111 notifySubtreeAccessibilityStateChangedIfNeeded(); 12112 invalidateViewProperty(false, false); 12113 } 12114 12115 /** 12116 * Internal version of {@link #invalidateOutline()} which invalidates the 12117 * outline without invalidating the view itself. This is intended to be called from 12118 * within methods in the View class itself which are the result of the view being 12119 * invalidated already. For example, when we are drawing the background of a View, 12120 * we invalidate the outline in case it changed in the meantime, but we do not 12121 * need to invalidate the view because we're already drawing the background as part 12122 * of drawing the view in response to an earlier invalidation of the view. 12123 */ 12124 private void rebuildOutline() { 12125 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 12126 if (mAttachInfo == null) return; 12127 12128 if (mOutlineProvider == null) { 12129 // no provider, remove outline 12130 mRenderNode.setOutline(null); 12131 } else { 12132 final Outline outline = mAttachInfo.mTmpOutline; 12133 outline.setEmpty(); 12134 outline.setAlpha(1.0f); 12135 12136 mOutlineProvider.getOutline(this, outline); 12137 mRenderNode.setOutline(outline); 12138 } 12139 } 12140 12141 /** 12142 * HierarchyViewer only 12143 * 12144 * @hide 12145 */ 12146 @ViewDebug.ExportedProperty(category = "drawing") 12147 public boolean hasShadow() { 12148 return mRenderNode.hasShadow(); 12149 } 12150 12151 12152 /** @hide */ 12153 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 12154 mRenderNode.setRevealClip(shouldClip, x, y, radius); 12155 invalidateViewProperty(false, false); 12156 } 12157 12158 /** 12159 * Hit rectangle in parent's coordinates 12160 * 12161 * @param outRect The hit rectangle of the view. 12162 */ 12163 public void getHitRect(Rect outRect) { 12164 if (hasIdentityMatrix() || mAttachInfo == null) { 12165 outRect.set(mLeft, mTop, mRight, mBottom); 12166 } else { 12167 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 12168 tmpRect.set(0, 0, getWidth(), getHeight()); 12169 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 12170 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 12171 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 12172 } 12173 } 12174 12175 /** 12176 * Determines whether the given point, in local coordinates is inside the view. 12177 */ 12178 /*package*/ final boolean pointInView(float localX, float localY) { 12179 return localX >= 0 && localX < (mRight - mLeft) 12180 && localY >= 0 && localY < (mBottom - mTop); 12181 } 12182 12183 /** 12184 * Utility method to determine whether the given point, in local coordinates, 12185 * is inside the view, where the area of the view is expanded by the slop factor. 12186 * This method is called while processing touch-move events to determine if the event 12187 * is still within the view. 12188 * 12189 * @hide 12190 */ 12191 public boolean pointInView(float localX, float localY, float slop) { 12192 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 12193 localY < ((mBottom - mTop) + slop); 12194 } 12195 12196 /** 12197 * When a view has focus and the user navigates away from it, the next view is searched for 12198 * starting from the rectangle filled in by this method. 12199 * 12200 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 12201 * of the view. However, if your view maintains some idea of internal selection, 12202 * such as a cursor, or a selected row or column, you should override this method and 12203 * fill in a more specific rectangle. 12204 * 12205 * @param r The rectangle to fill in, in this view's coordinates. 12206 */ 12207 public void getFocusedRect(Rect r) { 12208 getDrawingRect(r); 12209 } 12210 12211 /** 12212 * If some part of this view is not clipped by any of its parents, then 12213 * return that area in r in global (root) coordinates. To convert r to local 12214 * coordinates (without taking possible View rotations into account), offset 12215 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 12216 * If the view is completely clipped or translated out, return false. 12217 * 12218 * @param r If true is returned, r holds the global coordinates of the 12219 * visible portion of this view. 12220 * @param globalOffset If true is returned, globalOffset holds the dx,dy 12221 * between this view and its root. globalOffet may be null. 12222 * @return true if r is non-empty (i.e. part of the view is visible at the 12223 * root level. 12224 */ 12225 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 12226 int width = mRight - mLeft; 12227 int height = mBottom - mTop; 12228 if (width > 0 && height > 0) { 12229 r.set(0, 0, width, height); 12230 if (globalOffset != null) { 12231 globalOffset.set(-mScrollX, -mScrollY); 12232 } 12233 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 12234 } 12235 return false; 12236 } 12237 12238 public final boolean getGlobalVisibleRect(Rect r) { 12239 return getGlobalVisibleRect(r, null); 12240 } 12241 12242 public final boolean getLocalVisibleRect(Rect r) { 12243 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 12244 if (getGlobalVisibleRect(r, offset)) { 12245 r.offset(-offset.x, -offset.y); // make r local 12246 return true; 12247 } 12248 return false; 12249 } 12250 12251 /** 12252 * Offset this view's vertical location by the specified number of pixels. 12253 * 12254 * @param offset the number of pixels to offset the view by 12255 */ 12256 public void offsetTopAndBottom(int offset) { 12257 if (offset != 0) { 12258 final boolean matrixIsIdentity = hasIdentityMatrix(); 12259 if (matrixIsIdentity) { 12260 if (isHardwareAccelerated()) { 12261 invalidateViewProperty(false, false); 12262 } else { 12263 final ViewParent p = mParent; 12264 if (p != null && mAttachInfo != null) { 12265 final Rect r = mAttachInfo.mTmpInvalRect; 12266 int minTop; 12267 int maxBottom; 12268 int yLoc; 12269 if (offset < 0) { 12270 minTop = mTop + offset; 12271 maxBottom = mBottom; 12272 yLoc = offset; 12273 } else { 12274 minTop = mTop; 12275 maxBottom = mBottom + offset; 12276 yLoc = 0; 12277 } 12278 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 12279 p.invalidateChild(this, r); 12280 } 12281 } 12282 } else { 12283 invalidateViewProperty(false, false); 12284 } 12285 12286 mTop += offset; 12287 mBottom += offset; 12288 mRenderNode.offsetTopAndBottom(offset); 12289 if (isHardwareAccelerated()) { 12290 invalidateViewProperty(false, false); 12291 } else { 12292 if (!matrixIsIdentity) { 12293 invalidateViewProperty(false, true); 12294 } 12295 invalidateParentIfNeeded(); 12296 } 12297 notifySubtreeAccessibilityStateChangedIfNeeded(); 12298 } 12299 } 12300 12301 /** 12302 * Offset this view's horizontal location by the specified amount of pixels. 12303 * 12304 * @param offset the number of pixels to offset the view by 12305 */ 12306 public void offsetLeftAndRight(int offset) { 12307 if (offset != 0) { 12308 final boolean matrixIsIdentity = hasIdentityMatrix(); 12309 if (matrixIsIdentity) { 12310 if (isHardwareAccelerated()) { 12311 invalidateViewProperty(false, false); 12312 } else { 12313 final ViewParent p = mParent; 12314 if (p != null && mAttachInfo != null) { 12315 final Rect r = mAttachInfo.mTmpInvalRect; 12316 int minLeft; 12317 int maxRight; 12318 if (offset < 0) { 12319 minLeft = mLeft + offset; 12320 maxRight = mRight; 12321 } else { 12322 minLeft = mLeft; 12323 maxRight = mRight + offset; 12324 } 12325 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 12326 p.invalidateChild(this, r); 12327 } 12328 } 12329 } else { 12330 invalidateViewProperty(false, false); 12331 } 12332 12333 mLeft += offset; 12334 mRight += offset; 12335 mRenderNode.offsetLeftAndRight(offset); 12336 if (isHardwareAccelerated()) { 12337 invalidateViewProperty(false, false); 12338 } else { 12339 if (!matrixIsIdentity) { 12340 invalidateViewProperty(false, true); 12341 } 12342 invalidateParentIfNeeded(); 12343 } 12344 notifySubtreeAccessibilityStateChangedIfNeeded(); 12345 } 12346 } 12347 12348 /** 12349 * Get the LayoutParams associated with this view. All views should have 12350 * layout parameters. These supply parameters to the <i>parent</i> of this 12351 * view specifying how it should be arranged. There are many subclasses of 12352 * ViewGroup.LayoutParams, and these correspond to the different subclasses 12353 * of ViewGroup that are responsible for arranging their children. 12354 * 12355 * This method may return null if this View is not attached to a parent 12356 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 12357 * was not invoked successfully. When a View is attached to a parent 12358 * ViewGroup, this method must not return null. 12359 * 12360 * @return The LayoutParams associated with this view, or null if no 12361 * parameters have been set yet 12362 */ 12363 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 12364 public ViewGroup.LayoutParams getLayoutParams() { 12365 return mLayoutParams; 12366 } 12367 12368 /** 12369 * Set the layout parameters associated with this view. These supply 12370 * parameters to the <i>parent</i> of this view specifying how it should be 12371 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 12372 * correspond to the different subclasses of ViewGroup that are responsible 12373 * for arranging their children. 12374 * 12375 * @param params The layout parameters for this view, cannot be null 12376 */ 12377 public void setLayoutParams(ViewGroup.LayoutParams params) { 12378 if (params == null) { 12379 throw new NullPointerException("Layout parameters cannot be null"); 12380 } 12381 mLayoutParams = params; 12382 resolveLayoutParams(); 12383 if (mParent instanceof ViewGroup) { 12384 ((ViewGroup) mParent).onSetLayoutParams(this, params); 12385 } 12386 requestLayout(); 12387 } 12388 12389 /** 12390 * Resolve the layout parameters depending on the resolved layout direction 12391 * 12392 * @hide 12393 */ 12394 public void resolveLayoutParams() { 12395 if (mLayoutParams != null) { 12396 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 12397 } 12398 } 12399 12400 /** 12401 * Set the scrolled position of your view. This will cause a call to 12402 * {@link #onScrollChanged(int, int, int, int)} and the view will be 12403 * invalidated. 12404 * @param x the x position to scroll to 12405 * @param y the y position to scroll to 12406 */ 12407 public void scrollTo(int x, int y) { 12408 if (mScrollX != x || mScrollY != y) { 12409 int oldX = mScrollX; 12410 int oldY = mScrollY; 12411 mScrollX = x; 12412 mScrollY = y; 12413 invalidateParentCaches(); 12414 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 12415 if (!awakenScrollBars()) { 12416 postInvalidateOnAnimation(); 12417 } 12418 } 12419 } 12420 12421 /** 12422 * Move the scrolled position of your view. This will cause a call to 12423 * {@link #onScrollChanged(int, int, int, int)} and the view will be 12424 * invalidated. 12425 * @param x the amount of pixels to scroll by horizontally 12426 * @param y the amount of pixels to scroll by vertically 12427 */ 12428 public void scrollBy(int x, int y) { 12429 scrollTo(mScrollX + x, mScrollY + y); 12430 } 12431 12432 /** 12433 * <p>Trigger the scrollbars to draw. When invoked this method starts an 12434 * animation to fade the scrollbars out after a default delay. If a subclass 12435 * provides animated scrolling, the start delay should equal the duration 12436 * of the scrolling animation.</p> 12437 * 12438 * <p>The animation starts only if at least one of the scrollbars is 12439 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 12440 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 12441 * this method returns true, and false otherwise. If the animation is 12442 * started, this method calls {@link #invalidate()}; in that case the 12443 * caller should not call {@link #invalidate()}.</p> 12444 * 12445 * <p>This method should be invoked every time a subclass directly updates 12446 * the scroll parameters.</p> 12447 * 12448 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 12449 * and {@link #scrollTo(int, int)}.</p> 12450 * 12451 * @return true if the animation is played, false otherwise 12452 * 12453 * @see #awakenScrollBars(int) 12454 * @see #scrollBy(int, int) 12455 * @see #scrollTo(int, int) 12456 * @see #isHorizontalScrollBarEnabled() 12457 * @see #isVerticalScrollBarEnabled() 12458 * @see #setHorizontalScrollBarEnabled(boolean) 12459 * @see #setVerticalScrollBarEnabled(boolean) 12460 */ 12461 protected boolean awakenScrollBars() { 12462 return mScrollCache != null && 12463 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 12464 } 12465 12466 /** 12467 * Trigger the scrollbars to draw. 12468 * This method differs from awakenScrollBars() only in its default duration. 12469 * initialAwakenScrollBars() will show the scroll bars for longer than 12470 * usual to give the user more of a chance to notice them. 12471 * 12472 * @return true if the animation is played, false otherwise. 12473 */ 12474 private boolean initialAwakenScrollBars() { 12475 return mScrollCache != null && 12476 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 12477 } 12478 12479 /** 12480 * <p> 12481 * Trigger the scrollbars to draw. When invoked this method starts an 12482 * animation to fade the scrollbars out after a fixed delay. If a subclass 12483 * provides animated scrolling, the start delay should equal the duration of 12484 * the scrolling animation. 12485 * </p> 12486 * 12487 * <p> 12488 * The animation starts only if at least one of the scrollbars is enabled, 12489 * as specified by {@link #isHorizontalScrollBarEnabled()} and 12490 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 12491 * this method returns true, and false otherwise. If the animation is 12492 * started, this method calls {@link #invalidate()}; in that case the caller 12493 * should not call {@link #invalidate()}. 12494 * </p> 12495 * 12496 * <p> 12497 * This method should be invoked every time a subclass directly updates the 12498 * scroll parameters. 12499 * </p> 12500 * 12501 * @param startDelay the delay, in milliseconds, after which the animation 12502 * should start; when the delay is 0, the animation starts 12503 * immediately 12504 * @return true if the animation is played, false otherwise 12505 * 12506 * @see #scrollBy(int, int) 12507 * @see #scrollTo(int, int) 12508 * @see #isHorizontalScrollBarEnabled() 12509 * @see #isVerticalScrollBarEnabled() 12510 * @see #setHorizontalScrollBarEnabled(boolean) 12511 * @see #setVerticalScrollBarEnabled(boolean) 12512 */ 12513 protected boolean awakenScrollBars(int startDelay) { 12514 return awakenScrollBars(startDelay, true); 12515 } 12516 12517 /** 12518 * <p> 12519 * Trigger the scrollbars to draw. When invoked this method starts an 12520 * animation to fade the scrollbars out after a fixed delay. If a subclass 12521 * provides animated scrolling, the start delay should equal the duration of 12522 * the scrolling animation. 12523 * </p> 12524 * 12525 * <p> 12526 * The animation starts only if at least one of the scrollbars is enabled, 12527 * as specified by {@link #isHorizontalScrollBarEnabled()} and 12528 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 12529 * this method returns true, and false otherwise. If the animation is 12530 * started, this method calls {@link #invalidate()} if the invalidate parameter 12531 * is set to true; in that case the caller 12532 * should not call {@link #invalidate()}. 12533 * </p> 12534 * 12535 * <p> 12536 * This method should be invoked every time a subclass directly updates the 12537 * scroll parameters. 12538 * </p> 12539 * 12540 * @param startDelay the delay, in milliseconds, after which the animation 12541 * should start; when the delay is 0, the animation starts 12542 * immediately 12543 * 12544 * @param invalidate Whether this method should call invalidate 12545 * 12546 * @return true if the animation is played, false otherwise 12547 * 12548 * @see #scrollBy(int, int) 12549 * @see #scrollTo(int, int) 12550 * @see #isHorizontalScrollBarEnabled() 12551 * @see #isVerticalScrollBarEnabled() 12552 * @see #setHorizontalScrollBarEnabled(boolean) 12553 * @see #setVerticalScrollBarEnabled(boolean) 12554 */ 12555 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 12556 final ScrollabilityCache scrollCache = mScrollCache; 12557 12558 if (scrollCache == null || !scrollCache.fadeScrollBars) { 12559 return false; 12560 } 12561 12562 if (scrollCache.scrollBar == null) { 12563 scrollCache.scrollBar = new ScrollBarDrawable(); 12564 scrollCache.scrollBar.setCallback(this); 12565 scrollCache.scrollBar.setState(getDrawableState()); 12566 } 12567 12568 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 12569 12570 if (invalidate) { 12571 // Invalidate to show the scrollbars 12572 postInvalidateOnAnimation(); 12573 } 12574 12575 if (scrollCache.state == ScrollabilityCache.OFF) { 12576 // FIXME: this is copied from WindowManagerService. 12577 // We should get this value from the system when it 12578 // is possible to do so. 12579 final int KEY_REPEAT_FIRST_DELAY = 750; 12580 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 12581 } 12582 12583 // Tell mScrollCache when we should start fading. This may 12584 // extend the fade start time if one was already scheduled 12585 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 12586 scrollCache.fadeStartTime = fadeStartTime; 12587 scrollCache.state = ScrollabilityCache.ON; 12588 12589 // Schedule our fader to run, unscheduling any old ones first 12590 if (mAttachInfo != null) { 12591 mAttachInfo.mHandler.removeCallbacks(scrollCache); 12592 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 12593 } 12594 12595 return true; 12596 } 12597 12598 return false; 12599 } 12600 12601 /** 12602 * Do not invalidate views which are not visible and which are not running an animation. They 12603 * will not get drawn and they should not set dirty flags as if they will be drawn 12604 */ 12605 private boolean skipInvalidate() { 12606 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 12607 (!(mParent instanceof ViewGroup) || 12608 !((ViewGroup) mParent).isViewTransitioning(this)); 12609 } 12610 12611 /** 12612 * Mark the area defined by dirty as needing to be drawn. If the view is 12613 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 12614 * point in the future. 12615 * <p> 12616 * This must be called from a UI thread. To call from a non-UI thread, call 12617 * {@link #postInvalidate()}. 12618 * <p> 12619 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 12620 * {@code dirty}. 12621 * 12622 * @param dirty the rectangle representing the bounds of the dirty region 12623 */ 12624 public void invalidate(Rect dirty) { 12625 final int scrollX = mScrollX; 12626 final int scrollY = mScrollY; 12627 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 12628 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 12629 } 12630 12631 /** 12632 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 12633 * coordinates of the dirty rect are relative to the view. If the view is 12634 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 12635 * point in the future. 12636 * <p> 12637 * This must be called from a UI thread. To call from a non-UI thread, call 12638 * {@link #postInvalidate()}. 12639 * 12640 * @param l the left position of the dirty region 12641 * @param t the top position of the dirty region 12642 * @param r the right position of the dirty region 12643 * @param b the bottom position of the dirty region 12644 */ 12645 public void invalidate(int l, int t, int r, int b) { 12646 final int scrollX = mScrollX; 12647 final int scrollY = mScrollY; 12648 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 12649 } 12650 12651 /** 12652 * Invalidate the whole view. If the view is visible, 12653 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 12654 * the future. 12655 * <p> 12656 * This must be called from a UI thread. To call from a non-UI thread, call 12657 * {@link #postInvalidate()}. 12658 */ 12659 public void invalidate() { 12660 invalidate(true); 12661 } 12662 12663 /** 12664 * This is where the invalidate() work actually happens. A full invalidate() 12665 * causes the drawing cache to be invalidated, but this function can be 12666 * called with invalidateCache set to false to skip that invalidation step 12667 * for cases that do not need it (for example, a component that remains at 12668 * the same dimensions with the same content). 12669 * 12670 * @param invalidateCache Whether the drawing cache for this view should be 12671 * invalidated as well. This is usually true for a full 12672 * invalidate, but may be set to false if the View's contents or 12673 * dimensions have not changed. 12674 */ 12675 void invalidate(boolean invalidateCache) { 12676 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 12677 } 12678 12679 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 12680 boolean fullInvalidate) { 12681 if (mGhostView != null) { 12682 mGhostView.invalidate(true); 12683 return; 12684 } 12685 12686 if (skipInvalidate()) { 12687 return; 12688 } 12689 12690 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 12691 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 12692 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 12693 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 12694 if (fullInvalidate) { 12695 mLastIsOpaque = isOpaque(); 12696 mPrivateFlags &= ~PFLAG_DRAWN; 12697 } 12698 12699 mPrivateFlags |= PFLAG_DIRTY; 12700 12701 if (invalidateCache) { 12702 mPrivateFlags |= PFLAG_INVALIDATED; 12703 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12704 } 12705 12706 // Propagate the damage rectangle to the parent view. 12707 final AttachInfo ai = mAttachInfo; 12708 final ViewParent p = mParent; 12709 if (p != null && ai != null && l < r && t < b) { 12710 final Rect damage = ai.mTmpInvalRect; 12711 damage.set(l, t, r, b); 12712 p.invalidateChild(this, damage); 12713 } 12714 12715 // Damage the entire projection receiver, if necessary. 12716 if (mBackground != null && mBackground.isProjected()) { 12717 final View receiver = getProjectionReceiver(); 12718 if (receiver != null) { 12719 receiver.damageInParent(); 12720 } 12721 } 12722 12723 // Damage the entire IsolatedZVolume receiving this view's shadow. 12724 if (isHardwareAccelerated() && getZ() != 0) { 12725 damageShadowReceiver(); 12726 } 12727 } 12728 } 12729 12730 /** 12731 * @return this view's projection receiver, or {@code null} if none exists 12732 */ 12733 private View getProjectionReceiver() { 12734 ViewParent p = getParent(); 12735 while (p != null && p instanceof View) { 12736 final View v = (View) p; 12737 if (v.isProjectionReceiver()) { 12738 return v; 12739 } 12740 p = p.getParent(); 12741 } 12742 12743 return null; 12744 } 12745 12746 /** 12747 * @return whether the view is a projection receiver 12748 */ 12749 private boolean isProjectionReceiver() { 12750 return mBackground != null; 12751 } 12752 12753 /** 12754 * Damage area of the screen that can be covered by this View's shadow. 12755 * 12756 * This method will guarantee that any changes to shadows cast by a View 12757 * are damaged on the screen for future redraw. 12758 */ 12759 private void damageShadowReceiver() { 12760 final AttachInfo ai = mAttachInfo; 12761 if (ai != null) { 12762 ViewParent p = getParent(); 12763 if (p != null && p instanceof ViewGroup) { 12764 final ViewGroup vg = (ViewGroup) p; 12765 vg.damageInParent(); 12766 } 12767 } 12768 } 12769 12770 /** 12771 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 12772 * set any flags or handle all of the cases handled by the default invalidation methods. 12773 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 12774 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 12775 * walk up the hierarchy, transforming the dirty rect as necessary. 12776 * 12777 * The method also handles normal invalidation logic if display list properties are not 12778 * being used in this view. The invalidateParent and forceRedraw flags are used by that 12779 * backup approach, to handle these cases used in the various property-setting methods. 12780 * 12781 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 12782 * are not being used in this view 12783 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 12784 * list properties are not being used in this view 12785 */ 12786 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 12787 if (!isHardwareAccelerated() 12788 || !mRenderNode.isValid() 12789 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 12790 if (invalidateParent) { 12791 invalidateParentCaches(); 12792 } 12793 if (forceRedraw) { 12794 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12795 } 12796 invalidate(false); 12797 } else { 12798 damageInParent(); 12799 } 12800 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 12801 damageShadowReceiver(); 12802 } 12803 } 12804 12805 /** 12806 * Tells the parent view to damage this view's bounds. 12807 * 12808 * @hide 12809 */ 12810 protected void damageInParent() { 12811 final AttachInfo ai = mAttachInfo; 12812 final ViewParent p = mParent; 12813 if (p != null && ai != null) { 12814 final Rect r = ai.mTmpInvalRect; 12815 r.set(0, 0, mRight - mLeft, mBottom - mTop); 12816 if (mParent instanceof ViewGroup) { 12817 ((ViewGroup) mParent).damageChild(this, r); 12818 } else { 12819 mParent.invalidateChild(this, r); 12820 } 12821 } 12822 } 12823 12824 /** 12825 * Utility method to transform a given Rect by the current matrix of this view. 12826 */ 12827 void transformRect(final Rect rect) { 12828 if (!getMatrix().isIdentity()) { 12829 RectF boundingRect = mAttachInfo.mTmpTransformRect; 12830 boundingRect.set(rect); 12831 getMatrix().mapRect(boundingRect); 12832 rect.set((int) Math.floor(boundingRect.left), 12833 (int) Math.floor(boundingRect.top), 12834 (int) Math.ceil(boundingRect.right), 12835 (int) Math.ceil(boundingRect.bottom)); 12836 } 12837 } 12838 12839 /** 12840 * Used to indicate that the parent of this view should clear its caches. This functionality 12841 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12842 * which is necessary when various parent-managed properties of the view change, such as 12843 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 12844 * clears the parent caches and does not causes an invalidate event. 12845 * 12846 * @hide 12847 */ 12848 protected void invalidateParentCaches() { 12849 if (mParent instanceof View) { 12850 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 12851 } 12852 } 12853 12854 /** 12855 * Used to indicate that the parent of this view should be invalidated. This functionality 12856 * is used to force the parent to rebuild its display list (when hardware-accelerated), 12857 * which is necessary when various parent-managed properties of the view change, such as 12858 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 12859 * an invalidation event to the parent. 12860 * 12861 * @hide 12862 */ 12863 protected void invalidateParentIfNeeded() { 12864 if (isHardwareAccelerated() && mParent instanceof View) { 12865 ((View) mParent).invalidate(true); 12866 } 12867 } 12868 12869 /** 12870 * @hide 12871 */ 12872 protected void invalidateParentIfNeededAndWasQuickRejected() { 12873 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 12874 // View was rejected last time it was drawn by its parent; this may have changed 12875 invalidateParentIfNeeded(); 12876 } 12877 } 12878 12879 /** 12880 * Indicates whether this View is opaque. An opaque View guarantees that it will 12881 * draw all the pixels overlapping its bounds using a fully opaque color. 12882 * 12883 * Subclasses of View should override this method whenever possible to indicate 12884 * whether an instance is opaque. Opaque Views are treated in a special way by 12885 * the View hierarchy, possibly allowing it to perform optimizations during 12886 * invalidate/draw passes. 12887 * 12888 * @return True if this View is guaranteed to be fully opaque, false otherwise. 12889 */ 12890 @ViewDebug.ExportedProperty(category = "drawing") 12891 public boolean isOpaque() { 12892 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 12893 getFinalAlpha() >= 1.0f; 12894 } 12895 12896 /** 12897 * @hide 12898 */ 12899 protected void computeOpaqueFlags() { 12900 // Opaque if: 12901 // - Has a background 12902 // - Background is opaque 12903 // - Doesn't have scrollbars or scrollbars overlay 12904 12905 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 12906 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 12907 } else { 12908 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 12909 } 12910 12911 final int flags = mViewFlags; 12912 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 12913 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 12914 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 12915 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 12916 } else { 12917 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 12918 } 12919 } 12920 12921 /** 12922 * @hide 12923 */ 12924 protected boolean hasOpaqueScrollbars() { 12925 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 12926 } 12927 12928 /** 12929 * @return A handler associated with the thread running the View. This 12930 * handler can be used to pump events in the UI events queue. 12931 */ 12932 public Handler getHandler() { 12933 final AttachInfo attachInfo = mAttachInfo; 12934 if (attachInfo != null) { 12935 return attachInfo.mHandler; 12936 } 12937 return null; 12938 } 12939 12940 /** 12941 * Gets the view root associated with the View. 12942 * @return The view root, or null if none. 12943 * @hide 12944 */ 12945 public ViewRootImpl getViewRootImpl() { 12946 if (mAttachInfo != null) { 12947 return mAttachInfo.mViewRootImpl; 12948 } 12949 return null; 12950 } 12951 12952 /** 12953 * @hide 12954 */ 12955 public HardwareRenderer getHardwareRenderer() { 12956 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 12957 } 12958 12959 /** 12960 * <p>Causes the Runnable to be added to the message queue. 12961 * The runnable will be run on the user interface thread.</p> 12962 * 12963 * @param action The Runnable that will be executed. 12964 * 12965 * @return Returns true if the Runnable was successfully placed in to the 12966 * message queue. Returns false on failure, usually because the 12967 * looper processing the message queue is exiting. 12968 * 12969 * @see #postDelayed 12970 * @see #removeCallbacks 12971 */ 12972 public boolean post(Runnable action) { 12973 final AttachInfo attachInfo = mAttachInfo; 12974 if (attachInfo != null) { 12975 return attachInfo.mHandler.post(action); 12976 } 12977 // Assume that post will succeed later 12978 ViewRootImpl.getRunQueue().post(action); 12979 return true; 12980 } 12981 12982 /** 12983 * <p>Causes the Runnable to be added to the message queue, to be run 12984 * after the specified amount of time elapses. 12985 * The runnable will be run on the user interface thread.</p> 12986 * 12987 * @param action The Runnable that will be executed. 12988 * @param delayMillis The delay (in milliseconds) until the Runnable 12989 * will be executed. 12990 * 12991 * @return true if the Runnable was successfully placed in to the 12992 * message queue. Returns false on failure, usually because the 12993 * looper processing the message queue is exiting. Note that a 12994 * result of true does not mean the Runnable will be processed -- 12995 * if the looper is quit before the delivery time of the message 12996 * occurs then the message will be dropped. 12997 * 12998 * @see #post 12999 * @see #removeCallbacks 13000 */ 13001 public boolean postDelayed(Runnable action, long delayMillis) { 13002 final AttachInfo attachInfo = mAttachInfo; 13003 if (attachInfo != null) { 13004 return attachInfo.mHandler.postDelayed(action, delayMillis); 13005 } 13006 // Assume that post will succeed later 13007 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 13008 return true; 13009 } 13010 13011 /** 13012 * <p>Causes the Runnable to execute on the next animation time step. 13013 * The runnable will be run on the user interface thread.</p> 13014 * 13015 * @param action The Runnable that will be executed. 13016 * 13017 * @see #postOnAnimationDelayed 13018 * @see #removeCallbacks 13019 */ 13020 public void postOnAnimation(Runnable action) { 13021 final AttachInfo attachInfo = mAttachInfo; 13022 if (attachInfo != null) { 13023 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13024 Choreographer.CALLBACK_ANIMATION, action, null); 13025 } else { 13026 // Assume that post will succeed later 13027 ViewRootImpl.getRunQueue().post(action); 13028 } 13029 } 13030 13031 /** 13032 * <p>Causes the Runnable to execute on the next animation time step, 13033 * after the specified amount of time elapses. 13034 * The runnable will be run on the user interface thread.</p> 13035 * 13036 * @param action The Runnable that will be executed. 13037 * @param delayMillis The delay (in milliseconds) until the Runnable 13038 * will be executed. 13039 * 13040 * @see #postOnAnimation 13041 * @see #removeCallbacks 13042 */ 13043 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13044 final AttachInfo attachInfo = mAttachInfo; 13045 if (attachInfo != null) { 13046 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13047 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 13048 } else { 13049 // Assume that post will succeed later 13050 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 13051 } 13052 } 13053 13054 /** 13055 * <p>Removes the specified Runnable from the message queue.</p> 13056 * 13057 * @param action The Runnable to remove from the message handling queue 13058 * 13059 * @return true if this view could ask the Handler to remove the Runnable, 13060 * false otherwise. When the returned value is true, the Runnable 13061 * may or may not have been actually removed from the message queue 13062 * (for instance, if the Runnable was not in the queue already.) 13063 * 13064 * @see #post 13065 * @see #postDelayed 13066 * @see #postOnAnimation 13067 * @see #postOnAnimationDelayed 13068 */ 13069 public boolean removeCallbacks(Runnable action) { 13070 if (action != null) { 13071 final AttachInfo attachInfo = mAttachInfo; 13072 if (attachInfo != null) { 13073 attachInfo.mHandler.removeCallbacks(action); 13074 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13075 Choreographer.CALLBACK_ANIMATION, action, null); 13076 } 13077 // Assume that post will succeed later 13078 ViewRootImpl.getRunQueue().removeCallbacks(action); 13079 } 13080 return true; 13081 } 13082 13083 /** 13084 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 13085 * Use this to invalidate the View from a non-UI thread.</p> 13086 * 13087 * <p>This method can be invoked from outside of the UI thread 13088 * only when this View is attached to a window.</p> 13089 * 13090 * @see #invalidate() 13091 * @see #postInvalidateDelayed(long) 13092 */ 13093 public void postInvalidate() { 13094 postInvalidateDelayed(0); 13095 } 13096 13097 /** 13098 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13099 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 13100 * 13101 * <p>This method can be invoked from outside of the UI thread 13102 * only when this View is attached to a window.</p> 13103 * 13104 * @param left The left coordinate of the rectangle to invalidate. 13105 * @param top The top coordinate of the rectangle to invalidate. 13106 * @param right The right coordinate of the rectangle to invalidate. 13107 * @param bottom The bottom coordinate of the rectangle to invalidate. 13108 * 13109 * @see #invalidate(int, int, int, int) 13110 * @see #invalidate(Rect) 13111 * @see #postInvalidateDelayed(long, int, int, int, int) 13112 */ 13113 public void postInvalidate(int left, int top, int right, int bottom) { 13114 postInvalidateDelayed(0, left, top, right, bottom); 13115 } 13116 13117 /** 13118 * <p>Cause an invalidate to happen on a subsequent cycle through the event 13119 * loop. Waits for the specified amount of time.</p> 13120 * 13121 * <p>This method can be invoked from outside of the UI thread 13122 * only when this View is attached to a window.</p> 13123 * 13124 * @param delayMilliseconds the duration in milliseconds to delay the 13125 * invalidation by 13126 * 13127 * @see #invalidate() 13128 * @see #postInvalidate() 13129 */ 13130 public void postInvalidateDelayed(long delayMilliseconds) { 13131 // We try only with the AttachInfo because there's no point in invalidating 13132 // if we are not attached to our window 13133 final AttachInfo attachInfo = mAttachInfo; 13134 if (attachInfo != null) { 13135 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 13136 } 13137 } 13138 13139 /** 13140 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13141 * through the event loop. Waits for the specified amount of time.</p> 13142 * 13143 * <p>This method can be invoked from outside of the UI thread 13144 * only when this View is attached to a window.</p> 13145 * 13146 * @param delayMilliseconds the duration in milliseconds to delay the 13147 * invalidation by 13148 * @param left The left coordinate of the rectangle to invalidate. 13149 * @param top The top coordinate of the rectangle to invalidate. 13150 * @param right The right coordinate of the rectangle to invalidate. 13151 * @param bottom The bottom coordinate of the rectangle to invalidate. 13152 * 13153 * @see #invalidate(int, int, int, int) 13154 * @see #invalidate(Rect) 13155 * @see #postInvalidate(int, int, int, int) 13156 */ 13157 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 13158 int right, int bottom) { 13159 13160 // We try only with the AttachInfo because there's no point in invalidating 13161 // if we are not attached to our window 13162 final AttachInfo attachInfo = mAttachInfo; 13163 if (attachInfo != null) { 13164 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13165 info.target = this; 13166 info.left = left; 13167 info.top = top; 13168 info.right = right; 13169 info.bottom = bottom; 13170 13171 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 13172 } 13173 } 13174 13175 /** 13176 * <p>Cause an invalidate to happen on the next animation time step, typically the 13177 * next display frame.</p> 13178 * 13179 * <p>This method can be invoked from outside of the UI thread 13180 * only when this View is attached to a window.</p> 13181 * 13182 * @see #invalidate() 13183 */ 13184 public void postInvalidateOnAnimation() { 13185 // We try only with the AttachInfo because there's no point in invalidating 13186 // if we are not attached to our window 13187 final AttachInfo attachInfo = mAttachInfo; 13188 if (attachInfo != null) { 13189 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 13190 } 13191 } 13192 13193 /** 13194 * <p>Cause an invalidate of the specified area to happen on the next animation 13195 * time step, typically the next display frame.</p> 13196 * 13197 * <p>This method can be invoked from outside of the UI thread 13198 * only when this View is attached to a window.</p> 13199 * 13200 * @param left The left coordinate of the rectangle to invalidate. 13201 * @param top The top coordinate of the rectangle to invalidate. 13202 * @param right The right coordinate of the rectangle to invalidate. 13203 * @param bottom The bottom coordinate of the rectangle to invalidate. 13204 * 13205 * @see #invalidate(int, int, int, int) 13206 * @see #invalidate(Rect) 13207 */ 13208 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 13209 // We try only with the AttachInfo because there's no point in invalidating 13210 // if we are not attached to our window 13211 final AttachInfo attachInfo = mAttachInfo; 13212 if (attachInfo != null) { 13213 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13214 info.target = this; 13215 info.left = left; 13216 info.top = top; 13217 info.right = right; 13218 info.bottom = bottom; 13219 13220 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 13221 } 13222 } 13223 13224 /** 13225 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 13226 * This event is sent at most once every 13227 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 13228 */ 13229 private void postSendViewScrolledAccessibilityEventCallback() { 13230 if (mSendViewScrolledAccessibilityEvent == null) { 13231 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 13232 } 13233 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 13234 mSendViewScrolledAccessibilityEvent.mIsPending = true; 13235 postDelayed(mSendViewScrolledAccessibilityEvent, 13236 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 13237 } 13238 } 13239 13240 /** 13241 * Called by a parent to request that a child update its values for mScrollX 13242 * and mScrollY if necessary. This will typically be done if the child is 13243 * animating a scroll using a {@link android.widget.Scroller Scroller} 13244 * object. 13245 */ 13246 public void computeScroll() { 13247 } 13248 13249 /** 13250 * <p>Indicate whether the horizontal edges are faded when the view is 13251 * scrolled horizontally.</p> 13252 * 13253 * @return true if the horizontal edges should are faded on scroll, false 13254 * otherwise 13255 * 13256 * @see #setHorizontalFadingEdgeEnabled(boolean) 13257 * 13258 * @attr ref android.R.styleable#View_requiresFadingEdge 13259 */ 13260 public boolean isHorizontalFadingEdgeEnabled() { 13261 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 13262 } 13263 13264 /** 13265 * <p>Define whether the horizontal edges should be faded when this view 13266 * is scrolled horizontally.</p> 13267 * 13268 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 13269 * be faded when the view is scrolled 13270 * horizontally 13271 * 13272 * @see #isHorizontalFadingEdgeEnabled() 13273 * 13274 * @attr ref android.R.styleable#View_requiresFadingEdge 13275 */ 13276 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 13277 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 13278 if (horizontalFadingEdgeEnabled) { 13279 initScrollCache(); 13280 } 13281 13282 mViewFlags ^= FADING_EDGE_HORIZONTAL; 13283 } 13284 } 13285 13286 /** 13287 * <p>Indicate whether the vertical edges are faded when the view is 13288 * scrolled horizontally.</p> 13289 * 13290 * @return true if the vertical edges should are faded on scroll, false 13291 * otherwise 13292 * 13293 * @see #setVerticalFadingEdgeEnabled(boolean) 13294 * 13295 * @attr ref android.R.styleable#View_requiresFadingEdge 13296 */ 13297 public boolean isVerticalFadingEdgeEnabled() { 13298 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 13299 } 13300 13301 /** 13302 * <p>Define whether the vertical edges should be faded when this view 13303 * is scrolled vertically.</p> 13304 * 13305 * @param verticalFadingEdgeEnabled true if the vertical edges should 13306 * be faded when the view is scrolled 13307 * vertically 13308 * 13309 * @see #isVerticalFadingEdgeEnabled() 13310 * 13311 * @attr ref android.R.styleable#View_requiresFadingEdge 13312 */ 13313 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 13314 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 13315 if (verticalFadingEdgeEnabled) { 13316 initScrollCache(); 13317 } 13318 13319 mViewFlags ^= FADING_EDGE_VERTICAL; 13320 } 13321 } 13322 13323 /** 13324 * Returns the strength, or intensity, of the top faded edge. The strength is 13325 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13326 * returns 0.0 or 1.0 but no value in between. 13327 * 13328 * Subclasses should override this method to provide a smoother fade transition 13329 * when scrolling occurs. 13330 * 13331 * @return the intensity of the top fade as a float between 0.0f and 1.0f 13332 */ 13333 protected float getTopFadingEdgeStrength() { 13334 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 13335 } 13336 13337 /** 13338 * Returns the strength, or intensity, of the bottom faded edge. The strength is 13339 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13340 * returns 0.0 or 1.0 but no value in between. 13341 * 13342 * Subclasses should override this method to provide a smoother fade transition 13343 * when scrolling occurs. 13344 * 13345 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 13346 */ 13347 protected float getBottomFadingEdgeStrength() { 13348 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 13349 computeVerticalScrollRange() ? 1.0f : 0.0f; 13350 } 13351 13352 /** 13353 * Returns the strength, or intensity, of the left faded edge. The strength is 13354 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13355 * returns 0.0 or 1.0 but no value in between. 13356 * 13357 * Subclasses should override this method to provide a smoother fade transition 13358 * when scrolling occurs. 13359 * 13360 * @return the intensity of the left fade as a float between 0.0f and 1.0f 13361 */ 13362 protected float getLeftFadingEdgeStrength() { 13363 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 13364 } 13365 13366 /** 13367 * Returns the strength, or intensity, of the right faded edge. The strength is 13368 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 13369 * returns 0.0 or 1.0 but no value in between. 13370 * 13371 * Subclasses should override this method to provide a smoother fade transition 13372 * when scrolling occurs. 13373 * 13374 * @return the intensity of the right fade as a float between 0.0f and 1.0f 13375 */ 13376 protected float getRightFadingEdgeStrength() { 13377 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 13378 computeHorizontalScrollRange() ? 1.0f : 0.0f; 13379 } 13380 13381 /** 13382 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 13383 * scrollbar is not drawn by default.</p> 13384 * 13385 * @return true if the horizontal scrollbar should be painted, false 13386 * otherwise 13387 * 13388 * @see #setHorizontalScrollBarEnabled(boolean) 13389 */ 13390 public boolean isHorizontalScrollBarEnabled() { 13391 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 13392 } 13393 13394 /** 13395 * <p>Define whether the horizontal scrollbar should be drawn or not. The 13396 * scrollbar is not drawn by default.</p> 13397 * 13398 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 13399 * be painted 13400 * 13401 * @see #isHorizontalScrollBarEnabled() 13402 */ 13403 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 13404 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 13405 mViewFlags ^= SCROLLBARS_HORIZONTAL; 13406 computeOpaqueFlags(); 13407 resolvePadding(); 13408 } 13409 } 13410 13411 /** 13412 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 13413 * scrollbar is not drawn by default.</p> 13414 * 13415 * @return true if the vertical scrollbar should be painted, false 13416 * otherwise 13417 * 13418 * @see #setVerticalScrollBarEnabled(boolean) 13419 */ 13420 public boolean isVerticalScrollBarEnabled() { 13421 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 13422 } 13423 13424 /** 13425 * <p>Define whether the vertical scrollbar should be drawn or not. The 13426 * scrollbar is not drawn by default.</p> 13427 * 13428 * @param verticalScrollBarEnabled true if the vertical scrollbar should 13429 * be painted 13430 * 13431 * @see #isVerticalScrollBarEnabled() 13432 */ 13433 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 13434 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 13435 mViewFlags ^= SCROLLBARS_VERTICAL; 13436 computeOpaqueFlags(); 13437 resolvePadding(); 13438 } 13439 } 13440 13441 /** 13442 * @hide 13443 */ 13444 protected void recomputePadding() { 13445 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13446 } 13447 13448 /** 13449 * Define whether scrollbars will fade when the view is not scrolling. 13450 * 13451 * @param fadeScrollbars whether to enable fading 13452 * 13453 * @attr ref android.R.styleable#View_fadeScrollbars 13454 */ 13455 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 13456 initScrollCache(); 13457 final ScrollabilityCache scrollabilityCache = mScrollCache; 13458 scrollabilityCache.fadeScrollBars = fadeScrollbars; 13459 if (fadeScrollbars) { 13460 scrollabilityCache.state = ScrollabilityCache.OFF; 13461 } else { 13462 scrollabilityCache.state = ScrollabilityCache.ON; 13463 } 13464 } 13465 13466 /** 13467 * 13468 * Returns true if scrollbars will fade when this view is not scrolling 13469 * 13470 * @return true if scrollbar fading is enabled 13471 * 13472 * @attr ref android.R.styleable#View_fadeScrollbars 13473 */ 13474 public boolean isScrollbarFadingEnabled() { 13475 return mScrollCache != null && mScrollCache.fadeScrollBars; 13476 } 13477 13478 /** 13479 * 13480 * Returns the delay before scrollbars fade. 13481 * 13482 * @return the delay before scrollbars fade 13483 * 13484 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 13485 */ 13486 public int getScrollBarDefaultDelayBeforeFade() { 13487 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 13488 mScrollCache.scrollBarDefaultDelayBeforeFade; 13489 } 13490 13491 /** 13492 * Define the delay before scrollbars fade. 13493 * 13494 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 13495 * 13496 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 13497 */ 13498 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 13499 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 13500 } 13501 13502 /** 13503 * 13504 * Returns the scrollbar fade duration. 13505 * 13506 * @return the scrollbar fade duration 13507 * 13508 * @attr ref android.R.styleable#View_scrollbarFadeDuration 13509 */ 13510 public int getScrollBarFadeDuration() { 13511 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 13512 mScrollCache.scrollBarFadeDuration; 13513 } 13514 13515 /** 13516 * Define the scrollbar fade duration. 13517 * 13518 * @param scrollBarFadeDuration - the scrollbar fade duration 13519 * 13520 * @attr ref android.R.styleable#View_scrollbarFadeDuration 13521 */ 13522 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 13523 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 13524 } 13525 13526 /** 13527 * 13528 * Returns the scrollbar size. 13529 * 13530 * @return the scrollbar size 13531 * 13532 * @attr ref android.R.styleable#View_scrollbarSize 13533 */ 13534 public int getScrollBarSize() { 13535 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 13536 mScrollCache.scrollBarSize; 13537 } 13538 13539 /** 13540 * Define the scrollbar size. 13541 * 13542 * @param scrollBarSize - the scrollbar size 13543 * 13544 * @attr ref android.R.styleable#View_scrollbarSize 13545 */ 13546 public void setScrollBarSize(int scrollBarSize) { 13547 getScrollCache().scrollBarSize = scrollBarSize; 13548 } 13549 13550 /** 13551 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 13552 * inset. When inset, they add to the padding of the view. And the scrollbars 13553 * can be drawn inside the padding area or on the edge of the view. For example, 13554 * if a view has a background drawable and you want to draw the scrollbars 13555 * inside the padding specified by the drawable, you can use 13556 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 13557 * appear at the edge of the view, ignoring the padding, then you can use 13558 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 13559 * @param style the style of the scrollbars. Should be one of 13560 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 13561 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 13562 * @see #SCROLLBARS_INSIDE_OVERLAY 13563 * @see #SCROLLBARS_INSIDE_INSET 13564 * @see #SCROLLBARS_OUTSIDE_OVERLAY 13565 * @see #SCROLLBARS_OUTSIDE_INSET 13566 * 13567 * @attr ref android.R.styleable#View_scrollbarStyle 13568 */ 13569 public void setScrollBarStyle(@ScrollBarStyle int style) { 13570 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 13571 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 13572 computeOpaqueFlags(); 13573 resolvePadding(); 13574 } 13575 } 13576 13577 /** 13578 * <p>Returns the current scrollbar style.</p> 13579 * @return the current scrollbar style 13580 * @see #SCROLLBARS_INSIDE_OVERLAY 13581 * @see #SCROLLBARS_INSIDE_INSET 13582 * @see #SCROLLBARS_OUTSIDE_OVERLAY 13583 * @see #SCROLLBARS_OUTSIDE_INSET 13584 * 13585 * @attr ref android.R.styleable#View_scrollbarStyle 13586 */ 13587 @ViewDebug.ExportedProperty(mapping = { 13588 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 13589 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 13590 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 13591 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 13592 }) 13593 @ScrollBarStyle 13594 public int getScrollBarStyle() { 13595 return mViewFlags & SCROLLBARS_STYLE_MASK; 13596 } 13597 13598 /** 13599 * <p>Compute the horizontal range that the horizontal scrollbar 13600 * represents.</p> 13601 * 13602 * <p>The range is expressed in arbitrary units that must be the same as the 13603 * units used by {@link #computeHorizontalScrollExtent()} and 13604 * {@link #computeHorizontalScrollOffset()}.</p> 13605 * 13606 * <p>The default range is the drawing width of this view.</p> 13607 * 13608 * @return the total horizontal range represented by the horizontal 13609 * scrollbar 13610 * 13611 * @see #computeHorizontalScrollExtent() 13612 * @see #computeHorizontalScrollOffset() 13613 * @see android.widget.ScrollBarDrawable 13614 */ 13615 protected int computeHorizontalScrollRange() { 13616 return getWidth(); 13617 } 13618 13619 /** 13620 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 13621 * within the horizontal range. This value is used to compute the position 13622 * of the thumb within the scrollbar's track.</p> 13623 * 13624 * <p>The range is expressed in arbitrary units that must be the same as the 13625 * units used by {@link #computeHorizontalScrollRange()} and 13626 * {@link #computeHorizontalScrollExtent()}.</p> 13627 * 13628 * <p>The default offset is the scroll offset of this view.</p> 13629 * 13630 * @return the horizontal offset of the scrollbar's thumb 13631 * 13632 * @see #computeHorizontalScrollRange() 13633 * @see #computeHorizontalScrollExtent() 13634 * @see android.widget.ScrollBarDrawable 13635 */ 13636 protected int computeHorizontalScrollOffset() { 13637 return mScrollX; 13638 } 13639 13640 /** 13641 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 13642 * within the horizontal range. This value is used to compute the length 13643 * of the thumb within the scrollbar's track.</p> 13644 * 13645 * <p>The range is expressed in arbitrary units that must be the same as the 13646 * units used by {@link #computeHorizontalScrollRange()} and 13647 * {@link #computeHorizontalScrollOffset()}.</p> 13648 * 13649 * <p>The default extent is the drawing width of this view.</p> 13650 * 13651 * @return the horizontal extent of the scrollbar's thumb 13652 * 13653 * @see #computeHorizontalScrollRange() 13654 * @see #computeHorizontalScrollOffset() 13655 * @see android.widget.ScrollBarDrawable 13656 */ 13657 protected int computeHorizontalScrollExtent() { 13658 return getWidth(); 13659 } 13660 13661 /** 13662 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 13663 * 13664 * <p>The range is expressed in arbitrary units that must be the same as the 13665 * units used by {@link #computeVerticalScrollExtent()} and 13666 * {@link #computeVerticalScrollOffset()}.</p> 13667 * 13668 * @return the total vertical range represented by the vertical scrollbar 13669 * 13670 * <p>The default range is the drawing height of this view.</p> 13671 * 13672 * @see #computeVerticalScrollExtent() 13673 * @see #computeVerticalScrollOffset() 13674 * @see android.widget.ScrollBarDrawable 13675 */ 13676 protected int computeVerticalScrollRange() { 13677 return getHeight(); 13678 } 13679 13680 /** 13681 * <p>Compute the vertical offset of the vertical scrollbar's thumb 13682 * within the horizontal range. This value is used to compute the position 13683 * of the thumb within the scrollbar's track.</p> 13684 * 13685 * <p>The range is expressed in arbitrary units that must be the same as the 13686 * units used by {@link #computeVerticalScrollRange()} and 13687 * {@link #computeVerticalScrollExtent()}.</p> 13688 * 13689 * <p>The default offset is the scroll offset of this view.</p> 13690 * 13691 * @return the vertical offset of the scrollbar's thumb 13692 * 13693 * @see #computeVerticalScrollRange() 13694 * @see #computeVerticalScrollExtent() 13695 * @see android.widget.ScrollBarDrawable 13696 */ 13697 protected int computeVerticalScrollOffset() { 13698 return mScrollY; 13699 } 13700 13701 /** 13702 * <p>Compute the vertical extent of the vertical scrollbar's thumb 13703 * within the vertical range. This value is used to compute the length 13704 * of the thumb within the scrollbar's track.</p> 13705 * 13706 * <p>The range is expressed in arbitrary units that must be the same as the 13707 * units used by {@link #computeVerticalScrollRange()} and 13708 * {@link #computeVerticalScrollOffset()}.</p> 13709 * 13710 * <p>The default extent is the drawing height of this view.</p> 13711 * 13712 * @return the vertical extent of the scrollbar's thumb 13713 * 13714 * @see #computeVerticalScrollRange() 13715 * @see #computeVerticalScrollOffset() 13716 * @see android.widget.ScrollBarDrawable 13717 */ 13718 protected int computeVerticalScrollExtent() { 13719 return getHeight(); 13720 } 13721 13722 /** 13723 * Check if this view can be scrolled horizontally in a certain direction. 13724 * 13725 * @param direction Negative to check scrolling left, positive to check scrolling right. 13726 * @return true if this view can be scrolled in the specified direction, false otherwise. 13727 */ 13728 public boolean canScrollHorizontally(int direction) { 13729 final int offset = computeHorizontalScrollOffset(); 13730 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 13731 if (range == 0) return false; 13732 if (direction < 0) { 13733 return offset > 0; 13734 } else { 13735 return offset < range - 1; 13736 } 13737 } 13738 13739 /** 13740 * Check if this view can be scrolled vertically in a certain direction. 13741 * 13742 * @param direction Negative to check scrolling up, positive to check scrolling down. 13743 * @return true if this view can be scrolled in the specified direction, false otherwise. 13744 */ 13745 public boolean canScrollVertically(int direction) { 13746 final int offset = computeVerticalScrollOffset(); 13747 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 13748 if (range == 0) return false; 13749 if (direction < 0) { 13750 return offset > 0; 13751 } else { 13752 return offset < range - 1; 13753 } 13754 } 13755 13756 void getScrollIndicatorBounds(@NonNull Rect out) { 13757 out.left = mScrollX; 13758 out.right = mScrollX + mRight - mLeft; 13759 out.top = mScrollY; 13760 out.bottom = mScrollY + mBottom - mTop; 13761 } 13762 13763 private void onDrawScrollIndicators(Canvas c) { 13764 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 13765 // No scroll indicators enabled. 13766 return; 13767 } 13768 13769 final Drawable dr = mScrollIndicatorDrawable; 13770 if (dr == null) { 13771 // Scroll indicators aren't supported here. 13772 return; 13773 } 13774 13775 final int h = dr.getIntrinsicHeight(); 13776 final int w = dr.getIntrinsicWidth(); 13777 final Rect rect = mAttachInfo.mTmpInvalRect; 13778 getScrollIndicatorBounds(rect); 13779 13780 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 13781 final boolean canScrollUp = canScrollVertically(-1); 13782 if (canScrollUp) { 13783 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 13784 dr.draw(c); 13785 } 13786 } 13787 13788 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 13789 final boolean canScrollDown = canScrollVertically(1); 13790 if (canScrollDown) { 13791 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 13792 dr.draw(c); 13793 } 13794 } 13795 13796 final int leftRtl; 13797 final int rightRtl; 13798 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13799 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 13800 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 13801 } else { 13802 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 13803 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 13804 } 13805 13806 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 13807 if ((mPrivateFlags3 & leftMask) != 0) { 13808 final boolean canScrollLeft = canScrollHorizontally(-1); 13809 if (canScrollLeft) { 13810 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 13811 dr.draw(c); 13812 } 13813 } 13814 13815 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 13816 if ((mPrivateFlags3 & rightMask) != 0) { 13817 final boolean canScrollRight = canScrollHorizontally(1); 13818 if (canScrollRight) { 13819 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 13820 dr.draw(c); 13821 } 13822 } 13823 } 13824 13825 /** 13826 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 13827 * scrollbars are painted only if they have been awakened first.</p> 13828 * 13829 * @param canvas the canvas on which to draw the scrollbars 13830 * 13831 * @see #awakenScrollBars(int) 13832 */ 13833 protected final void onDrawScrollBars(Canvas canvas) { 13834 // scrollbars are drawn only when the animation is running 13835 final ScrollabilityCache cache = mScrollCache; 13836 if (cache != null) { 13837 13838 int state = cache.state; 13839 13840 if (state == ScrollabilityCache.OFF) { 13841 return; 13842 } 13843 13844 boolean invalidate = false; 13845 13846 if (state == ScrollabilityCache.FADING) { 13847 // We're fading -- get our fade interpolation 13848 if (cache.interpolatorValues == null) { 13849 cache.interpolatorValues = new float[1]; 13850 } 13851 13852 float[] values = cache.interpolatorValues; 13853 13854 // Stops the animation if we're done 13855 if (cache.scrollBarInterpolator.timeToValues(values) == 13856 Interpolator.Result.FREEZE_END) { 13857 cache.state = ScrollabilityCache.OFF; 13858 } else { 13859 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 13860 } 13861 13862 // This will make the scroll bars inval themselves after 13863 // drawing. We only want this when we're fading so that 13864 // we prevent excessive redraws 13865 invalidate = true; 13866 } else { 13867 // We're just on -- but we may have been fading before so 13868 // reset alpha 13869 cache.scrollBar.mutate().setAlpha(255); 13870 } 13871 13872 13873 final int viewFlags = mViewFlags; 13874 13875 final boolean drawHorizontalScrollBar = 13876 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 13877 final boolean drawVerticalScrollBar = 13878 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 13879 && !isVerticalScrollBarHidden(); 13880 13881 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 13882 final int width = mRight - mLeft; 13883 final int height = mBottom - mTop; 13884 13885 final ScrollBarDrawable scrollBar = cache.scrollBar; 13886 13887 final int scrollX = mScrollX; 13888 final int scrollY = mScrollY; 13889 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 13890 13891 int left; 13892 int top; 13893 int right; 13894 int bottom; 13895 13896 if (drawHorizontalScrollBar) { 13897 int size = scrollBar.getSize(false); 13898 if (size <= 0) { 13899 size = cache.scrollBarSize; 13900 } 13901 13902 scrollBar.setParameters(computeHorizontalScrollRange(), 13903 computeHorizontalScrollOffset(), 13904 computeHorizontalScrollExtent(), false); 13905 final int verticalScrollBarGap = drawVerticalScrollBar ? 13906 getVerticalScrollbarWidth() : 0; 13907 top = scrollY + height - size - (mUserPaddingBottom & inside); 13908 left = scrollX + (mPaddingLeft & inside); 13909 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 13910 bottom = top + size; 13911 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 13912 if (invalidate) { 13913 invalidate(left, top, right, bottom); 13914 } 13915 } 13916 13917 if (drawVerticalScrollBar) { 13918 int size = scrollBar.getSize(true); 13919 if (size <= 0) { 13920 size = cache.scrollBarSize; 13921 } 13922 13923 scrollBar.setParameters(computeVerticalScrollRange(), 13924 computeVerticalScrollOffset(), 13925 computeVerticalScrollExtent(), true); 13926 int verticalScrollbarPosition = mVerticalScrollbarPosition; 13927 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 13928 verticalScrollbarPosition = isLayoutRtl() ? 13929 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 13930 } 13931 switch (verticalScrollbarPosition) { 13932 default: 13933 case SCROLLBAR_POSITION_RIGHT: 13934 left = scrollX + width - size - (mUserPaddingRight & inside); 13935 break; 13936 case SCROLLBAR_POSITION_LEFT: 13937 left = scrollX + (mUserPaddingLeft & inside); 13938 break; 13939 } 13940 top = scrollY + (mPaddingTop & inside); 13941 right = left + size; 13942 bottom = scrollY + height - (mUserPaddingBottom & inside); 13943 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 13944 if (invalidate) { 13945 invalidate(left, top, right, bottom); 13946 } 13947 } 13948 } 13949 } 13950 } 13951 13952 /** 13953 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 13954 * FastScroller is visible. 13955 * @return whether to temporarily hide the vertical scrollbar 13956 * @hide 13957 */ 13958 protected boolean isVerticalScrollBarHidden() { 13959 return false; 13960 } 13961 13962 /** 13963 * <p>Draw the horizontal scrollbar if 13964 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 13965 * 13966 * @param canvas the canvas on which to draw the scrollbar 13967 * @param scrollBar the scrollbar's drawable 13968 * 13969 * @see #isHorizontalScrollBarEnabled() 13970 * @see #computeHorizontalScrollRange() 13971 * @see #computeHorizontalScrollExtent() 13972 * @see #computeHorizontalScrollOffset() 13973 * @see android.widget.ScrollBarDrawable 13974 * @hide 13975 */ 13976 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 13977 int l, int t, int r, int b) { 13978 scrollBar.setBounds(l, t, r, b); 13979 scrollBar.draw(canvas); 13980 } 13981 13982 /** 13983 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 13984 * returns true.</p> 13985 * 13986 * @param canvas the canvas on which to draw the scrollbar 13987 * @param scrollBar the scrollbar's drawable 13988 * 13989 * @see #isVerticalScrollBarEnabled() 13990 * @see #computeVerticalScrollRange() 13991 * @see #computeVerticalScrollExtent() 13992 * @see #computeVerticalScrollOffset() 13993 * @see android.widget.ScrollBarDrawable 13994 * @hide 13995 */ 13996 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 13997 int l, int t, int r, int b) { 13998 scrollBar.setBounds(l, t, r, b); 13999 scrollBar.draw(canvas); 14000 } 14001 14002 /** 14003 * Implement this to do your drawing. 14004 * 14005 * @param canvas the canvas on which the background will be drawn 14006 */ 14007 protected void onDraw(Canvas canvas) { 14008 } 14009 14010 /* 14011 * Caller is responsible for calling requestLayout if necessary. 14012 * (This allows addViewInLayout to not request a new layout.) 14013 */ 14014 void assignParent(ViewParent parent) { 14015 if (mParent == null) { 14016 mParent = parent; 14017 } else if (parent == null) { 14018 mParent = null; 14019 } else { 14020 throw new RuntimeException("view " + this + " being added, but" 14021 + " it already has a parent"); 14022 } 14023 } 14024 14025 /** 14026 * This is called when the view is attached to a window. At this point it 14027 * has a Surface and will start drawing. Note that this function is 14028 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 14029 * however it may be called any time before the first onDraw -- including 14030 * before or after {@link #onMeasure(int, int)}. 14031 * 14032 * @see #onDetachedFromWindow() 14033 */ 14034 @CallSuper 14035 protected void onAttachedToWindow() { 14036 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 14037 mParent.requestTransparentRegion(this); 14038 } 14039 14040 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14041 14042 jumpDrawablesToCurrentState(); 14043 14044 resetSubtreeAccessibilityStateChanged(); 14045 14046 // rebuild, since Outline not maintained while View is detached 14047 rebuildOutline(); 14048 14049 if (isFocused()) { 14050 InputMethodManager imm = InputMethodManager.peekInstance(); 14051 if (imm != null) { 14052 imm.focusIn(this); 14053 } 14054 } 14055 } 14056 14057 /** 14058 * Resolve all RTL related properties. 14059 * 14060 * @return true if resolution of RTL properties has been done 14061 * 14062 * @hide 14063 */ 14064 public boolean resolveRtlPropertiesIfNeeded() { 14065 if (!needRtlPropertiesResolution()) return false; 14066 14067 // Order is important here: LayoutDirection MUST be resolved first 14068 if (!isLayoutDirectionResolved()) { 14069 resolveLayoutDirection(); 14070 resolveLayoutParams(); 14071 } 14072 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 14073 if (!isTextDirectionResolved()) { 14074 resolveTextDirection(); 14075 } 14076 if (!isTextAlignmentResolved()) { 14077 resolveTextAlignment(); 14078 } 14079 // Should resolve Drawables before Padding because we need the layout direction of the 14080 // Drawable to correctly resolve Padding. 14081 if (!areDrawablesResolved()) { 14082 resolveDrawables(); 14083 } 14084 if (!isPaddingResolved()) { 14085 resolvePadding(); 14086 } 14087 onRtlPropertiesChanged(getLayoutDirection()); 14088 return true; 14089 } 14090 14091 /** 14092 * Reset resolution of all RTL related properties. 14093 * 14094 * @hide 14095 */ 14096 public void resetRtlProperties() { 14097 resetResolvedLayoutDirection(); 14098 resetResolvedTextDirection(); 14099 resetResolvedTextAlignment(); 14100 resetResolvedPadding(); 14101 resetResolvedDrawables(); 14102 } 14103 14104 /** 14105 * @see #onScreenStateChanged(int) 14106 */ 14107 void dispatchScreenStateChanged(int screenState) { 14108 onScreenStateChanged(screenState); 14109 } 14110 14111 /** 14112 * This method is called whenever the state of the screen this view is 14113 * attached to changes. A state change will usually occurs when the screen 14114 * turns on or off (whether it happens automatically or the user does it 14115 * manually.) 14116 * 14117 * @param screenState The new state of the screen. Can be either 14118 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 14119 */ 14120 public void onScreenStateChanged(int screenState) { 14121 } 14122 14123 /** 14124 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 14125 */ 14126 private boolean hasRtlSupport() { 14127 return mContext.getApplicationInfo().hasRtlSupport(); 14128 } 14129 14130 /** 14131 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 14132 * RTL not supported) 14133 */ 14134 private boolean isRtlCompatibilityMode() { 14135 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 14136 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 14137 } 14138 14139 /** 14140 * @return true if RTL properties need resolution. 14141 * 14142 */ 14143 private boolean needRtlPropertiesResolution() { 14144 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 14145 } 14146 14147 /** 14148 * Called when any RTL property (layout direction or text direction or text alignment) has 14149 * been changed. 14150 * 14151 * Subclasses need to override this method to take care of cached information that depends on the 14152 * resolved layout direction, or to inform child views that inherit their layout direction. 14153 * 14154 * The default implementation does nothing. 14155 * 14156 * @param layoutDirection the direction of the layout 14157 * 14158 * @see #LAYOUT_DIRECTION_LTR 14159 * @see #LAYOUT_DIRECTION_RTL 14160 */ 14161 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 14162 } 14163 14164 /** 14165 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 14166 * that the parent directionality can and will be resolved before its children. 14167 * 14168 * @return true if resolution has been done, false otherwise. 14169 * 14170 * @hide 14171 */ 14172 public boolean resolveLayoutDirection() { 14173 // Clear any previous layout direction resolution 14174 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14175 14176 if (hasRtlSupport()) { 14177 // Set resolved depending on layout direction 14178 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 14179 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 14180 case LAYOUT_DIRECTION_INHERIT: 14181 // We cannot resolve yet. LTR is by default and let the resolution happen again 14182 // later to get the correct resolved value 14183 if (!canResolveLayoutDirection()) return false; 14184 14185 // Parent has not yet resolved, LTR is still the default 14186 try { 14187 if (!mParent.isLayoutDirectionResolved()) return false; 14188 14189 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14190 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14191 } 14192 } catch (AbstractMethodError e) { 14193 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14194 " does not fully implement ViewParent", e); 14195 } 14196 break; 14197 case LAYOUT_DIRECTION_RTL: 14198 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14199 break; 14200 case LAYOUT_DIRECTION_LOCALE: 14201 if((LAYOUT_DIRECTION_RTL == 14202 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 14203 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14204 } 14205 break; 14206 default: 14207 // Nothing to do, LTR by default 14208 } 14209 } 14210 14211 // Set to resolved 14212 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14213 return true; 14214 } 14215 14216 /** 14217 * Check if layout direction resolution can be done. 14218 * 14219 * @return true if layout direction resolution can be done otherwise return false. 14220 */ 14221 public boolean canResolveLayoutDirection() { 14222 switch (getRawLayoutDirection()) { 14223 case LAYOUT_DIRECTION_INHERIT: 14224 if (mParent != null) { 14225 try { 14226 return mParent.canResolveLayoutDirection(); 14227 } catch (AbstractMethodError e) { 14228 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14229 " does not fully implement ViewParent", e); 14230 } 14231 } 14232 return false; 14233 14234 default: 14235 return true; 14236 } 14237 } 14238 14239 /** 14240 * Reset the resolved layout direction. Layout direction will be resolved during a call to 14241 * {@link #onMeasure(int, int)}. 14242 * 14243 * @hide 14244 */ 14245 public void resetResolvedLayoutDirection() { 14246 // Reset the current resolved bits 14247 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14248 } 14249 14250 /** 14251 * @return true if the layout direction is inherited. 14252 * 14253 * @hide 14254 */ 14255 public boolean isLayoutDirectionInherited() { 14256 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 14257 } 14258 14259 /** 14260 * @return true if layout direction has been resolved. 14261 */ 14262 public boolean isLayoutDirectionResolved() { 14263 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14264 } 14265 14266 /** 14267 * Return if padding has been resolved 14268 * 14269 * @hide 14270 */ 14271 boolean isPaddingResolved() { 14272 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 14273 } 14274 14275 /** 14276 * Resolves padding depending on layout direction, if applicable, and 14277 * recomputes internal padding values to adjust for scroll bars. 14278 * 14279 * @hide 14280 */ 14281 public void resolvePadding() { 14282 final int resolvedLayoutDirection = getLayoutDirection(); 14283 14284 if (!isRtlCompatibilityMode()) { 14285 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 14286 // If start / end padding are defined, they will be resolved (hence overriding) to 14287 // left / right or right / left depending on the resolved layout direction. 14288 // If start / end padding are not defined, use the left / right ones. 14289 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 14290 Rect padding = sThreadLocal.get(); 14291 if (padding == null) { 14292 padding = new Rect(); 14293 sThreadLocal.set(padding); 14294 } 14295 mBackground.getPadding(padding); 14296 if (!mLeftPaddingDefined) { 14297 mUserPaddingLeftInitial = padding.left; 14298 } 14299 if (!mRightPaddingDefined) { 14300 mUserPaddingRightInitial = padding.right; 14301 } 14302 } 14303 switch (resolvedLayoutDirection) { 14304 case LAYOUT_DIRECTION_RTL: 14305 if (mUserPaddingStart != UNDEFINED_PADDING) { 14306 mUserPaddingRight = mUserPaddingStart; 14307 } else { 14308 mUserPaddingRight = mUserPaddingRightInitial; 14309 } 14310 if (mUserPaddingEnd != UNDEFINED_PADDING) { 14311 mUserPaddingLeft = mUserPaddingEnd; 14312 } else { 14313 mUserPaddingLeft = mUserPaddingLeftInitial; 14314 } 14315 break; 14316 case LAYOUT_DIRECTION_LTR: 14317 default: 14318 if (mUserPaddingStart != UNDEFINED_PADDING) { 14319 mUserPaddingLeft = mUserPaddingStart; 14320 } else { 14321 mUserPaddingLeft = mUserPaddingLeftInitial; 14322 } 14323 if (mUserPaddingEnd != UNDEFINED_PADDING) { 14324 mUserPaddingRight = mUserPaddingEnd; 14325 } else { 14326 mUserPaddingRight = mUserPaddingRightInitial; 14327 } 14328 } 14329 14330 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 14331 } 14332 14333 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14334 onRtlPropertiesChanged(resolvedLayoutDirection); 14335 14336 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 14337 } 14338 14339 /** 14340 * Reset the resolved layout direction. 14341 * 14342 * @hide 14343 */ 14344 public void resetResolvedPadding() { 14345 resetResolvedPaddingInternal(); 14346 } 14347 14348 /** 14349 * Used when we only want to reset *this* view's padding and not trigger overrides 14350 * in ViewGroup that reset children too. 14351 */ 14352 void resetResolvedPaddingInternal() { 14353 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 14354 } 14355 14356 /** 14357 * This is called when the view is detached from a window. At this point it 14358 * no longer has a surface for drawing. 14359 * 14360 * @see #onAttachedToWindow() 14361 */ 14362 @CallSuper 14363 protected void onDetachedFromWindow() { 14364 } 14365 14366 /** 14367 * This is a framework-internal mirror of onDetachedFromWindow() that's called 14368 * after onDetachedFromWindow(). 14369 * 14370 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 14371 * The super method should be called at the end of the overridden method to ensure 14372 * subclasses are destroyed first 14373 * 14374 * @hide 14375 */ 14376 @CallSuper 14377 protected void onDetachedFromWindowInternal() { 14378 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 14379 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14380 14381 removeUnsetPressCallback(); 14382 removeLongPressCallback(); 14383 removePerformClickCallback(); 14384 removeSendViewScrolledAccessibilityEventCallback(); 14385 stopNestedScroll(); 14386 14387 // Anything that started animating right before detach should already 14388 // be in its final state when re-attached. 14389 jumpDrawablesToCurrentState(); 14390 14391 destroyDrawingCache(); 14392 14393 cleanupDraw(); 14394 mCurrentAnimation = null; 14395 } 14396 14397 private void cleanupDraw() { 14398 resetDisplayList(); 14399 if (mAttachInfo != null) { 14400 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 14401 } 14402 } 14403 14404 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 14405 } 14406 14407 /** 14408 * @return The number of times this view has been attached to a window 14409 */ 14410 protected int getWindowAttachCount() { 14411 return mWindowAttachCount; 14412 } 14413 14414 /** 14415 * Retrieve a unique token identifying the window this view is attached to. 14416 * @return Return the window's token for use in 14417 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 14418 */ 14419 public IBinder getWindowToken() { 14420 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 14421 } 14422 14423 /** 14424 * Retrieve the {@link WindowId} for the window this view is 14425 * currently attached to. 14426 */ 14427 public WindowId getWindowId() { 14428 if (mAttachInfo == null) { 14429 return null; 14430 } 14431 if (mAttachInfo.mWindowId == null) { 14432 try { 14433 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 14434 mAttachInfo.mWindowToken); 14435 mAttachInfo.mWindowId = new WindowId( 14436 mAttachInfo.mIWindowId); 14437 } catch (RemoteException e) { 14438 } 14439 } 14440 return mAttachInfo.mWindowId; 14441 } 14442 14443 /** 14444 * Retrieve a unique token identifying the top-level "real" window of 14445 * the window that this view is attached to. That is, this is like 14446 * {@link #getWindowToken}, except if the window this view in is a panel 14447 * window (attached to another containing window), then the token of 14448 * the containing window is returned instead. 14449 * 14450 * @return Returns the associated window token, either 14451 * {@link #getWindowToken()} or the containing window's token. 14452 */ 14453 public IBinder getApplicationWindowToken() { 14454 AttachInfo ai = mAttachInfo; 14455 if (ai != null) { 14456 IBinder appWindowToken = ai.mPanelParentWindowToken; 14457 if (appWindowToken == null) { 14458 appWindowToken = ai.mWindowToken; 14459 } 14460 return appWindowToken; 14461 } 14462 return null; 14463 } 14464 14465 /** 14466 * Gets the logical display to which the view's window has been attached. 14467 * 14468 * @return The logical display, or null if the view is not currently attached to a window. 14469 */ 14470 public Display getDisplay() { 14471 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 14472 } 14473 14474 /** 14475 * Retrieve private session object this view hierarchy is using to 14476 * communicate with the window manager. 14477 * @return the session object to communicate with the window manager 14478 */ 14479 /*package*/ IWindowSession getWindowSession() { 14480 return mAttachInfo != null ? mAttachInfo.mSession : null; 14481 } 14482 14483 /** 14484 * Return the visibility value of the least visible component passed. 14485 */ 14486 int combineVisibility(int vis1, int vis2) { 14487 // This works because VISIBLE < INVISIBLE < GONE. 14488 return Math.max(vis1, vis2); 14489 } 14490 14491 /** 14492 * @param info the {@link android.view.View.AttachInfo} to associated with 14493 * this view 14494 */ 14495 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 14496 //System.out.println("Attached! " + this); 14497 mAttachInfo = info; 14498 if (mOverlay != null) { 14499 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 14500 } 14501 mWindowAttachCount++; 14502 // We will need to evaluate the drawable state at least once. 14503 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 14504 if (mFloatingTreeObserver != null) { 14505 info.mTreeObserver.merge(mFloatingTreeObserver); 14506 mFloatingTreeObserver = null; 14507 } 14508 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 14509 mAttachInfo.mScrollContainers.add(this); 14510 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 14511 } 14512 performCollectViewAttributes(mAttachInfo, visibility); 14513 onAttachedToWindow(); 14514 14515 ListenerInfo li = mListenerInfo; 14516 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 14517 li != null ? li.mOnAttachStateChangeListeners : null; 14518 if (listeners != null && listeners.size() > 0) { 14519 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 14520 // perform the dispatching. The iterator is a safe guard against listeners that 14521 // could mutate the list by calling the various add/remove methods. This prevents 14522 // the array from being modified while we iterate it. 14523 for (OnAttachStateChangeListener listener : listeners) { 14524 listener.onViewAttachedToWindow(this); 14525 } 14526 } 14527 14528 int vis = info.mWindowVisibility; 14529 if (vis != GONE) { 14530 onWindowVisibilityChanged(vis); 14531 } 14532 14533 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 14534 // As all views in the subtree will already receive dispatchAttachedToWindow 14535 // traversing the subtree again here is not desired. 14536 onVisibilityChanged(this, visibility); 14537 14538 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 14539 // If nobody has evaluated the drawable state yet, then do it now. 14540 refreshDrawableState(); 14541 } 14542 needGlobalAttributesUpdate(false); 14543 } 14544 14545 void dispatchDetachedFromWindow() { 14546 AttachInfo info = mAttachInfo; 14547 if (info != null) { 14548 int vis = info.mWindowVisibility; 14549 if (vis != GONE) { 14550 onWindowVisibilityChanged(GONE); 14551 } 14552 } 14553 14554 onDetachedFromWindow(); 14555 onDetachedFromWindowInternal(); 14556 14557 InputMethodManager imm = InputMethodManager.peekInstance(); 14558 if (imm != null) { 14559 imm.onViewDetachedFromWindow(this); 14560 } 14561 14562 ListenerInfo li = mListenerInfo; 14563 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 14564 li != null ? li.mOnAttachStateChangeListeners : null; 14565 if (listeners != null && listeners.size() > 0) { 14566 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 14567 // perform the dispatching. The iterator is a safe guard against listeners that 14568 // could mutate the list by calling the various add/remove methods. This prevents 14569 // the array from being modified while we iterate it. 14570 for (OnAttachStateChangeListener listener : listeners) { 14571 listener.onViewDetachedFromWindow(this); 14572 } 14573 } 14574 14575 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 14576 mAttachInfo.mScrollContainers.remove(this); 14577 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 14578 } 14579 14580 mAttachInfo = null; 14581 if (mOverlay != null) { 14582 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 14583 } 14584 } 14585 14586 /** 14587 * Cancel any deferred high-level input events that were previously posted to the event queue. 14588 * 14589 * <p>Many views post high-level events such as click handlers to the event queue 14590 * to run deferred in order to preserve a desired user experience - clearing visible 14591 * pressed states before executing, etc. This method will abort any events of this nature 14592 * that are currently in flight.</p> 14593 * 14594 * <p>Custom views that generate their own high-level deferred input events should override 14595 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 14596 * 14597 * <p>This will also cancel pending input events for any child views.</p> 14598 * 14599 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 14600 * This will not impact newer events posted after this call that may occur as a result of 14601 * lower-level input events still waiting in the queue. If you are trying to prevent 14602 * double-submitted events for the duration of some sort of asynchronous transaction 14603 * you should also take other steps to protect against unexpected double inputs e.g. calling 14604 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 14605 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 14606 */ 14607 public final void cancelPendingInputEvents() { 14608 dispatchCancelPendingInputEvents(); 14609 } 14610 14611 /** 14612 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 14613 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 14614 */ 14615 void dispatchCancelPendingInputEvents() { 14616 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 14617 onCancelPendingInputEvents(); 14618 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 14619 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 14620 " did not call through to super.onCancelPendingInputEvents()"); 14621 } 14622 } 14623 14624 /** 14625 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 14626 * a parent view. 14627 * 14628 * <p>This method is responsible for removing any pending high-level input events that were 14629 * posted to the event queue to run later. Custom view classes that post their own deferred 14630 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 14631 * {@link android.os.Handler} should override this method, call 14632 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 14633 * </p> 14634 */ 14635 public void onCancelPendingInputEvents() { 14636 removePerformClickCallback(); 14637 cancelLongPress(); 14638 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 14639 } 14640 14641 /** 14642 * Store this view hierarchy's frozen state into the given container. 14643 * 14644 * @param container The SparseArray in which to save the view's state. 14645 * 14646 * @see #restoreHierarchyState(android.util.SparseArray) 14647 * @see #dispatchSaveInstanceState(android.util.SparseArray) 14648 * @see #onSaveInstanceState() 14649 */ 14650 public void saveHierarchyState(SparseArray<Parcelable> container) { 14651 dispatchSaveInstanceState(container); 14652 } 14653 14654 /** 14655 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 14656 * this view and its children. May be overridden to modify how freezing happens to a 14657 * view's children; for example, some views may want to not store state for their children. 14658 * 14659 * @param container The SparseArray in which to save the view's state. 14660 * 14661 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 14662 * @see #saveHierarchyState(android.util.SparseArray) 14663 * @see #onSaveInstanceState() 14664 */ 14665 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 14666 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 14667 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 14668 Parcelable state = onSaveInstanceState(); 14669 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 14670 throw new IllegalStateException( 14671 "Derived class did not call super.onSaveInstanceState()"); 14672 } 14673 if (state != null) { 14674 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 14675 // + ": " + state); 14676 container.put(mID, state); 14677 } 14678 } 14679 } 14680 14681 /** 14682 * Hook allowing a view to generate a representation of its internal state 14683 * that can later be used to create a new instance with that same state. 14684 * This state should only contain information that is not persistent or can 14685 * not be reconstructed later. For example, you will never store your 14686 * current position on screen because that will be computed again when a 14687 * new instance of the view is placed in its view hierarchy. 14688 * <p> 14689 * Some examples of things you may store here: the current cursor position 14690 * in a text view (but usually not the text itself since that is stored in a 14691 * content provider or other persistent storage), the currently selected 14692 * item in a list view. 14693 * 14694 * @return Returns a Parcelable object containing the view's current dynamic 14695 * state, or null if there is nothing interesting to save. The 14696 * default implementation returns null. 14697 * @see #onRestoreInstanceState(android.os.Parcelable) 14698 * @see #saveHierarchyState(android.util.SparseArray) 14699 * @see #dispatchSaveInstanceState(android.util.SparseArray) 14700 * @see #setSaveEnabled(boolean) 14701 */ 14702 @CallSuper 14703 protected Parcelable onSaveInstanceState() { 14704 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 14705 if (mStartActivityRequestWho != null) { 14706 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 14707 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 14708 return state; 14709 } 14710 return BaseSavedState.EMPTY_STATE; 14711 } 14712 14713 /** 14714 * Restore this view hierarchy's frozen state from the given container. 14715 * 14716 * @param container The SparseArray which holds previously frozen states. 14717 * 14718 * @see #saveHierarchyState(android.util.SparseArray) 14719 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 14720 * @see #onRestoreInstanceState(android.os.Parcelable) 14721 */ 14722 public void restoreHierarchyState(SparseArray<Parcelable> container) { 14723 dispatchRestoreInstanceState(container); 14724 } 14725 14726 /** 14727 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 14728 * state for this view and its children. May be overridden to modify how restoring 14729 * happens to a view's children; for example, some views may want to not store state 14730 * for their children. 14731 * 14732 * @param container The SparseArray which holds previously saved state. 14733 * 14734 * @see #dispatchSaveInstanceState(android.util.SparseArray) 14735 * @see #restoreHierarchyState(android.util.SparseArray) 14736 * @see #onRestoreInstanceState(android.os.Parcelable) 14737 */ 14738 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 14739 if (mID != NO_ID) { 14740 Parcelable state = container.get(mID); 14741 if (state != null) { 14742 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 14743 // + ": " + state); 14744 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 14745 onRestoreInstanceState(state); 14746 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 14747 throw new IllegalStateException( 14748 "Derived class did not call super.onRestoreInstanceState()"); 14749 } 14750 } 14751 } 14752 } 14753 14754 /** 14755 * Hook allowing a view to re-apply a representation of its internal state that had previously 14756 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 14757 * null state. 14758 * 14759 * @param state The frozen state that had previously been returned by 14760 * {@link #onSaveInstanceState}. 14761 * 14762 * @see #onSaveInstanceState() 14763 * @see #restoreHierarchyState(android.util.SparseArray) 14764 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 14765 */ 14766 @CallSuper 14767 protected void onRestoreInstanceState(Parcelable state) { 14768 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 14769 if (state != null && !(state instanceof AbsSavedState)) { 14770 throw new IllegalArgumentException("Wrong state class, expecting View State but " 14771 + "received " + state.getClass().toString() + " instead. This usually happens " 14772 + "when two views of different type have the same id in the same hierarchy. " 14773 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 14774 + "other views do not use the same id."); 14775 } 14776 if (state != null && state instanceof BaseSavedState) { 14777 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 14778 } 14779 } 14780 14781 /** 14782 * <p>Return the time at which the drawing of the view hierarchy started.</p> 14783 * 14784 * @return the drawing start time in milliseconds 14785 */ 14786 public long getDrawingTime() { 14787 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 14788 } 14789 14790 /** 14791 * <p>Enables or disables the duplication of the parent's state into this view. When 14792 * duplication is enabled, this view gets its drawable state from its parent rather 14793 * than from its own internal properties.</p> 14794 * 14795 * <p>Note: in the current implementation, setting this property to true after the 14796 * view was added to a ViewGroup might have no effect at all. This property should 14797 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 14798 * 14799 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 14800 * property is enabled, an exception will be thrown.</p> 14801 * 14802 * <p>Note: if the child view uses and updates additional states which are unknown to the 14803 * parent, these states should not be affected by this method.</p> 14804 * 14805 * @param enabled True to enable duplication of the parent's drawable state, false 14806 * to disable it. 14807 * 14808 * @see #getDrawableState() 14809 * @see #isDuplicateParentStateEnabled() 14810 */ 14811 public void setDuplicateParentStateEnabled(boolean enabled) { 14812 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 14813 } 14814 14815 /** 14816 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 14817 * 14818 * @return True if this view's drawable state is duplicated from the parent, 14819 * false otherwise 14820 * 14821 * @see #getDrawableState() 14822 * @see #setDuplicateParentStateEnabled(boolean) 14823 */ 14824 public boolean isDuplicateParentStateEnabled() { 14825 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 14826 } 14827 14828 /** 14829 * <p>Specifies the type of layer backing this view. The layer can be 14830 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14831 * {@link #LAYER_TYPE_HARDWARE}.</p> 14832 * 14833 * <p>A layer is associated with an optional {@link android.graphics.Paint} 14834 * instance that controls how the layer is composed on screen. The following 14835 * properties of the paint are taken into account when composing the layer:</p> 14836 * <ul> 14837 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 14838 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 14839 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 14840 * </ul> 14841 * 14842 * <p>If this view has an alpha value set to < 1.0 by calling 14843 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 14844 * by this view's alpha value.</p> 14845 * 14846 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 14847 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 14848 * for more information on when and how to use layers.</p> 14849 * 14850 * @param layerType The type of layer to use with this view, must be one of 14851 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14852 * {@link #LAYER_TYPE_HARDWARE} 14853 * @param paint The paint used to compose the layer. This argument is optional 14854 * and can be null. It is ignored when the layer type is 14855 * {@link #LAYER_TYPE_NONE} 14856 * 14857 * @see #getLayerType() 14858 * @see #LAYER_TYPE_NONE 14859 * @see #LAYER_TYPE_SOFTWARE 14860 * @see #LAYER_TYPE_HARDWARE 14861 * @see #setAlpha(float) 14862 * 14863 * @attr ref android.R.styleable#View_layerType 14864 */ 14865 public void setLayerType(int layerType, Paint paint) { 14866 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 14867 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 14868 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 14869 } 14870 14871 boolean typeChanged = mRenderNode.setLayerType(layerType); 14872 14873 if (!typeChanged) { 14874 setLayerPaint(paint); 14875 return; 14876 } 14877 14878 // Destroy any previous software drawing cache if needed 14879 if (mLayerType == LAYER_TYPE_SOFTWARE) { 14880 destroyDrawingCache(); 14881 } 14882 14883 mLayerType = layerType; 14884 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 14885 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 14886 mRenderNode.setLayerPaint(mLayerPaint); 14887 14888 // draw() behaves differently if we are on a layer, so we need to 14889 // invalidate() here 14890 invalidateParentCaches(); 14891 invalidate(true); 14892 } 14893 14894 /** 14895 * Updates the {@link Paint} object used with the current layer (used only if the current 14896 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 14897 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 14898 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 14899 * ensure that the view gets redrawn immediately. 14900 * 14901 * <p>A layer is associated with an optional {@link android.graphics.Paint} 14902 * instance that controls how the layer is composed on screen. The following 14903 * properties of the paint are taken into account when composing the layer:</p> 14904 * <ul> 14905 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 14906 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 14907 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 14908 * </ul> 14909 * 14910 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 14911 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 14912 * 14913 * @param paint The paint used to compose the layer. This argument is optional 14914 * and can be null. It is ignored when the layer type is 14915 * {@link #LAYER_TYPE_NONE} 14916 * 14917 * @see #setLayerType(int, android.graphics.Paint) 14918 */ 14919 public void setLayerPaint(Paint paint) { 14920 int layerType = getLayerType(); 14921 if (layerType != LAYER_TYPE_NONE) { 14922 mLayerPaint = paint == null ? new Paint() : paint; 14923 if (layerType == LAYER_TYPE_HARDWARE) { 14924 if (mRenderNode.setLayerPaint(mLayerPaint)) { 14925 invalidateViewProperty(false, false); 14926 } 14927 } else { 14928 invalidate(); 14929 } 14930 } 14931 } 14932 14933 /** 14934 * Indicates what type of layer is currently associated with this view. By default 14935 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 14936 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 14937 * for more information on the different types of layers. 14938 * 14939 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 14940 * {@link #LAYER_TYPE_HARDWARE} 14941 * 14942 * @see #setLayerType(int, android.graphics.Paint) 14943 * @see #buildLayer() 14944 * @see #LAYER_TYPE_NONE 14945 * @see #LAYER_TYPE_SOFTWARE 14946 * @see #LAYER_TYPE_HARDWARE 14947 */ 14948 public int getLayerType() { 14949 return mLayerType; 14950 } 14951 14952 /** 14953 * Forces this view's layer to be created and this view to be rendered 14954 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 14955 * invoking this method will have no effect. 14956 * 14957 * This method can for instance be used to render a view into its layer before 14958 * starting an animation. If this view is complex, rendering into the layer 14959 * before starting the animation will avoid skipping frames. 14960 * 14961 * @throws IllegalStateException If this view is not attached to a window 14962 * 14963 * @see #setLayerType(int, android.graphics.Paint) 14964 */ 14965 public void buildLayer() { 14966 if (mLayerType == LAYER_TYPE_NONE) return; 14967 14968 final AttachInfo attachInfo = mAttachInfo; 14969 if (attachInfo == null) { 14970 throw new IllegalStateException("This view must be attached to a window first"); 14971 } 14972 14973 if (getWidth() == 0 || getHeight() == 0) { 14974 return; 14975 } 14976 14977 switch (mLayerType) { 14978 case LAYER_TYPE_HARDWARE: 14979 updateDisplayListIfDirty(); 14980 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 14981 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 14982 } 14983 break; 14984 case LAYER_TYPE_SOFTWARE: 14985 buildDrawingCache(true); 14986 break; 14987 } 14988 } 14989 14990 /** 14991 * If this View draws with a HardwareLayer, returns it. 14992 * Otherwise returns null 14993 * 14994 * TODO: Only TextureView uses this, can we eliminate it? 14995 */ 14996 HardwareLayer getHardwareLayer() { 14997 return null; 14998 } 14999 15000 /** 15001 * Destroys all hardware rendering resources. This method is invoked 15002 * when the system needs to reclaim resources. Upon execution of this 15003 * method, you should free any OpenGL resources created by the view. 15004 * 15005 * Note: you <strong>must</strong> call 15006 * <code>super.destroyHardwareResources()</code> when overriding 15007 * this method. 15008 * 15009 * @hide 15010 */ 15011 @CallSuper 15012 protected void destroyHardwareResources() { 15013 // Although the Layer will be destroyed by RenderNode, we want to release 15014 // the staging display list, which is also a signal to RenderNode that it's 15015 // safe to free its copy of the display list as it knows that we will 15016 // push an updated DisplayList if we try to draw again 15017 resetDisplayList(); 15018 } 15019 15020 /** 15021 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 15022 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 15023 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 15024 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 15025 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 15026 * null.</p> 15027 * 15028 * <p>Enabling the drawing cache is similar to 15029 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 15030 * acceleration is turned off. When hardware acceleration is turned on, enabling the 15031 * drawing cache has no effect on rendering because the system uses a different mechanism 15032 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 15033 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 15034 * for information on how to enable software and hardware layers.</p> 15035 * 15036 * <p>This API can be used to manually generate 15037 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 15038 * {@link #getDrawingCache()}.</p> 15039 * 15040 * @param enabled true to enable the drawing cache, false otherwise 15041 * 15042 * @see #isDrawingCacheEnabled() 15043 * @see #getDrawingCache() 15044 * @see #buildDrawingCache() 15045 * @see #setLayerType(int, android.graphics.Paint) 15046 */ 15047 public void setDrawingCacheEnabled(boolean enabled) { 15048 mCachingFailed = false; 15049 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 15050 } 15051 15052 /** 15053 * <p>Indicates whether the drawing cache is enabled for this view.</p> 15054 * 15055 * @return true if the drawing cache is enabled 15056 * 15057 * @see #setDrawingCacheEnabled(boolean) 15058 * @see #getDrawingCache() 15059 */ 15060 @ViewDebug.ExportedProperty(category = "drawing") 15061 public boolean isDrawingCacheEnabled() { 15062 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 15063 } 15064 15065 /** 15066 * Debugging utility which recursively outputs the dirty state of a view and its 15067 * descendants. 15068 * 15069 * @hide 15070 */ 15071 @SuppressWarnings({"UnusedDeclaration"}) 15072 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 15073 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 15074 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 15075 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 15076 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 15077 if (clear) { 15078 mPrivateFlags &= clearMask; 15079 } 15080 if (this instanceof ViewGroup) { 15081 ViewGroup parent = (ViewGroup) this; 15082 final int count = parent.getChildCount(); 15083 for (int i = 0; i < count; i++) { 15084 final View child = parent.getChildAt(i); 15085 child.outputDirtyFlags(indent + " ", clear, clearMask); 15086 } 15087 } 15088 } 15089 15090 /** 15091 * This method is used by ViewGroup to cause its children to restore or recreate their 15092 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 15093 * to recreate its own display list, which would happen if it went through the normal 15094 * draw/dispatchDraw mechanisms. 15095 * 15096 * @hide 15097 */ 15098 protected void dispatchGetDisplayList() {} 15099 15100 /** 15101 * A view that is not attached or hardware accelerated cannot create a display list. 15102 * This method checks these conditions and returns the appropriate result. 15103 * 15104 * @return true if view has the ability to create a display list, false otherwise. 15105 * 15106 * @hide 15107 */ 15108 public boolean canHaveDisplayList() { 15109 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 15110 } 15111 15112 /** 15113 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 15114 * @hide 15115 */ 15116 @NonNull 15117 public RenderNode updateDisplayListIfDirty() { 15118 final RenderNode renderNode = mRenderNode; 15119 if (!canHaveDisplayList()) { 15120 // can't populate RenderNode, don't try 15121 return renderNode; 15122 } 15123 15124 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 15125 || !renderNode.isValid() 15126 || (mRecreateDisplayList)) { 15127 // Don't need to recreate the display list, just need to tell our 15128 // children to restore/recreate theirs 15129 if (renderNode.isValid() 15130 && !mRecreateDisplayList) { 15131 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15132 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15133 dispatchGetDisplayList(); 15134 15135 return renderNode; // no work needed 15136 } 15137 15138 // If we got here, we're recreating it. Mark it as such to ensure that 15139 // we copy in child display lists into ours in drawChild() 15140 mRecreateDisplayList = true; 15141 15142 int width = mRight - mLeft; 15143 int height = mBottom - mTop; 15144 int layerType = getLayerType(); 15145 15146 final DisplayListCanvas canvas = renderNode.start(width, height); 15147 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 15148 15149 try { 15150 final HardwareLayer layer = getHardwareLayer(); 15151 if (layer != null && layer.isValid()) { 15152 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 15153 } else if (layerType == LAYER_TYPE_SOFTWARE) { 15154 buildDrawingCache(true); 15155 Bitmap cache = getDrawingCache(true); 15156 if (cache != null) { 15157 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 15158 } 15159 } else { 15160 computeScroll(); 15161 15162 canvas.translate(-mScrollX, -mScrollY); 15163 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15164 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15165 15166 // Fast path for layouts with no backgrounds 15167 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15168 dispatchDraw(canvas); 15169 if (mOverlay != null && !mOverlay.isEmpty()) { 15170 mOverlay.getOverlayView().draw(canvas); 15171 } 15172 } else { 15173 draw(canvas); 15174 } 15175 } 15176 } finally { 15177 renderNode.end(canvas); 15178 setDisplayListProperties(renderNode); 15179 } 15180 } else { 15181 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15182 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15183 } 15184 return renderNode; 15185 } 15186 15187 private void resetDisplayList() { 15188 if (mRenderNode.isValid()) { 15189 mRenderNode.destroyDisplayListData(); 15190 } 15191 15192 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 15193 mBackgroundRenderNode.destroyDisplayListData(); 15194 } 15195 } 15196 15197 /** 15198 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 15199 * 15200 * @return A non-scaled bitmap representing this view or null if cache is disabled. 15201 * 15202 * @see #getDrawingCache(boolean) 15203 */ 15204 public Bitmap getDrawingCache() { 15205 return getDrawingCache(false); 15206 } 15207 15208 /** 15209 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 15210 * is null when caching is disabled. If caching is enabled and the cache is not ready, 15211 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 15212 * draw from the cache when the cache is enabled. To benefit from the cache, you must 15213 * request the drawing cache by calling this method and draw it on screen if the 15214 * returned bitmap is not null.</p> 15215 * 15216 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15217 * this method will create a bitmap of the same size as this view. Because this bitmap 15218 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15219 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15220 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15221 * size than the view. This implies that your application must be able to handle this 15222 * size.</p> 15223 * 15224 * @param autoScale Indicates whether the generated bitmap should be scaled based on 15225 * the current density of the screen when the application is in compatibility 15226 * mode. 15227 * 15228 * @return A bitmap representing this view or null if cache is disabled. 15229 * 15230 * @see #setDrawingCacheEnabled(boolean) 15231 * @see #isDrawingCacheEnabled() 15232 * @see #buildDrawingCache(boolean) 15233 * @see #destroyDrawingCache() 15234 */ 15235 public Bitmap getDrawingCache(boolean autoScale) { 15236 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 15237 return null; 15238 } 15239 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 15240 buildDrawingCache(autoScale); 15241 } 15242 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 15243 } 15244 15245 /** 15246 * <p>Frees the resources used by the drawing cache. If you call 15247 * {@link #buildDrawingCache()} manually without calling 15248 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15249 * should cleanup the cache with this method afterwards.</p> 15250 * 15251 * @see #setDrawingCacheEnabled(boolean) 15252 * @see #buildDrawingCache() 15253 * @see #getDrawingCache() 15254 */ 15255 public void destroyDrawingCache() { 15256 if (mDrawingCache != null) { 15257 mDrawingCache.recycle(); 15258 mDrawingCache = null; 15259 } 15260 if (mUnscaledDrawingCache != null) { 15261 mUnscaledDrawingCache.recycle(); 15262 mUnscaledDrawingCache = null; 15263 } 15264 } 15265 15266 /** 15267 * Setting a solid background color for the drawing cache's bitmaps will improve 15268 * performance and memory usage. Note, though that this should only be used if this 15269 * view will always be drawn on top of a solid color. 15270 * 15271 * @param color The background color to use for the drawing cache's bitmap 15272 * 15273 * @see #setDrawingCacheEnabled(boolean) 15274 * @see #buildDrawingCache() 15275 * @see #getDrawingCache() 15276 */ 15277 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 15278 if (color != mDrawingCacheBackgroundColor) { 15279 mDrawingCacheBackgroundColor = color; 15280 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 15281 } 15282 } 15283 15284 /** 15285 * @see #setDrawingCacheBackgroundColor(int) 15286 * 15287 * @return The background color to used for the drawing cache's bitmap 15288 */ 15289 @ColorInt 15290 public int getDrawingCacheBackgroundColor() { 15291 return mDrawingCacheBackgroundColor; 15292 } 15293 15294 /** 15295 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 15296 * 15297 * @see #buildDrawingCache(boolean) 15298 */ 15299 public void buildDrawingCache() { 15300 buildDrawingCache(false); 15301 } 15302 15303 /** 15304 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 15305 * 15306 * <p>If you call {@link #buildDrawingCache()} manually without calling 15307 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15308 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 15309 * 15310 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15311 * this method will create a bitmap of the same size as this view. Because this bitmap 15312 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15313 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15314 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15315 * size than the view. This implies that your application must be able to handle this 15316 * size.</p> 15317 * 15318 * <p>You should avoid calling this method when hardware acceleration is enabled. If 15319 * you do not need the drawing cache bitmap, calling this method will increase memory 15320 * usage and cause the view to be rendered in software once, thus negatively impacting 15321 * performance.</p> 15322 * 15323 * @see #getDrawingCache() 15324 * @see #destroyDrawingCache() 15325 */ 15326 public void buildDrawingCache(boolean autoScale) { 15327 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 15328 mDrawingCache == null : mUnscaledDrawingCache == null)) { 15329 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 15330 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 15331 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 15332 } 15333 try { 15334 buildDrawingCacheImpl(autoScale); 15335 } finally { 15336 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 15337 } 15338 } 15339 } 15340 15341 /** 15342 * private, internal implementation of buildDrawingCache, used to enable tracing 15343 */ 15344 private void buildDrawingCacheImpl(boolean autoScale) { 15345 mCachingFailed = false; 15346 15347 int width = mRight - mLeft; 15348 int height = mBottom - mTop; 15349 15350 final AttachInfo attachInfo = mAttachInfo; 15351 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 15352 15353 if (autoScale && scalingRequired) { 15354 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 15355 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 15356 } 15357 15358 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 15359 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 15360 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 15361 15362 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 15363 final long drawingCacheSize = 15364 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 15365 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 15366 if (width > 0 && height > 0) { 15367 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 15368 + projectedBitmapSize + " bytes, only " 15369 + drawingCacheSize + " available"); 15370 } 15371 destroyDrawingCache(); 15372 mCachingFailed = true; 15373 return; 15374 } 15375 15376 boolean clear = true; 15377 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 15378 15379 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 15380 Bitmap.Config quality; 15381 if (!opaque) { 15382 // Never pick ARGB_4444 because it looks awful 15383 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 15384 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 15385 case DRAWING_CACHE_QUALITY_AUTO: 15386 case DRAWING_CACHE_QUALITY_LOW: 15387 case DRAWING_CACHE_QUALITY_HIGH: 15388 default: 15389 quality = Bitmap.Config.ARGB_8888; 15390 break; 15391 } 15392 } else { 15393 // Optimization for translucent windows 15394 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 15395 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 15396 } 15397 15398 // Try to cleanup memory 15399 if (bitmap != null) bitmap.recycle(); 15400 15401 try { 15402 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 15403 width, height, quality); 15404 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 15405 if (autoScale) { 15406 mDrawingCache = bitmap; 15407 } else { 15408 mUnscaledDrawingCache = bitmap; 15409 } 15410 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 15411 } catch (OutOfMemoryError e) { 15412 // If there is not enough memory to create the bitmap cache, just 15413 // ignore the issue as bitmap caches are not required to draw the 15414 // view hierarchy 15415 if (autoScale) { 15416 mDrawingCache = null; 15417 } else { 15418 mUnscaledDrawingCache = null; 15419 } 15420 mCachingFailed = true; 15421 return; 15422 } 15423 15424 clear = drawingCacheBackgroundColor != 0; 15425 } 15426 15427 Canvas canvas; 15428 if (attachInfo != null) { 15429 canvas = attachInfo.mCanvas; 15430 if (canvas == null) { 15431 canvas = new Canvas(); 15432 } 15433 canvas.setBitmap(bitmap); 15434 // Temporarily clobber the cached Canvas in case one of our children 15435 // is also using a drawing cache. Without this, the children would 15436 // steal the canvas by attaching their own bitmap to it and bad, bad 15437 // thing would happen (invisible views, corrupted drawings, etc.) 15438 attachInfo.mCanvas = null; 15439 } else { 15440 // This case should hopefully never or seldom happen 15441 canvas = new Canvas(bitmap); 15442 } 15443 15444 if (clear) { 15445 bitmap.eraseColor(drawingCacheBackgroundColor); 15446 } 15447 15448 computeScroll(); 15449 final int restoreCount = canvas.save(); 15450 15451 if (autoScale && scalingRequired) { 15452 final float scale = attachInfo.mApplicationScale; 15453 canvas.scale(scale, scale); 15454 } 15455 15456 canvas.translate(-mScrollX, -mScrollY); 15457 15458 mPrivateFlags |= PFLAG_DRAWN; 15459 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 15460 mLayerType != LAYER_TYPE_NONE) { 15461 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 15462 } 15463 15464 // Fast path for layouts with no backgrounds 15465 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15466 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15467 dispatchDraw(canvas); 15468 if (mOverlay != null && !mOverlay.isEmpty()) { 15469 mOverlay.getOverlayView().draw(canvas); 15470 } 15471 } else { 15472 draw(canvas); 15473 } 15474 15475 canvas.restoreToCount(restoreCount); 15476 canvas.setBitmap(null); 15477 15478 if (attachInfo != null) { 15479 // Restore the cached Canvas for our siblings 15480 attachInfo.mCanvas = canvas; 15481 } 15482 } 15483 15484 /** 15485 * Create a snapshot of the view into a bitmap. We should probably make 15486 * some form of this public, but should think about the API. 15487 */ 15488 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 15489 int width = mRight - mLeft; 15490 int height = mBottom - mTop; 15491 15492 final AttachInfo attachInfo = mAttachInfo; 15493 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 15494 width = (int) ((width * scale) + 0.5f); 15495 height = (int) ((height * scale) + 0.5f); 15496 15497 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 15498 width > 0 ? width : 1, height > 0 ? height : 1, quality); 15499 if (bitmap == null) { 15500 throw new OutOfMemoryError(); 15501 } 15502 15503 Resources resources = getResources(); 15504 if (resources != null) { 15505 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 15506 } 15507 15508 Canvas canvas; 15509 if (attachInfo != null) { 15510 canvas = attachInfo.mCanvas; 15511 if (canvas == null) { 15512 canvas = new Canvas(); 15513 } 15514 canvas.setBitmap(bitmap); 15515 // Temporarily clobber the cached Canvas in case one of our children 15516 // is also using a drawing cache. Without this, the children would 15517 // steal the canvas by attaching their own bitmap to it and bad, bad 15518 // things would happen (invisible views, corrupted drawings, etc.) 15519 attachInfo.mCanvas = null; 15520 } else { 15521 // This case should hopefully never or seldom happen 15522 canvas = new Canvas(bitmap); 15523 } 15524 15525 if ((backgroundColor & 0xff000000) != 0) { 15526 bitmap.eraseColor(backgroundColor); 15527 } 15528 15529 computeScroll(); 15530 final int restoreCount = canvas.save(); 15531 canvas.scale(scale, scale); 15532 canvas.translate(-mScrollX, -mScrollY); 15533 15534 // Temporarily remove the dirty mask 15535 int flags = mPrivateFlags; 15536 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15537 15538 // Fast path for layouts with no backgrounds 15539 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15540 dispatchDraw(canvas); 15541 if (mOverlay != null && !mOverlay.isEmpty()) { 15542 mOverlay.getOverlayView().draw(canvas); 15543 } 15544 } else { 15545 draw(canvas); 15546 } 15547 15548 mPrivateFlags = flags; 15549 15550 canvas.restoreToCount(restoreCount); 15551 canvas.setBitmap(null); 15552 15553 if (attachInfo != null) { 15554 // Restore the cached Canvas for our siblings 15555 attachInfo.mCanvas = canvas; 15556 } 15557 15558 return bitmap; 15559 } 15560 15561 /** 15562 * Indicates whether this View is currently in edit mode. A View is usually 15563 * in edit mode when displayed within a developer tool. For instance, if 15564 * this View is being drawn by a visual user interface builder, this method 15565 * should return true. 15566 * 15567 * Subclasses should check the return value of this method to provide 15568 * different behaviors if their normal behavior might interfere with the 15569 * host environment. For instance: the class spawns a thread in its 15570 * constructor, the drawing code relies on device-specific features, etc. 15571 * 15572 * This method is usually checked in the drawing code of custom widgets. 15573 * 15574 * @return True if this View is in edit mode, false otherwise. 15575 */ 15576 public boolean isInEditMode() { 15577 return false; 15578 } 15579 15580 /** 15581 * If the View draws content inside its padding and enables fading edges, 15582 * it needs to support padding offsets. Padding offsets are added to the 15583 * fading edges to extend the length of the fade so that it covers pixels 15584 * drawn inside the padding. 15585 * 15586 * Subclasses of this class should override this method if they need 15587 * to draw content inside the padding. 15588 * 15589 * @return True if padding offset must be applied, false otherwise. 15590 * 15591 * @see #getLeftPaddingOffset() 15592 * @see #getRightPaddingOffset() 15593 * @see #getTopPaddingOffset() 15594 * @see #getBottomPaddingOffset() 15595 * 15596 * @since CURRENT 15597 */ 15598 protected boolean isPaddingOffsetRequired() { 15599 return false; 15600 } 15601 15602 /** 15603 * Amount by which to extend the left fading region. Called only when 15604 * {@link #isPaddingOffsetRequired()} returns true. 15605 * 15606 * @return The left padding offset in pixels. 15607 * 15608 * @see #isPaddingOffsetRequired() 15609 * 15610 * @since CURRENT 15611 */ 15612 protected int getLeftPaddingOffset() { 15613 return 0; 15614 } 15615 15616 /** 15617 * Amount by which to extend the right fading region. Called only when 15618 * {@link #isPaddingOffsetRequired()} returns true. 15619 * 15620 * @return The right padding offset in pixels. 15621 * 15622 * @see #isPaddingOffsetRequired() 15623 * 15624 * @since CURRENT 15625 */ 15626 protected int getRightPaddingOffset() { 15627 return 0; 15628 } 15629 15630 /** 15631 * Amount by which to extend the top fading region. Called only when 15632 * {@link #isPaddingOffsetRequired()} returns true. 15633 * 15634 * @return The top padding offset in pixels. 15635 * 15636 * @see #isPaddingOffsetRequired() 15637 * 15638 * @since CURRENT 15639 */ 15640 protected int getTopPaddingOffset() { 15641 return 0; 15642 } 15643 15644 /** 15645 * Amount by which to extend the bottom fading region. Called only when 15646 * {@link #isPaddingOffsetRequired()} returns true. 15647 * 15648 * @return The bottom padding offset in pixels. 15649 * 15650 * @see #isPaddingOffsetRequired() 15651 * 15652 * @since CURRENT 15653 */ 15654 protected int getBottomPaddingOffset() { 15655 return 0; 15656 } 15657 15658 /** 15659 * @hide 15660 * @param offsetRequired 15661 */ 15662 protected int getFadeTop(boolean offsetRequired) { 15663 int top = mPaddingTop; 15664 if (offsetRequired) top += getTopPaddingOffset(); 15665 return top; 15666 } 15667 15668 /** 15669 * @hide 15670 * @param offsetRequired 15671 */ 15672 protected int getFadeHeight(boolean offsetRequired) { 15673 int padding = mPaddingTop; 15674 if (offsetRequired) padding += getTopPaddingOffset(); 15675 return mBottom - mTop - mPaddingBottom - padding; 15676 } 15677 15678 /** 15679 * <p>Indicates whether this view is attached to a hardware accelerated 15680 * window or not.</p> 15681 * 15682 * <p>Even if this method returns true, it does not mean that every call 15683 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 15684 * accelerated {@link android.graphics.Canvas}. For instance, if this view 15685 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 15686 * window is hardware accelerated, 15687 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 15688 * return false, and this method will return true.</p> 15689 * 15690 * @return True if the view is attached to a window and the window is 15691 * hardware accelerated; false in any other case. 15692 */ 15693 @ViewDebug.ExportedProperty(category = "drawing") 15694 public boolean isHardwareAccelerated() { 15695 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 15696 } 15697 15698 /** 15699 * Sets a rectangular area on this view to which the view will be clipped 15700 * when it is drawn. Setting the value to null will remove the clip bounds 15701 * and the view will draw normally, using its full bounds. 15702 * 15703 * @param clipBounds The rectangular area, in the local coordinates of 15704 * this view, to which future drawing operations will be clipped. 15705 */ 15706 public void setClipBounds(Rect clipBounds) { 15707 if (clipBounds == mClipBounds 15708 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 15709 return; 15710 } 15711 if (clipBounds != null) { 15712 if (mClipBounds == null) { 15713 mClipBounds = new Rect(clipBounds); 15714 } else { 15715 mClipBounds.set(clipBounds); 15716 } 15717 } else { 15718 mClipBounds = null; 15719 } 15720 mRenderNode.setClipBounds(mClipBounds); 15721 invalidateViewProperty(false, false); 15722 } 15723 15724 /** 15725 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 15726 * 15727 * @return A copy of the current clip bounds if clip bounds are set, 15728 * otherwise null. 15729 */ 15730 public Rect getClipBounds() { 15731 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 15732 } 15733 15734 15735 /** 15736 * Populates an output rectangle with the clip bounds of the view, 15737 * returning {@code true} if successful or {@code false} if the view's 15738 * clip bounds are {@code null}. 15739 * 15740 * @param outRect rectangle in which to place the clip bounds of the view 15741 * @return {@code true} if successful or {@code false} if the view's 15742 * clip bounds are {@code null} 15743 */ 15744 public boolean getClipBounds(Rect outRect) { 15745 if (mClipBounds != null) { 15746 outRect.set(mClipBounds); 15747 return true; 15748 } 15749 return false; 15750 } 15751 15752 /** 15753 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 15754 * case of an active Animation being run on the view. 15755 */ 15756 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 15757 Animation a, boolean scalingRequired) { 15758 Transformation invalidationTransform; 15759 final int flags = parent.mGroupFlags; 15760 final boolean initialized = a.isInitialized(); 15761 if (!initialized) { 15762 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 15763 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 15764 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 15765 onAnimationStart(); 15766 } 15767 15768 final Transformation t = parent.getChildTransformation(); 15769 boolean more = a.getTransformation(drawingTime, t, 1f); 15770 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 15771 if (parent.mInvalidationTransformation == null) { 15772 parent.mInvalidationTransformation = new Transformation(); 15773 } 15774 invalidationTransform = parent.mInvalidationTransformation; 15775 a.getTransformation(drawingTime, invalidationTransform, 1f); 15776 } else { 15777 invalidationTransform = t; 15778 } 15779 15780 if (more) { 15781 if (!a.willChangeBounds()) { 15782 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 15783 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 15784 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 15785 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 15786 // The child need to draw an animation, potentially offscreen, so 15787 // make sure we do not cancel invalidate requests 15788 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 15789 parent.invalidate(mLeft, mTop, mRight, mBottom); 15790 } 15791 } else { 15792 if (parent.mInvalidateRegion == null) { 15793 parent.mInvalidateRegion = new RectF(); 15794 } 15795 final RectF region = parent.mInvalidateRegion; 15796 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 15797 invalidationTransform); 15798 15799 // The child need to draw an animation, potentially offscreen, so 15800 // make sure we do not cancel invalidate requests 15801 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 15802 15803 final int left = mLeft + (int) region.left; 15804 final int top = mTop + (int) region.top; 15805 parent.invalidate(left, top, left + (int) (region.width() + .5f), 15806 top + (int) (region.height() + .5f)); 15807 } 15808 } 15809 return more; 15810 } 15811 15812 /** 15813 * This method is called by getDisplayList() when a display list is recorded for a View. 15814 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 15815 */ 15816 void setDisplayListProperties(RenderNode renderNode) { 15817 if (renderNode != null) { 15818 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 15819 renderNode.setClipToBounds(mParent instanceof ViewGroup 15820 && ((ViewGroup) mParent).getClipChildren()); 15821 15822 float alpha = 1; 15823 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 15824 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 15825 ViewGroup parentVG = (ViewGroup) mParent; 15826 final Transformation t = parentVG.getChildTransformation(); 15827 if (parentVG.getChildStaticTransformation(this, t)) { 15828 final int transformType = t.getTransformationType(); 15829 if (transformType != Transformation.TYPE_IDENTITY) { 15830 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 15831 alpha = t.getAlpha(); 15832 } 15833 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 15834 renderNode.setStaticMatrix(t.getMatrix()); 15835 } 15836 } 15837 } 15838 } 15839 if (mTransformationInfo != null) { 15840 alpha *= getFinalAlpha(); 15841 if (alpha < 1) { 15842 final int multipliedAlpha = (int) (255 * alpha); 15843 if (onSetAlpha(multipliedAlpha)) { 15844 alpha = 1; 15845 } 15846 } 15847 renderNode.setAlpha(alpha); 15848 } else if (alpha < 1) { 15849 renderNode.setAlpha(alpha); 15850 } 15851 } 15852 } 15853 15854 /** 15855 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 15856 * 15857 * This is where the View specializes rendering behavior based on layer type, 15858 * and hardware acceleration. 15859 */ 15860 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 15861 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 15862 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 15863 * 15864 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 15865 * HW accelerated, it can't handle drawing RenderNodes. 15866 */ 15867 boolean drawingWithRenderNode = mAttachInfo != null 15868 && mAttachInfo.mHardwareAccelerated 15869 && hardwareAcceleratedCanvas; 15870 15871 boolean more = false; 15872 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 15873 final int parentFlags = parent.mGroupFlags; 15874 15875 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 15876 parent.getChildTransformation().clear(); 15877 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 15878 } 15879 15880 Transformation transformToApply = null; 15881 boolean concatMatrix = false; 15882 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 15883 final Animation a = getAnimation(); 15884 if (a != null) { 15885 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 15886 concatMatrix = a.willChangeTransformationMatrix(); 15887 if (concatMatrix) { 15888 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 15889 } 15890 transformToApply = parent.getChildTransformation(); 15891 } else { 15892 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 15893 // No longer animating: clear out old animation matrix 15894 mRenderNode.setAnimationMatrix(null); 15895 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 15896 } 15897 if (!drawingWithRenderNode 15898 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 15899 final Transformation t = parent.getChildTransformation(); 15900 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 15901 if (hasTransform) { 15902 final int transformType = t.getTransformationType(); 15903 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 15904 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 15905 } 15906 } 15907 } 15908 15909 concatMatrix |= !childHasIdentityMatrix; 15910 15911 // Sets the flag as early as possible to allow draw() implementations 15912 // to call invalidate() successfully when doing animations 15913 mPrivateFlags |= PFLAG_DRAWN; 15914 15915 if (!concatMatrix && 15916 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 15917 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 15918 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 15919 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 15920 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 15921 return more; 15922 } 15923 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 15924 15925 if (hardwareAcceleratedCanvas) { 15926 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 15927 // retain the flag's value temporarily in the mRecreateDisplayList flag 15928 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 15929 mPrivateFlags &= ~PFLAG_INVALIDATED; 15930 } 15931 15932 RenderNode renderNode = null; 15933 Bitmap cache = null; 15934 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 15935 if (layerType == LAYER_TYPE_SOFTWARE 15936 || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) { 15937 // If not drawing with RenderNode, treat HW layers as SW 15938 layerType = LAYER_TYPE_SOFTWARE; 15939 buildDrawingCache(true); 15940 cache = getDrawingCache(true); 15941 } 15942 15943 if (drawingWithRenderNode) { 15944 // Delay getting the display list until animation-driven alpha values are 15945 // set up and possibly passed on to the view 15946 renderNode = updateDisplayListIfDirty(); 15947 if (!renderNode.isValid()) { 15948 // Uncommon, but possible. If a view is removed from the hierarchy during the call 15949 // to getDisplayList(), the display list will be marked invalid and we should not 15950 // try to use it again. 15951 renderNode = null; 15952 drawingWithRenderNode = false; 15953 } 15954 } 15955 15956 int sx = 0; 15957 int sy = 0; 15958 if (!drawingWithRenderNode) { 15959 computeScroll(); 15960 sx = mScrollX; 15961 sy = mScrollY; 15962 } 15963 15964 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 15965 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 15966 15967 int restoreTo = -1; 15968 if (!drawingWithRenderNode || transformToApply != null) { 15969 restoreTo = canvas.save(); 15970 } 15971 if (offsetForScroll) { 15972 canvas.translate(mLeft - sx, mTop - sy); 15973 } else { 15974 if (!drawingWithRenderNode) { 15975 canvas.translate(mLeft, mTop); 15976 } 15977 if (scalingRequired) { 15978 if (drawingWithRenderNode) { 15979 // TODO: Might not need this if we put everything inside the DL 15980 restoreTo = canvas.save(); 15981 } 15982 // mAttachInfo cannot be null, otherwise scalingRequired == false 15983 final float scale = 1.0f / mAttachInfo.mApplicationScale; 15984 canvas.scale(scale, scale); 15985 } 15986 } 15987 15988 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 15989 if (transformToApply != null 15990 || alpha < 1 15991 || !hasIdentityMatrix() 15992 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 15993 if (transformToApply != null || !childHasIdentityMatrix) { 15994 int transX = 0; 15995 int transY = 0; 15996 15997 if (offsetForScroll) { 15998 transX = -sx; 15999 transY = -sy; 16000 } 16001 16002 if (transformToApply != null) { 16003 if (concatMatrix) { 16004 if (drawingWithRenderNode) { 16005 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 16006 } else { 16007 // Undo the scroll translation, apply the transformation matrix, 16008 // then redo the scroll translate to get the correct result. 16009 canvas.translate(-transX, -transY); 16010 canvas.concat(transformToApply.getMatrix()); 16011 canvas.translate(transX, transY); 16012 } 16013 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16014 } 16015 16016 float transformAlpha = transformToApply.getAlpha(); 16017 if (transformAlpha < 1) { 16018 alpha *= transformAlpha; 16019 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16020 } 16021 } 16022 16023 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 16024 canvas.translate(-transX, -transY); 16025 canvas.concat(getMatrix()); 16026 canvas.translate(transX, transY); 16027 } 16028 } 16029 16030 // Deal with alpha if it is or used to be <1 16031 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16032 if (alpha < 1) { 16033 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16034 } else { 16035 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16036 } 16037 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16038 if (!drawingWithDrawingCache) { 16039 final int multipliedAlpha = (int) (255 * alpha); 16040 if (!onSetAlpha(multipliedAlpha)) { 16041 if (drawingWithRenderNode) { 16042 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 16043 } else if (layerType == LAYER_TYPE_NONE) { 16044 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 16045 multipliedAlpha); 16046 } 16047 } else { 16048 // Alpha is handled by the child directly, clobber the layer's alpha 16049 mPrivateFlags |= PFLAG_ALPHA_SET; 16050 } 16051 } 16052 } 16053 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16054 onSetAlpha(255); 16055 mPrivateFlags &= ~PFLAG_ALPHA_SET; 16056 } 16057 16058 if (!drawingWithRenderNode) { 16059 // apply clips directly, since RenderNode won't do it for this draw 16060 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 16061 if (offsetForScroll) { 16062 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 16063 } else { 16064 if (!scalingRequired || cache == null) { 16065 canvas.clipRect(0, 0, getWidth(), getHeight()); 16066 } else { 16067 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 16068 } 16069 } 16070 } 16071 16072 if (mClipBounds != null) { 16073 // clip bounds ignore scroll 16074 canvas.clipRect(mClipBounds); 16075 } 16076 } 16077 16078 if (!drawingWithDrawingCache) { 16079 if (drawingWithRenderNode) { 16080 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16081 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16082 } else { 16083 // Fast path for layouts with no backgrounds 16084 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16085 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16086 dispatchDraw(canvas); 16087 } else { 16088 draw(canvas); 16089 } 16090 } 16091 } else if (cache != null) { 16092 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16093 if (layerType == LAYER_TYPE_NONE) { 16094 // no layer paint, use temporary paint to draw bitmap 16095 Paint cachePaint = parent.mCachePaint; 16096 if (cachePaint == null) { 16097 cachePaint = new Paint(); 16098 cachePaint.setDither(false); 16099 parent.mCachePaint = cachePaint; 16100 } 16101 cachePaint.setAlpha((int) (alpha * 255)); 16102 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 16103 } else { 16104 // use layer paint to draw the bitmap, merging the two alphas, but also restore 16105 int layerPaintAlpha = mLayerPaint.getAlpha(); 16106 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 16107 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 16108 mLayerPaint.setAlpha(layerPaintAlpha); 16109 } 16110 } 16111 16112 if (restoreTo >= 0) { 16113 canvas.restoreToCount(restoreTo); 16114 } 16115 16116 if (a != null && !more) { 16117 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 16118 onSetAlpha(255); 16119 } 16120 parent.finishAnimatingView(this, a); 16121 } 16122 16123 if (more && hardwareAcceleratedCanvas) { 16124 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16125 // alpha animations should cause the child to recreate its display list 16126 invalidate(true); 16127 } 16128 } 16129 16130 mRecreateDisplayList = false; 16131 16132 return more; 16133 } 16134 16135 /** 16136 * Manually render this view (and all of its children) to the given Canvas. 16137 * The view must have already done a full layout before this function is 16138 * called. When implementing a view, implement 16139 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 16140 * If you do need to override this method, call the superclass version. 16141 * 16142 * @param canvas The Canvas to which the View is rendered. 16143 */ 16144 @CallSuper 16145 public void draw(Canvas canvas) { 16146 final int privateFlags = mPrivateFlags; 16147 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 16148 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 16149 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 16150 16151 /* 16152 * Draw traversal performs several drawing steps which must be executed 16153 * in the appropriate order: 16154 * 16155 * 1. Draw the background 16156 * 2. If necessary, save the canvas' layers to prepare for fading 16157 * 3. Draw view's content 16158 * 4. Draw children 16159 * 5. If necessary, draw the fading edges and restore layers 16160 * 6. Draw decorations (scrollbars for instance) 16161 */ 16162 16163 // Step 1, draw the background, if needed 16164 int saveCount; 16165 16166 if (!dirtyOpaque) { 16167 drawBackground(canvas); 16168 } 16169 16170 // skip step 2 & 5 if possible (common case) 16171 final int viewFlags = mViewFlags; 16172 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 16173 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 16174 if (!verticalEdges && !horizontalEdges) { 16175 // Step 3, draw the content 16176 if (!dirtyOpaque) onDraw(canvas); 16177 16178 // Step 4, draw the children 16179 dispatchDraw(canvas); 16180 16181 // Overlay is part of the content and draws beneath Foreground 16182 if (mOverlay != null && !mOverlay.isEmpty()) { 16183 mOverlay.getOverlayView().dispatchDraw(canvas); 16184 } 16185 16186 // Step 6, draw decorations (foreground, scrollbars) 16187 onDrawForeground(canvas); 16188 16189 // we're done... 16190 return; 16191 } 16192 16193 /* 16194 * Here we do the full fledged routine... 16195 * (this is an uncommon case where speed matters less, 16196 * this is why we repeat some of the tests that have been 16197 * done above) 16198 */ 16199 16200 boolean drawTop = false; 16201 boolean drawBottom = false; 16202 boolean drawLeft = false; 16203 boolean drawRight = false; 16204 16205 float topFadeStrength = 0.0f; 16206 float bottomFadeStrength = 0.0f; 16207 float leftFadeStrength = 0.0f; 16208 float rightFadeStrength = 0.0f; 16209 16210 // Step 2, save the canvas' layers 16211 int paddingLeft = mPaddingLeft; 16212 16213 final boolean offsetRequired = isPaddingOffsetRequired(); 16214 if (offsetRequired) { 16215 paddingLeft += getLeftPaddingOffset(); 16216 } 16217 16218 int left = mScrollX + paddingLeft; 16219 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 16220 int top = mScrollY + getFadeTop(offsetRequired); 16221 int bottom = top + getFadeHeight(offsetRequired); 16222 16223 if (offsetRequired) { 16224 right += getRightPaddingOffset(); 16225 bottom += getBottomPaddingOffset(); 16226 } 16227 16228 final ScrollabilityCache scrollabilityCache = mScrollCache; 16229 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 16230 int length = (int) fadeHeight; 16231 16232 // clip the fade length if top and bottom fades overlap 16233 // overlapping fades produce odd-looking artifacts 16234 if (verticalEdges && (top + length > bottom - length)) { 16235 length = (bottom - top) / 2; 16236 } 16237 16238 // also clip horizontal fades if necessary 16239 if (horizontalEdges && (left + length > right - length)) { 16240 length = (right - left) / 2; 16241 } 16242 16243 if (verticalEdges) { 16244 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 16245 drawTop = topFadeStrength * fadeHeight > 1.0f; 16246 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 16247 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 16248 } 16249 16250 if (horizontalEdges) { 16251 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 16252 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 16253 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 16254 drawRight = rightFadeStrength * fadeHeight > 1.0f; 16255 } 16256 16257 saveCount = canvas.getSaveCount(); 16258 16259 int solidColor = getSolidColor(); 16260 if (solidColor == 0) { 16261 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 16262 16263 if (drawTop) { 16264 canvas.saveLayer(left, top, right, top + length, null, flags); 16265 } 16266 16267 if (drawBottom) { 16268 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 16269 } 16270 16271 if (drawLeft) { 16272 canvas.saveLayer(left, top, left + length, bottom, null, flags); 16273 } 16274 16275 if (drawRight) { 16276 canvas.saveLayer(right - length, top, right, bottom, null, flags); 16277 } 16278 } else { 16279 scrollabilityCache.setFadeColor(solidColor); 16280 } 16281 16282 // Step 3, draw the content 16283 if (!dirtyOpaque) onDraw(canvas); 16284 16285 // Step 4, draw the children 16286 dispatchDraw(canvas); 16287 16288 // Step 5, draw the fade effect and restore layers 16289 final Paint p = scrollabilityCache.paint; 16290 final Matrix matrix = scrollabilityCache.matrix; 16291 final Shader fade = scrollabilityCache.shader; 16292 16293 if (drawTop) { 16294 matrix.setScale(1, fadeHeight * topFadeStrength); 16295 matrix.postTranslate(left, top); 16296 fade.setLocalMatrix(matrix); 16297 p.setShader(fade); 16298 canvas.drawRect(left, top, right, top + length, p); 16299 } 16300 16301 if (drawBottom) { 16302 matrix.setScale(1, fadeHeight * bottomFadeStrength); 16303 matrix.postRotate(180); 16304 matrix.postTranslate(left, bottom); 16305 fade.setLocalMatrix(matrix); 16306 p.setShader(fade); 16307 canvas.drawRect(left, bottom - length, right, bottom, p); 16308 } 16309 16310 if (drawLeft) { 16311 matrix.setScale(1, fadeHeight * leftFadeStrength); 16312 matrix.postRotate(-90); 16313 matrix.postTranslate(left, top); 16314 fade.setLocalMatrix(matrix); 16315 p.setShader(fade); 16316 canvas.drawRect(left, top, left + length, bottom, p); 16317 } 16318 16319 if (drawRight) { 16320 matrix.setScale(1, fadeHeight * rightFadeStrength); 16321 matrix.postRotate(90); 16322 matrix.postTranslate(right, top); 16323 fade.setLocalMatrix(matrix); 16324 p.setShader(fade); 16325 canvas.drawRect(right - length, top, right, bottom, p); 16326 } 16327 16328 canvas.restoreToCount(saveCount); 16329 16330 // Overlay is part of the content and draws beneath Foreground 16331 if (mOverlay != null && !mOverlay.isEmpty()) { 16332 mOverlay.getOverlayView().dispatchDraw(canvas); 16333 } 16334 16335 // Step 6, draw decorations (foreground, scrollbars) 16336 onDrawForeground(canvas); 16337 } 16338 16339 /** 16340 * Draws the background onto the specified canvas. 16341 * 16342 * @param canvas Canvas on which to draw the background 16343 */ 16344 private void drawBackground(Canvas canvas) { 16345 final Drawable background = mBackground; 16346 if (background == null) { 16347 return; 16348 } 16349 16350 setBackgroundBounds(); 16351 16352 // Attempt to use a display list if requested. 16353 if (canvas.isHardwareAccelerated() && mAttachInfo != null 16354 && mAttachInfo.mHardwareRenderer != null) { 16355 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 16356 16357 final RenderNode renderNode = mBackgroundRenderNode; 16358 if (renderNode != null && renderNode.isValid()) { 16359 setBackgroundRenderNodeProperties(renderNode); 16360 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16361 return; 16362 } 16363 } 16364 16365 final int scrollX = mScrollX; 16366 final int scrollY = mScrollY; 16367 if ((scrollX | scrollY) == 0) { 16368 background.draw(canvas); 16369 } else { 16370 canvas.translate(scrollX, scrollY); 16371 background.draw(canvas); 16372 canvas.translate(-scrollX, -scrollY); 16373 } 16374 } 16375 16376 /** 16377 * Sets the correct background bounds and rebuilds the outline, if needed. 16378 * <p/> 16379 * This is called by LayoutLib. 16380 */ 16381 void setBackgroundBounds() { 16382 if (mBackgroundSizeChanged && mBackground != null) { 16383 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 16384 mBackgroundSizeChanged = false; 16385 rebuildOutline(); 16386 } 16387 } 16388 16389 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 16390 renderNode.setTranslationX(mScrollX); 16391 renderNode.setTranslationY(mScrollY); 16392 } 16393 16394 /** 16395 * Creates a new display list or updates the existing display list for the 16396 * specified Drawable. 16397 * 16398 * @param drawable Drawable for which to create a display list 16399 * @param renderNode Existing RenderNode, or {@code null} 16400 * @return A valid display list for the specified drawable 16401 */ 16402 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 16403 if (renderNode == null) { 16404 renderNode = RenderNode.create(drawable.getClass().getName(), this); 16405 } 16406 16407 final Rect bounds = drawable.getBounds(); 16408 final int width = bounds.width(); 16409 final int height = bounds.height(); 16410 final DisplayListCanvas canvas = renderNode.start(width, height); 16411 16412 // Reverse left/top translation done by drawable canvas, which will 16413 // instead be applied by rendernode's LTRB bounds below. This way, the 16414 // drawable's bounds match with its rendernode bounds and its content 16415 // will lie within those bounds in the rendernode tree. 16416 canvas.translate(-bounds.left, -bounds.top); 16417 16418 try { 16419 drawable.draw(canvas); 16420 } finally { 16421 renderNode.end(canvas); 16422 } 16423 16424 // Set up drawable properties that are view-independent. 16425 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 16426 renderNode.setProjectBackwards(drawable.isProjected()); 16427 renderNode.setProjectionReceiver(true); 16428 renderNode.setClipToBounds(false); 16429 return renderNode; 16430 } 16431 16432 /** 16433 * Returns the overlay for this view, creating it if it does not yet exist. 16434 * Adding drawables to the overlay will cause them to be displayed whenever 16435 * the view itself is redrawn. Objects in the overlay should be actively 16436 * managed: remove them when they should not be displayed anymore. The 16437 * overlay will always have the same size as its host view. 16438 * 16439 * <p>Note: Overlays do not currently work correctly with {@link 16440 * SurfaceView} or {@link TextureView}; contents in overlays for these 16441 * types of views may not display correctly.</p> 16442 * 16443 * @return The ViewOverlay object for this view. 16444 * @see ViewOverlay 16445 */ 16446 public ViewOverlay getOverlay() { 16447 if (mOverlay == null) { 16448 mOverlay = new ViewOverlay(mContext, this); 16449 } 16450 return mOverlay; 16451 } 16452 16453 /** 16454 * Override this if your view is known to always be drawn on top of a solid color background, 16455 * and needs to draw fading edges. Returning a non-zero color enables the view system to 16456 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 16457 * should be set to 0xFF. 16458 * 16459 * @see #setVerticalFadingEdgeEnabled(boolean) 16460 * @see #setHorizontalFadingEdgeEnabled(boolean) 16461 * 16462 * @return The known solid color background for this view, or 0 if the color may vary 16463 */ 16464 @ViewDebug.ExportedProperty(category = "drawing") 16465 @ColorInt 16466 public int getSolidColor() { 16467 return 0; 16468 } 16469 16470 /** 16471 * Build a human readable string representation of the specified view flags. 16472 * 16473 * @param flags the view flags to convert to a string 16474 * @return a String representing the supplied flags 16475 */ 16476 private static String printFlags(int flags) { 16477 String output = ""; 16478 int numFlags = 0; 16479 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 16480 output += "TAKES_FOCUS"; 16481 numFlags++; 16482 } 16483 16484 switch (flags & VISIBILITY_MASK) { 16485 case INVISIBLE: 16486 if (numFlags > 0) { 16487 output += " "; 16488 } 16489 output += "INVISIBLE"; 16490 // USELESS HERE numFlags++; 16491 break; 16492 case GONE: 16493 if (numFlags > 0) { 16494 output += " "; 16495 } 16496 output += "GONE"; 16497 // USELESS HERE numFlags++; 16498 break; 16499 default: 16500 break; 16501 } 16502 return output; 16503 } 16504 16505 /** 16506 * Build a human readable string representation of the specified private 16507 * view flags. 16508 * 16509 * @param privateFlags the private view flags to convert to a string 16510 * @return a String representing the supplied flags 16511 */ 16512 private static String printPrivateFlags(int privateFlags) { 16513 String output = ""; 16514 int numFlags = 0; 16515 16516 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 16517 output += "WANTS_FOCUS"; 16518 numFlags++; 16519 } 16520 16521 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 16522 if (numFlags > 0) { 16523 output += " "; 16524 } 16525 output += "FOCUSED"; 16526 numFlags++; 16527 } 16528 16529 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 16530 if (numFlags > 0) { 16531 output += " "; 16532 } 16533 output += "SELECTED"; 16534 numFlags++; 16535 } 16536 16537 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 16538 if (numFlags > 0) { 16539 output += " "; 16540 } 16541 output += "IS_ROOT_NAMESPACE"; 16542 numFlags++; 16543 } 16544 16545 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 16546 if (numFlags > 0) { 16547 output += " "; 16548 } 16549 output += "HAS_BOUNDS"; 16550 numFlags++; 16551 } 16552 16553 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 16554 if (numFlags > 0) { 16555 output += " "; 16556 } 16557 output += "DRAWN"; 16558 // USELESS HERE numFlags++; 16559 } 16560 return output; 16561 } 16562 16563 /** 16564 * <p>Indicates whether or not this view's layout will be requested during 16565 * the next hierarchy layout pass.</p> 16566 * 16567 * @return true if the layout will be forced during next layout pass 16568 */ 16569 public boolean isLayoutRequested() { 16570 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 16571 } 16572 16573 /** 16574 * Return true if o is a ViewGroup that is laying out using optical bounds. 16575 * @hide 16576 */ 16577 public static boolean isLayoutModeOptical(Object o) { 16578 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 16579 } 16580 16581 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 16582 Insets parentInsets = mParent instanceof View ? 16583 ((View) mParent).getOpticalInsets() : Insets.NONE; 16584 Insets childInsets = getOpticalInsets(); 16585 return setFrame( 16586 left + parentInsets.left - childInsets.left, 16587 top + parentInsets.top - childInsets.top, 16588 right + parentInsets.left + childInsets.right, 16589 bottom + parentInsets.top + childInsets.bottom); 16590 } 16591 16592 /** 16593 * Assign a size and position to a view and all of its 16594 * descendants 16595 * 16596 * <p>This is the second phase of the layout mechanism. 16597 * (The first is measuring). In this phase, each parent calls 16598 * layout on all of its children to position them. 16599 * This is typically done using the child measurements 16600 * that were stored in the measure pass().</p> 16601 * 16602 * <p>Derived classes should not override this method. 16603 * Derived classes with children should override 16604 * onLayout. In that method, they should 16605 * call layout on each of their children.</p> 16606 * 16607 * @param l Left position, relative to parent 16608 * @param t Top position, relative to parent 16609 * @param r Right position, relative to parent 16610 * @param b Bottom position, relative to parent 16611 */ 16612 @SuppressWarnings({"unchecked"}) 16613 public void layout(int l, int t, int r, int b) { 16614 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 16615 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 16616 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 16617 } 16618 16619 int oldL = mLeft; 16620 int oldT = mTop; 16621 int oldB = mBottom; 16622 int oldR = mRight; 16623 16624 boolean changed = isLayoutModeOptical(mParent) ? 16625 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 16626 16627 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 16628 onLayout(changed, l, t, r, b); 16629 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 16630 16631 ListenerInfo li = mListenerInfo; 16632 if (li != null && li.mOnLayoutChangeListeners != null) { 16633 ArrayList<OnLayoutChangeListener> listenersCopy = 16634 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 16635 int numListeners = listenersCopy.size(); 16636 for (int i = 0; i < numListeners; ++i) { 16637 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 16638 } 16639 } 16640 } 16641 16642 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 16643 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 16644 } 16645 16646 /** 16647 * Called from layout when this view should 16648 * assign a size and position to each of its children. 16649 * 16650 * Derived classes with children should override 16651 * this method and call layout on each of 16652 * their children. 16653 * @param changed This is a new size or position for this view 16654 * @param left Left position, relative to parent 16655 * @param top Top position, relative to parent 16656 * @param right Right position, relative to parent 16657 * @param bottom Bottom position, relative to parent 16658 */ 16659 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 16660 } 16661 16662 /** 16663 * Assign a size and position to this view. 16664 * 16665 * This is called from layout. 16666 * 16667 * @param left Left position, relative to parent 16668 * @param top Top position, relative to parent 16669 * @param right Right position, relative to parent 16670 * @param bottom Bottom position, relative to parent 16671 * @return true if the new size and position are different than the 16672 * previous ones 16673 * {@hide} 16674 */ 16675 protected boolean setFrame(int left, int top, int right, int bottom) { 16676 boolean changed = false; 16677 16678 if (DBG) { 16679 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 16680 + right + "," + bottom + ")"); 16681 } 16682 16683 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 16684 changed = true; 16685 16686 // Remember our drawn bit 16687 int drawn = mPrivateFlags & PFLAG_DRAWN; 16688 16689 int oldWidth = mRight - mLeft; 16690 int oldHeight = mBottom - mTop; 16691 int newWidth = right - left; 16692 int newHeight = bottom - top; 16693 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 16694 16695 // Invalidate our old position 16696 invalidate(sizeChanged); 16697 16698 mLeft = left; 16699 mTop = top; 16700 mRight = right; 16701 mBottom = bottom; 16702 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 16703 16704 mPrivateFlags |= PFLAG_HAS_BOUNDS; 16705 16706 16707 if (sizeChanged) { 16708 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 16709 } 16710 16711 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 16712 // If we are visible, force the DRAWN bit to on so that 16713 // this invalidate will go through (at least to our parent). 16714 // This is because someone may have invalidated this view 16715 // before this call to setFrame came in, thereby clearing 16716 // the DRAWN bit. 16717 mPrivateFlags |= PFLAG_DRAWN; 16718 invalidate(sizeChanged); 16719 // parent display list may need to be recreated based on a change in the bounds 16720 // of any child 16721 invalidateParentCaches(); 16722 } 16723 16724 // Reset drawn bit to original value (invalidate turns it off) 16725 mPrivateFlags |= drawn; 16726 16727 mBackgroundSizeChanged = true; 16728 if (mForegroundInfo != null) { 16729 mForegroundInfo.mBoundsChanged = true; 16730 } 16731 16732 notifySubtreeAccessibilityStateChangedIfNeeded(); 16733 } 16734 return changed; 16735 } 16736 16737 /** 16738 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 16739 * @hide 16740 */ 16741 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 16742 setFrame(left, top, right, bottom); 16743 } 16744 16745 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 16746 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 16747 if (mOverlay != null) { 16748 mOverlay.getOverlayView().setRight(newWidth); 16749 mOverlay.getOverlayView().setBottom(newHeight); 16750 } 16751 rebuildOutline(); 16752 } 16753 16754 /** 16755 * Finalize inflating a view from XML. This is called as the last phase 16756 * of inflation, after all child views have been added. 16757 * 16758 * <p>Even if the subclass overrides onFinishInflate, they should always be 16759 * sure to call the super method, so that we get called. 16760 */ 16761 @CallSuper 16762 protected void onFinishInflate() { 16763 } 16764 16765 /** 16766 * Returns the resources associated with this view. 16767 * 16768 * @return Resources object. 16769 */ 16770 public Resources getResources() { 16771 return mResources; 16772 } 16773 16774 /** 16775 * Invalidates the specified Drawable. 16776 * 16777 * @param drawable the drawable to invalidate 16778 */ 16779 @Override 16780 public void invalidateDrawable(@NonNull Drawable drawable) { 16781 if (verifyDrawable(drawable)) { 16782 final Rect dirty = drawable.getDirtyBounds(); 16783 final int scrollX = mScrollX; 16784 final int scrollY = mScrollY; 16785 16786 invalidate(dirty.left + scrollX, dirty.top + scrollY, 16787 dirty.right + scrollX, dirty.bottom + scrollY); 16788 rebuildOutline(); 16789 } 16790 } 16791 16792 /** 16793 * Schedules an action on a drawable to occur at a specified time. 16794 * 16795 * @param who the recipient of the action 16796 * @param what the action to run on the drawable 16797 * @param when the time at which the action must occur. Uses the 16798 * {@link SystemClock#uptimeMillis} timebase. 16799 */ 16800 @Override 16801 public void scheduleDrawable(Drawable who, Runnable what, long when) { 16802 if (verifyDrawable(who) && what != null) { 16803 final long delay = when - SystemClock.uptimeMillis(); 16804 if (mAttachInfo != null) { 16805 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 16806 Choreographer.CALLBACK_ANIMATION, what, who, 16807 Choreographer.subtractFrameDelay(delay)); 16808 } else { 16809 ViewRootImpl.getRunQueue().postDelayed(what, delay); 16810 } 16811 } 16812 } 16813 16814 /** 16815 * Cancels a scheduled action on a drawable. 16816 * 16817 * @param who the recipient of the action 16818 * @param what the action to cancel 16819 */ 16820 @Override 16821 public void unscheduleDrawable(Drawable who, Runnable what) { 16822 if (verifyDrawable(who) && what != null) { 16823 if (mAttachInfo != null) { 16824 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 16825 Choreographer.CALLBACK_ANIMATION, what, who); 16826 } 16827 ViewRootImpl.getRunQueue().removeCallbacks(what); 16828 } 16829 } 16830 16831 /** 16832 * Unschedule any events associated with the given Drawable. This can be 16833 * used when selecting a new Drawable into a view, so that the previous 16834 * one is completely unscheduled. 16835 * 16836 * @param who The Drawable to unschedule. 16837 * 16838 * @see #drawableStateChanged 16839 */ 16840 public void unscheduleDrawable(Drawable who) { 16841 if (mAttachInfo != null && who != null) { 16842 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 16843 Choreographer.CALLBACK_ANIMATION, null, who); 16844 } 16845 } 16846 16847 /** 16848 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 16849 * that the View directionality can and will be resolved before its Drawables. 16850 * 16851 * Will call {@link View#onResolveDrawables} when resolution is done. 16852 * 16853 * @hide 16854 */ 16855 protected void resolveDrawables() { 16856 // Drawables resolution may need to happen before resolving the layout direction (which is 16857 // done only during the measure() call). 16858 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 16859 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 16860 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 16861 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 16862 // direction to be resolved as its resolved value will be the same as its raw value. 16863 if (!isLayoutDirectionResolved() && 16864 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 16865 return; 16866 } 16867 16868 final int layoutDirection = isLayoutDirectionResolved() ? 16869 getLayoutDirection() : getRawLayoutDirection(); 16870 16871 if (mBackground != null) { 16872 mBackground.setLayoutDirection(layoutDirection); 16873 } 16874 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 16875 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 16876 } 16877 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 16878 onResolveDrawables(layoutDirection); 16879 } 16880 16881 boolean areDrawablesResolved() { 16882 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 16883 } 16884 16885 /** 16886 * Called when layout direction has been resolved. 16887 * 16888 * The default implementation does nothing. 16889 * 16890 * @param layoutDirection The resolved layout direction. 16891 * 16892 * @see #LAYOUT_DIRECTION_LTR 16893 * @see #LAYOUT_DIRECTION_RTL 16894 * 16895 * @hide 16896 */ 16897 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 16898 } 16899 16900 /** 16901 * @hide 16902 */ 16903 protected void resetResolvedDrawables() { 16904 resetResolvedDrawablesInternal(); 16905 } 16906 16907 void resetResolvedDrawablesInternal() { 16908 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 16909 } 16910 16911 /** 16912 * If your view subclass is displaying its own Drawable objects, it should 16913 * override this function and return true for any Drawable it is 16914 * displaying. This allows animations for those drawables to be 16915 * scheduled. 16916 * 16917 * <p>Be sure to call through to the super class when overriding this 16918 * function. 16919 * 16920 * @param who The Drawable to verify. Return true if it is one you are 16921 * displaying, else return the result of calling through to the 16922 * super class. 16923 * 16924 * @return boolean If true than the Drawable is being displayed in the 16925 * view; else false and it is not allowed to animate. 16926 * 16927 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 16928 * @see #drawableStateChanged() 16929 */ 16930 @CallSuper 16931 protected boolean verifyDrawable(Drawable who) { 16932 return who == mBackground || (mScrollCache != null && mScrollCache.scrollBar == who) 16933 || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 16934 } 16935 16936 /** 16937 * This function is called whenever the state of the view changes in such 16938 * a way that it impacts the state of drawables being shown. 16939 * <p> 16940 * If the View has a StateListAnimator, it will also be called to run necessary state 16941 * change animations. 16942 * <p> 16943 * Be sure to call through to the superclass when overriding this function. 16944 * 16945 * @see Drawable#setState(int[]) 16946 */ 16947 @CallSuper 16948 protected void drawableStateChanged() { 16949 final int[] state = getDrawableState(); 16950 16951 final Drawable bg = mBackground; 16952 if (bg != null && bg.isStateful()) { 16953 bg.setState(state); 16954 } 16955 16956 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 16957 if (fg != null && fg.isStateful()) { 16958 fg.setState(state); 16959 } 16960 16961 if (mScrollCache != null) { 16962 final Drawable scrollBar = mScrollCache.scrollBar; 16963 if (scrollBar != null && scrollBar.isStateful()) { 16964 scrollBar.setState(state); 16965 } 16966 } 16967 16968 if (mStateListAnimator != null) { 16969 mStateListAnimator.setState(state); 16970 } 16971 } 16972 16973 /** 16974 * This function is called whenever the view hotspot changes and needs to 16975 * be propagated to drawables or child views managed by the view. 16976 * <p> 16977 * Dispatching to child views is handled by 16978 * {@link #dispatchDrawableHotspotChanged(float, float)}. 16979 * <p> 16980 * Be sure to call through to the superclass when overriding this function. 16981 * 16982 * @param x hotspot x coordinate 16983 * @param y hotspot y coordinate 16984 */ 16985 @CallSuper 16986 public void drawableHotspotChanged(float x, float y) { 16987 if (mBackground != null) { 16988 mBackground.setHotspot(x, y); 16989 } 16990 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 16991 mForegroundInfo.mDrawable.setHotspot(x, y); 16992 } 16993 16994 dispatchDrawableHotspotChanged(x, y); 16995 } 16996 16997 /** 16998 * Dispatches drawableHotspotChanged to all of this View's children. 16999 * 17000 * @param x hotspot x coordinate 17001 * @param y hotspot y coordinate 17002 * @see #drawableHotspotChanged(float, float) 17003 */ 17004 public void dispatchDrawableHotspotChanged(float x, float y) { 17005 } 17006 17007 /** 17008 * Call this to force a view to update its drawable state. This will cause 17009 * drawableStateChanged to be called on this view. Views that are interested 17010 * in the new state should call getDrawableState. 17011 * 17012 * @see #drawableStateChanged 17013 * @see #getDrawableState 17014 */ 17015 public void refreshDrawableState() { 17016 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 17017 drawableStateChanged(); 17018 17019 ViewParent parent = mParent; 17020 if (parent != null) { 17021 parent.childDrawableStateChanged(this); 17022 } 17023 } 17024 17025 /** 17026 * Return an array of resource IDs of the drawable states representing the 17027 * current state of the view. 17028 * 17029 * @return The current drawable state 17030 * 17031 * @see Drawable#setState(int[]) 17032 * @see #drawableStateChanged() 17033 * @see #onCreateDrawableState(int) 17034 */ 17035 public final int[] getDrawableState() { 17036 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 17037 return mDrawableState; 17038 } else { 17039 mDrawableState = onCreateDrawableState(0); 17040 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 17041 return mDrawableState; 17042 } 17043 } 17044 17045 /** 17046 * Generate the new {@link android.graphics.drawable.Drawable} state for 17047 * this view. This is called by the view 17048 * system when the cached Drawable state is determined to be invalid. To 17049 * retrieve the current state, you should use {@link #getDrawableState}. 17050 * 17051 * @param extraSpace if non-zero, this is the number of extra entries you 17052 * would like in the returned array in which you can place your own 17053 * states. 17054 * 17055 * @return Returns an array holding the current {@link Drawable} state of 17056 * the view. 17057 * 17058 * @see #mergeDrawableStates(int[], int[]) 17059 */ 17060 protected int[] onCreateDrawableState(int extraSpace) { 17061 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 17062 mParent instanceof View) { 17063 return ((View) mParent).onCreateDrawableState(extraSpace); 17064 } 17065 17066 int[] drawableState; 17067 17068 int privateFlags = mPrivateFlags; 17069 17070 int viewStateIndex = 0; 17071 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 17072 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 17073 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 17074 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 17075 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 17076 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 17077 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 17078 HardwareRenderer.isAvailable()) { 17079 // This is set if HW acceleration is requested, even if the current 17080 // process doesn't allow it. This is just to allow app preview 17081 // windows to better match their app. 17082 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 17083 } 17084 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 17085 17086 final int privateFlags2 = mPrivateFlags2; 17087 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 17088 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 17089 } 17090 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 17091 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 17092 } 17093 17094 drawableState = StateSet.get(viewStateIndex); 17095 17096 //noinspection ConstantIfStatement 17097 if (false) { 17098 Log.i("View", "drawableStateIndex=" + viewStateIndex); 17099 Log.i("View", toString() 17100 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 17101 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 17102 + " fo=" + hasFocus() 17103 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 17104 + " wf=" + hasWindowFocus() 17105 + ": " + Arrays.toString(drawableState)); 17106 } 17107 17108 if (extraSpace == 0) { 17109 return drawableState; 17110 } 17111 17112 final int[] fullState; 17113 if (drawableState != null) { 17114 fullState = new int[drawableState.length + extraSpace]; 17115 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 17116 } else { 17117 fullState = new int[extraSpace]; 17118 } 17119 17120 return fullState; 17121 } 17122 17123 /** 17124 * Merge your own state values in <var>additionalState</var> into the base 17125 * state values <var>baseState</var> that were returned by 17126 * {@link #onCreateDrawableState(int)}. 17127 * 17128 * @param baseState The base state values returned by 17129 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 17130 * own additional state values. 17131 * 17132 * @param additionalState The additional state values you would like 17133 * added to <var>baseState</var>; this array is not modified. 17134 * 17135 * @return As a convenience, the <var>baseState</var> array you originally 17136 * passed into the function is returned. 17137 * 17138 * @see #onCreateDrawableState(int) 17139 */ 17140 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 17141 final int N = baseState.length; 17142 int i = N - 1; 17143 while (i >= 0 && baseState[i] == 0) { 17144 i--; 17145 } 17146 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 17147 return baseState; 17148 } 17149 17150 /** 17151 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 17152 * on all Drawable objects associated with this view. 17153 * <p> 17154 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 17155 * attached to this view. 17156 */ 17157 @CallSuper 17158 public void jumpDrawablesToCurrentState() { 17159 if (mBackground != null) { 17160 mBackground.jumpToCurrentState(); 17161 } 17162 if (mStateListAnimator != null) { 17163 mStateListAnimator.jumpToCurrentState(); 17164 } 17165 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17166 mForegroundInfo.mDrawable.jumpToCurrentState(); 17167 } 17168 } 17169 17170 /** 17171 * Sets the background color for this view. 17172 * @param color the color of the background 17173 */ 17174 @RemotableViewMethod 17175 public void setBackgroundColor(@ColorInt int color) { 17176 if (mBackground instanceof ColorDrawable) { 17177 ((ColorDrawable) mBackground.mutate()).setColor(color); 17178 computeOpaqueFlags(); 17179 mBackgroundResource = 0; 17180 } else { 17181 setBackground(new ColorDrawable(color)); 17182 } 17183 } 17184 17185 /** 17186 * Set the background to a given resource. The resource should refer to 17187 * a Drawable object or 0 to remove the background. 17188 * @param resid The identifier of the resource. 17189 * 17190 * @attr ref android.R.styleable#View_background 17191 */ 17192 @RemotableViewMethod 17193 public void setBackgroundResource(@DrawableRes int resid) { 17194 if (resid != 0 && resid == mBackgroundResource) { 17195 return; 17196 } 17197 17198 Drawable d = null; 17199 if (resid != 0) { 17200 d = mContext.getDrawable(resid); 17201 } 17202 setBackground(d); 17203 17204 mBackgroundResource = resid; 17205 } 17206 17207 /** 17208 * Set the background to a given Drawable, or remove the background. If the 17209 * background has padding, this View's padding is set to the background's 17210 * padding. However, when a background is removed, this View's padding isn't 17211 * touched. If setting the padding is desired, please use 17212 * {@link #setPadding(int, int, int, int)}. 17213 * 17214 * @param background The Drawable to use as the background, or null to remove the 17215 * background 17216 */ 17217 public void setBackground(Drawable background) { 17218 //noinspection deprecation 17219 setBackgroundDrawable(background); 17220 } 17221 17222 /** 17223 * @deprecated use {@link #setBackground(Drawable)} instead 17224 */ 17225 @Deprecated 17226 public void setBackgroundDrawable(Drawable background) { 17227 computeOpaqueFlags(); 17228 17229 if (background == mBackground) { 17230 return; 17231 } 17232 17233 boolean requestLayout = false; 17234 17235 mBackgroundResource = 0; 17236 17237 /* 17238 * Regardless of whether we're setting a new background or not, we want 17239 * to clear the previous drawable. 17240 */ 17241 if (mBackground != null) { 17242 mBackground.setCallback(null); 17243 unscheduleDrawable(mBackground); 17244 } 17245 17246 if (background != null) { 17247 Rect padding = sThreadLocal.get(); 17248 if (padding == null) { 17249 padding = new Rect(); 17250 sThreadLocal.set(padding); 17251 } 17252 resetResolvedDrawablesInternal(); 17253 background.setLayoutDirection(getLayoutDirection()); 17254 if (background.getPadding(padding)) { 17255 resetResolvedPaddingInternal(); 17256 switch (background.getLayoutDirection()) { 17257 case LAYOUT_DIRECTION_RTL: 17258 mUserPaddingLeftInitial = padding.right; 17259 mUserPaddingRightInitial = padding.left; 17260 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 17261 break; 17262 case LAYOUT_DIRECTION_LTR: 17263 default: 17264 mUserPaddingLeftInitial = padding.left; 17265 mUserPaddingRightInitial = padding.right; 17266 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 17267 } 17268 mLeftPaddingDefined = false; 17269 mRightPaddingDefined = false; 17270 } 17271 17272 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 17273 // if it has a different minimum size, we should layout again 17274 if (mBackground == null 17275 || mBackground.getMinimumHeight() != background.getMinimumHeight() 17276 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 17277 requestLayout = true; 17278 } 17279 17280 background.setCallback(this); 17281 if (background.isStateful()) { 17282 background.setState(getDrawableState()); 17283 } 17284 background.setVisible(getVisibility() == VISIBLE, false); 17285 mBackground = background; 17286 17287 applyBackgroundTint(); 17288 17289 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 17290 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 17291 requestLayout = true; 17292 } 17293 } else { 17294 /* Remove the background */ 17295 mBackground = null; 17296 if ((mViewFlags & WILL_NOT_DRAW) != 0 17297 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 17298 mPrivateFlags |= PFLAG_SKIP_DRAW; 17299 } 17300 17301 /* 17302 * When the background is set, we try to apply its padding to this 17303 * View. When the background is removed, we don't touch this View's 17304 * padding. This is noted in the Javadocs. Hence, we don't need to 17305 * requestLayout(), the invalidate() below is sufficient. 17306 */ 17307 17308 // The old background's minimum size could have affected this 17309 // View's layout, so let's requestLayout 17310 requestLayout = true; 17311 } 17312 17313 computeOpaqueFlags(); 17314 17315 if (requestLayout) { 17316 requestLayout(); 17317 } 17318 17319 mBackgroundSizeChanged = true; 17320 invalidate(true); 17321 } 17322 17323 /** 17324 * Gets the background drawable 17325 * 17326 * @return The drawable used as the background for this view, if any. 17327 * 17328 * @see #setBackground(Drawable) 17329 * 17330 * @attr ref android.R.styleable#View_background 17331 */ 17332 public Drawable getBackground() { 17333 return mBackground; 17334 } 17335 17336 /** 17337 * Applies a tint to the background drawable. Does not modify the current tint 17338 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 17339 * <p> 17340 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 17341 * mutate the drawable and apply the specified tint and tint mode using 17342 * {@link Drawable#setTintList(ColorStateList)}. 17343 * 17344 * @param tint the tint to apply, may be {@code null} to clear tint 17345 * 17346 * @attr ref android.R.styleable#View_backgroundTint 17347 * @see #getBackgroundTintList() 17348 * @see Drawable#setTintList(ColorStateList) 17349 */ 17350 public void setBackgroundTintList(@Nullable ColorStateList tint) { 17351 if (mBackgroundTint == null) { 17352 mBackgroundTint = new TintInfo(); 17353 } 17354 mBackgroundTint.mTintList = tint; 17355 mBackgroundTint.mHasTintList = true; 17356 17357 applyBackgroundTint(); 17358 } 17359 17360 /** 17361 * Return the tint applied to the background drawable, if specified. 17362 * 17363 * @return the tint applied to the background drawable 17364 * @attr ref android.R.styleable#View_backgroundTint 17365 * @see #setBackgroundTintList(ColorStateList) 17366 */ 17367 @Nullable 17368 public ColorStateList getBackgroundTintList() { 17369 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 17370 } 17371 17372 /** 17373 * Specifies the blending mode used to apply the tint specified by 17374 * {@link #setBackgroundTintList(ColorStateList)}} to the background 17375 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 17376 * 17377 * @param tintMode the blending mode used to apply the tint, may be 17378 * {@code null} to clear tint 17379 * @attr ref android.R.styleable#View_backgroundTintMode 17380 * @see #getBackgroundTintMode() 17381 * @see Drawable#setTintMode(PorterDuff.Mode) 17382 */ 17383 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 17384 if (mBackgroundTint == null) { 17385 mBackgroundTint = new TintInfo(); 17386 } 17387 mBackgroundTint.mTintMode = tintMode; 17388 mBackgroundTint.mHasTintMode = true; 17389 17390 applyBackgroundTint(); 17391 } 17392 17393 /** 17394 * Return the blending mode used to apply the tint to the background 17395 * drawable, if specified. 17396 * 17397 * @return the blending mode used to apply the tint to the background 17398 * drawable 17399 * @attr ref android.R.styleable#View_backgroundTintMode 17400 * @see #setBackgroundTintMode(PorterDuff.Mode) 17401 */ 17402 @Nullable 17403 public PorterDuff.Mode getBackgroundTintMode() { 17404 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 17405 } 17406 17407 private void applyBackgroundTint() { 17408 if (mBackground != null && mBackgroundTint != null) { 17409 final TintInfo tintInfo = mBackgroundTint; 17410 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 17411 mBackground = mBackground.mutate(); 17412 17413 if (tintInfo.mHasTintList) { 17414 mBackground.setTintList(tintInfo.mTintList); 17415 } 17416 17417 if (tintInfo.mHasTintMode) { 17418 mBackground.setTintMode(tintInfo.mTintMode); 17419 } 17420 17421 // The drawable (or one of its children) may not have been 17422 // stateful before applying the tint, so let's try again. 17423 if (mBackground.isStateful()) { 17424 mBackground.setState(getDrawableState()); 17425 } 17426 } 17427 } 17428 } 17429 17430 /** 17431 * Returns the drawable used as the foreground of this View. The 17432 * foreground drawable, if non-null, is always drawn on top of the view's content. 17433 * 17434 * @return a Drawable or null if no foreground was set 17435 * 17436 * @see #onDrawForeground(Canvas) 17437 */ 17438 public Drawable getForeground() { 17439 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17440 } 17441 17442 /** 17443 * Supply a Drawable that is to be rendered on top of all of the content in the view. 17444 * 17445 * @param foreground the Drawable to be drawn on top of the children 17446 * 17447 * @attr ref android.R.styleable#View_foreground 17448 */ 17449 public void setForeground(Drawable foreground) { 17450 if (mForegroundInfo == null) { 17451 if (foreground == null) { 17452 // Nothing to do. 17453 return; 17454 } 17455 mForegroundInfo = new ForegroundInfo(); 17456 } 17457 17458 if (foreground == mForegroundInfo.mDrawable) { 17459 // Nothing to do 17460 return; 17461 } 17462 17463 if (mForegroundInfo.mDrawable != null) { 17464 mForegroundInfo.mDrawable.setCallback(null); 17465 unscheduleDrawable(mForegroundInfo.mDrawable); 17466 } 17467 17468 mForegroundInfo.mDrawable = foreground; 17469 mForegroundInfo.mBoundsChanged = true; 17470 if (foreground != null) { 17471 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 17472 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 17473 } 17474 foreground.setCallback(this); 17475 foreground.setLayoutDirection(getLayoutDirection()); 17476 if (foreground.isStateful()) { 17477 foreground.setState(getDrawableState()); 17478 } 17479 applyForegroundTint(); 17480 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 17481 mPrivateFlags |= PFLAG_SKIP_DRAW; 17482 } 17483 requestLayout(); 17484 invalidate(); 17485 } 17486 17487 /** 17488 * Magic bit used to support features of framework-internal window decor implementation details. 17489 * This used to live exclusively in FrameLayout. 17490 * 17491 * @return true if the foreground should draw inside the padding region or false 17492 * if it should draw inset by the view's padding 17493 * @hide internal use only; only used by FrameLayout and internal screen layouts. 17494 */ 17495 public boolean isForegroundInsidePadding() { 17496 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 17497 } 17498 17499 /** 17500 * Describes how the foreground is positioned. 17501 * 17502 * @return foreground gravity. 17503 * 17504 * @see #setForegroundGravity(int) 17505 * 17506 * @attr ref android.R.styleable#View_foregroundGravity 17507 */ 17508 public int getForegroundGravity() { 17509 return mForegroundInfo != null ? mForegroundInfo.mGravity 17510 : Gravity.START | Gravity.TOP; 17511 } 17512 17513 /** 17514 * Describes how the foreground is positioned. Defaults to START and TOP. 17515 * 17516 * @param gravity see {@link android.view.Gravity} 17517 * 17518 * @see #getForegroundGravity() 17519 * 17520 * @attr ref android.R.styleable#View_foregroundGravity 17521 */ 17522 public void setForegroundGravity(int gravity) { 17523 if (mForegroundInfo == null) { 17524 mForegroundInfo = new ForegroundInfo(); 17525 } 17526 17527 if (mForegroundInfo.mGravity != gravity) { 17528 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 17529 gravity |= Gravity.START; 17530 } 17531 17532 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 17533 gravity |= Gravity.TOP; 17534 } 17535 17536 mForegroundInfo.mGravity = gravity; 17537 requestLayout(); 17538 } 17539 } 17540 17541 /** 17542 * Applies a tint to the foreground drawable. Does not modify the current tint 17543 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 17544 * <p> 17545 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 17546 * mutate the drawable and apply the specified tint and tint mode using 17547 * {@link Drawable#setTintList(ColorStateList)}. 17548 * 17549 * @param tint the tint to apply, may be {@code null} to clear tint 17550 * 17551 * @attr ref android.R.styleable#View_foregroundTint 17552 * @see #getForegroundTintList() 17553 * @see Drawable#setTintList(ColorStateList) 17554 */ 17555 public void setForegroundTintList(@Nullable ColorStateList tint) { 17556 if (mForegroundInfo == null) { 17557 mForegroundInfo = new ForegroundInfo(); 17558 } 17559 if (mForegroundInfo.mTintInfo == null) { 17560 mForegroundInfo.mTintInfo = new TintInfo(); 17561 } 17562 mForegroundInfo.mTintInfo.mTintList = tint; 17563 mForegroundInfo.mTintInfo.mHasTintList = true; 17564 17565 applyForegroundTint(); 17566 } 17567 17568 /** 17569 * Return the tint applied to the foreground drawable, if specified. 17570 * 17571 * @return the tint applied to the foreground drawable 17572 * @attr ref android.R.styleable#View_foregroundTint 17573 * @see #setForegroundTintList(ColorStateList) 17574 */ 17575 @Nullable 17576 public ColorStateList getForegroundTintList() { 17577 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 17578 ? mForegroundInfo.mTintInfo.mTintList : null; 17579 } 17580 17581 /** 17582 * Specifies the blending mode used to apply the tint specified by 17583 * {@link #setForegroundTintList(ColorStateList)}} to the background 17584 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 17585 * 17586 * @param tintMode the blending mode used to apply the tint, may be 17587 * {@code null} to clear tint 17588 * @attr ref android.R.styleable#View_foregroundTintMode 17589 * @see #getForegroundTintMode() 17590 * @see Drawable#setTintMode(PorterDuff.Mode) 17591 */ 17592 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 17593 if (mForegroundInfo == null) { 17594 mForegroundInfo = new ForegroundInfo(); 17595 } 17596 if (mForegroundInfo.mTintInfo == null) { 17597 mForegroundInfo.mTintInfo = new TintInfo(); 17598 } 17599 mForegroundInfo.mTintInfo.mTintMode = tintMode; 17600 mForegroundInfo.mTintInfo.mHasTintMode = true; 17601 17602 applyForegroundTint(); 17603 } 17604 17605 /** 17606 * Return the blending mode used to apply the tint to the foreground 17607 * drawable, if specified. 17608 * 17609 * @return the blending mode used to apply the tint to the foreground 17610 * drawable 17611 * @attr ref android.R.styleable#View_foregroundTintMode 17612 * @see #setForegroundTintMode(PorterDuff.Mode) 17613 */ 17614 @Nullable 17615 public PorterDuff.Mode getForegroundTintMode() { 17616 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 17617 ? mForegroundInfo.mTintInfo.mTintMode : null; 17618 } 17619 17620 private void applyForegroundTint() { 17621 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 17622 && mForegroundInfo.mTintInfo != null) { 17623 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 17624 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 17625 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 17626 17627 if (tintInfo.mHasTintList) { 17628 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 17629 } 17630 17631 if (tintInfo.mHasTintMode) { 17632 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 17633 } 17634 17635 // The drawable (or one of its children) may not have been 17636 // stateful before applying the tint, so let's try again. 17637 if (mForegroundInfo.mDrawable.isStateful()) { 17638 mForegroundInfo.mDrawable.setState(getDrawableState()); 17639 } 17640 } 17641 } 17642 } 17643 17644 /** 17645 * Draw any foreground content for this view. 17646 * 17647 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 17648 * drawable or other view-specific decorations. The foreground is drawn on top of the 17649 * primary view content.</p> 17650 * 17651 * @param canvas canvas to draw into 17652 */ 17653 public void onDrawForeground(Canvas canvas) { 17654 onDrawScrollIndicators(canvas); 17655 onDrawScrollBars(canvas); 17656 17657 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17658 if (foreground != null) { 17659 if (mForegroundInfo.mBoundsChanged) { 17660 mForegroundInfo.mBoundsChanged = false; 17661 final Rect selfBounds = mForegroundInfo.mSelfBounds; 17662 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 17663 17664 if (mForegroundInfo.mInsidePadding) { 17665 selfBounds.set(0, 0, getWidth(), getHeight()); 17666 } else { 17667 selfBounds.set(getPaddingLeft(), getPaddingTop(), 17668 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 17669 } 17670 17671 final int ld = getLayoutDirection(); 17672 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 17673 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 17674 foreground.setBounds(overlayBounds); 17675 } 17676 17677 foreground.draw(canvas); 17678 } 17679 } 17680 17681 /** 17682 * Sets the padding. The view may add on the space required to display 17683 * the scrollbars, depending on the style and visibility of the scrollbars. 17684 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 17685 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 17686 * from the values set in this call. 17687 * 17688 * @attr ref android.R.styleable#View_padding 17689 * @attr ref android.R.styleable#View_paddingBottom 17690 * @attr ref android.R.styleable#View_paddingLeft 17691 * @attr ref android.R.styleable#View_paddingRight 17692 * @attr ref android.R.styleable#View_paddingTop 17693 * @param left the left padding in pixels 17694 * @param top the top padding in pixels 17695 * @param right the right padding in pixels 17696 * @param bottom the bottom padding in pixels 17697 */ 17698 public void setPadding(int left, int top, int right, int bottom) { 17699 resetResolvedPaddingInternal(); 17700 17701 mUserPaddingStart = UNDEFINED_PADDING; 17702 mUserPaddingEnd = UNDEFINED_PADDING; 17703 17704 mUserPaddingLeftInitial = left; 17705 mUserPaddingRightInitial = right; 17706 17707 mLeftPaddingDefined = true; 17708 mRightPaddingDefined = true; 17709 17710 internalSetPadding(left, top, right, bottom); 17711 } 17712 17713 /** 17714 * @hide 17715 */ 17716 protected void internalSetPadding(int left, int top, int right, int bottom) { 17717 mUserPaddingLeft = left; 17718 mUserPaddingRight = right; 17719 mUserPaddingBottom = bottom; 17720 17721 final int viewFlags = mViewFlags; 17722 boolean changed = false; 17723 17724 // Common case is there are no scroll bars. 17725 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 17726 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 17727 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 17728 ? 0 : getVerticalScrollbarWidth(); 17729 switch (mVerticalScrollbarPosition) { 17730 case SCROLLBAR_POSITION_DEFAULT: 17731 if (isLayoutRtl()) { 17732 left += offset; 17733 } else { 17734 right += offset; 17735 } 17736 break; 17737 case SCROLLBAR_POSITION_RIGHT: 17738 right += offset; 17739 break; 17740 case SCROLLBAR_POSITION_LEFT: 17741 left += offset; 17742 break; 17743 } 17744 } 17745 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 17746 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 17747 ? 0 : getHorizontalScrollbarHeight(); 17748 } 17749 } 17750 17751 if (mPaddingLeft != left) { 17752 changed = true; 17753 mPaddingLeft = left; 17754 } 17755 if (mPaddingTop != top) { 17756 changed = true; 17757 mPaddingTop = top; 17758 } 17759 if (mPaddingRight != right) { 17760 changed = true; 17761 mPaddingRight = right; 17762 } 17763 if (mPaddingBottom != bottom) { 17764 changed = true; 17765 mPaddingBottom = bottom; 17766 } 17767 17768 if (changed) { 17769 requestLayout(); 17770 invalidateOutline(); 17771 } 17772 } 17773 17774 /** 17775 * Sets the relative padding. The view may add on the space required to display 17776 * the scrollbars, depending on the style and visibility of the scrollbars. 17777 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 17778 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 17779 * from the values set in this call. 17780 * 17781 * @attr ref android.R.styleable#View_padding 17782 * @attr ref android.R.styleable#View_paddingBottom 17783 * @attr ref android.R.styleable#View_paddingStart 17784 * @attr ref android.R.styleable#View_paddingEnd 17785 * @attr ref android.R.styleable#View_paddingTop 17786 * @param start the start padding in pixels 17787 * @param top the top padding in pixels 17788 * @param end the end padding in pixels 17789 * @param bottom the bottom padding in pixels 17790 */ 17791 public void setPaddingRelative(int start, int top, int end, int bottom) { 17792 resetResolvedPaddingInternal(); 17793 17794 mUserPaddingStart = start; 17795 mUserPaddingEnd = end; 17796 mLeftPaddingDefined = true; 17797 mRightPaddingDefined = true; 17798 17799 switch(getLayoutDirection()) { 17800 case LAYOUT_DIRECTION_RTL: 17801 mUserPaddingLeftInitial = end; 17802 mUserPaddingRightInitial = start; 17803 internalSetPadding(end, top, start, bottom); 17804 break; 17805 case LAYOUT_DIRECTION_LTR: 17806 default: 17807 mUserPaddingLeftInitial = start; 17808 mUserPaddingRightInitial = end; 17809 internalSetPadding(start, top, end, bottom); 17810 } 17811 } 17812 17813 /** 17814 * Returns the top padding of this view. 17815 * 17816 * @return the top padding in pixels 17817 */ 17818 public int getPaddingTop() { 17819 return mPaddingTop; 17820 } 17821 17822 /** 17823 * Returns the bottom padding of this view. If there are inset and enabled 17824 * scrollbars, this value may include the space required to display the 17825 * scrollbars as well. 17826 * 17827 * @return the bottom padding in pixels 17828 */ 17829 public int getPaddingBottom() { 17830 return mPaddingBottom; 17831 } 17832 17833 /** 17834 * Returns the left padding of this view. If there are inset and enabled 17835 * scrollbars, this value may include the space required to display the 17836 * scrollbars as well. 17837 * 17838 * @return the left padding in pixels 17839 */ 17840 public int getPaddingLeft() { 17841 if (!isPaddingResolved()) { 17842 resolvePadding(); 17843 } 17844 return mPaddingLeft; 17845 } 17846 17847 /** 17848 * Returns the start padding of this view depending on its resolved layout direction. 17849 * If there are inset and enabled scrollbars, this value may include the space 17850 * required to display the scrollbars as well. 17851 * 17852 * @return the start padding in pixels 17853 */ 17854 public int getPaddingStart() { 17855 if (!isPaddingResolved()) { 17856 resolvePadding(); 17857 } 17858 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 17859 mPaddingRight : mPaddingLeft; 17860 } 17861 17862 /** 17863 * Returns the right padding of this view. If there are inset and enabled 17864 * scrollbars, this value may include the space required to display the 17865 * scrollbars as well. 17866 * 17867 * @return the right padding in pixels 17868 */ 17869 public int getPaddingRight() { 17870 if (!isPaddingResolved()) { 17871 resolvePadding(); 17872 } 17873 return mPaddingRight; 17874 } 17875 17876 /** 17877 * Returns the end padding of this view depending on its resolved layout direction. 17878 * If there are inset and enabled scrollbars, this value may include the space 17879 * required to display the scrollbars as well. 17880 * 17881 * @return the end padding in pixels 17882 */ 17883 public int getPaddingEnd() { 17884 if (!isPaddingResolved()) { 17885 resolvePadding(); 17886 } 17887 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 17888 mPaddingLeft : mPaddingRight; 17889 } 17890 17891 /** 17892 * Return if the padding has been set through relative values 17893 * {@link #setPaddingRelative(int, int, int, int)} or through 17894 * @attr ref android.R.styleable#View_paddingStart or 17895 * @attr ref android.R.styleable#View_paddingEnd 17896 * 17897 * @return true if the padding is relative or false if it is not. 17898 */ 17899 public boolean isPaddingRelative() { 17900 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 17901 } 17902 17903 Insets computeOpticalInsets() { 17904 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 17905 } 17906 17907 /** 17908 * @hide 17909 */ 17910 public void resetPaddingToInitialValues() { 17911 if (isRtlCompatibilityMode()) { 17912 mPaddingLeft = mUserPaddingLeftInitial; 17913 mPaddingRight = mUserPaddingRightInitial; 17914 return; 17915 } 17916 if (isLayoutRtl()) { 17917 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 17918 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 17919 } else { 17920 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 17921 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 17922 } 17923 } 17924 17925 /** 17926 * @hide 17927 */ 17928 public Insets getOpticalInsets() { 17929 if (mLayoutInsets == null) { 17930 mLayoutInsets = computeOpticalInsets(); 17931 } 17932 return mLayoutInsets; 17933 } 17934 17935 /** 17936 * Set this view's optical insets. 17937 * 17938 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 17939 * property. Views that compute their own optical insets should call it as part of measurement. 17940 * This method does not request layout. If you are setting optical insets outside of 17941 * measure/layout itself you will want to call requestLayout() yourself. 17942 * </p> 17943 * @hide 17944 */ 17945 public void setOpticalInsets(Insets insets) { 17946 mLayoutInsets = insets; 17947 } 17948 17949 /** 17950 * Changes the selection state of this view. A view can be selected or not. 17951 * Note that selection is not the same as focus. Views are typically 17952 * selected in the context of an AdapterView like ListView or GridView; 17953 * the selected view is the view that is highlighted. 17954 * 17955 * @param selected true if the view must be selected, false otherwise 17956 */ 17957 public void setSelected(boolean selected) { 17958 //noinspection DoubleNegation 17959 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 17960 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 17961 if (!selected) resetPressedState(); 17962 invalidate(true); 17963 refreshDrawableState(); 17964 dispatchSetSelected(selected); 17965 if (selected) { 17966 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 17967 } else { 17968 notifyViewAccessibilityStateChangedIfNeeded( 17969 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 17970 } 17971 } 17972 } 17973 17974 /** 17975 * Dispatch setSelected to all of this View's children. 17976 * 17977 * @see #setSelected(boolean) 17978 * 17979 * @param selected The new selected state 17980 */ 17981 protected void dispatchSetSelected(boolean selected) { 17982 } 17983 17984 /** 17985 * Indicates the selection state of this view. 17986 * 17987 * @return true if the view is selected, false otherwise 17988 */ 17989 @ViewDebug.ExportedProperty 17990 public boolean isSelected() { 17991 return (mPrivateFlags & PFLAG_SELECTED) != 0; 17992 } 17993 17994 /** 17995 * Changes the activated state of this view. A view can be activated or not. 17996 * Note that activation is not the same as selection. Selection is 17997 * a transient property, representing the view (hierarchy) the user is 17998 * currently interacting with. Activation is a longer-term state that the 17999 * user can move views in and out of. For example, in a list view with 18000 * single or multiple selection enabled, the views in the current selection 18001 * set are activated. (Um, yeah, we are deeply sorry about the terminology 18002 * here.) The activated state is propagated down to children of the view it 18003 * is set on. 18004 * 18005 * @param activated true if the view must be activated, false otherwise 18006 */ 18007 public void setActivated(boolean activated) { 18008 //noinspection DoubleNegation 18009 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 18010 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 18011 invalidate(true); 18012 refreshDrawableState(); 18013 dispatchSetActivated(activated); 18014 } 18015 } 18016 18017 /** 18018 * Dispatch setActivated to all of this View's children. 18019 * 18020 * @see #setActivated(boolean) 18021 * 18022 * @param activated The new activated state 18023 */ 18024 protected void dispatchSetActivated(boolean activated) { 18025 } 18026 18027 /** 18028 * Indicates the activation state of this view. 18029 * 18030 * @return true if the view is activated, false otherwise 18031 */ 18032 @ViewDebug.ExportedProperty 18033 public boolean isActivated() { 18034 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 18035 } 18036 18037 /** 18038 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 18039 * observer can be used to get notifications when global events, like 18040 * layout, happen. 18041 * 18042 * The returned ViewTreeObserver observer is not guaranteed to remain 18043 * valid for the lifetime of this View. If the caller of this method keeps 18044 * a long-lived reference to ViewTreeObserver, it should always check for 18045 * the return value of {@link ViewTreeObserver#isAlive()}. 18046 * 18047 * @return The ViewTreeObserver for this view's hierarchy. 18048 */ 18049 public ViewTreeObserver getViewTreeObserver() { 18050 if (mAttachInfo != null) { 18051 return mAttachInfo.mTreeObserver; 18052 } 18053 if (mFloatingTreeObserver == null) { 18054 mFloatingTreeObserver = new ViewTreeObserver(); 18055 } 18056 return mFloatingTreeObserver; 18057 } 18058 18059 /** 18060 * <p>Finds the topmost view in the current view hierarchy.</p> 18061 * 18062 * @return the topmost view containing this view 18063 */ 18064 public View getRootView() { 18065 if (mAttachInfo != null) { 18066 final View v = mAttachInfo.mRootView; 18067 if (v != null) { 18068 return v; 18069 } 18070 } 18071 18072 View parent = this; 18073 18074 while (parent.mParent != null && parent.mParent instanceof View) { 18075 parent = (View) parent.mParent; 18076 } 18077 18078 return parent; 18079 } 18080 18081 /** 18082 * Transforms a motion event from view-local coordinates to on-screen 18083 * coordinates. 18084 * 18085 * @param ev the view-local motion event 18086 * @return false if the transformation could not be applied 18087 * @hide 18088 */ 18089 public boolean toGlobalMotionEvent(MotionEvent ev) { 18090 final AttachInfo info = mAttachInfo; 18091 if (info == null) { 18092 return false; 18093 } 18094 18095 final Matrix m = info.mTmpMatrix; 18096 m.set(Matrix.IDENTITY_MATRIX); 18097 transformMatrixToGlobal(m); 18098 ev.transform(m); 18099 return true; 18100 } 18101 18102 /** 18103 * Transforms a motion event from on-screen coordinates to view-local 18104 * coordinates. 18105 * 18106 * @param ev the on-screen motion event 18107 * @return false if the transformation could not be applied 18108 * @hide 18109 */ 18110 public boolean toLocalMotionEvent(MotionEvent ev) { 18111 final AttachInfo info = mAttachInfo; 18112 if (info == null) { 18113 return false; 18114 } 18115 18116 final Matrix m = info.mTmpMatrix; 18117 m.set(Matrix.IDENTITY_MATRIX); 18118 transformMatrixToLocal(m); 18119 ev.transform(m); 18120 return true; 18121 } 18122 18123 /** 18124 * Modifies the input matrix such that it maps view-local coordinates to 18125 * on-screen coordinates. 18126 * 18127 * @param m input matrix to modify 18128 * @hide 18129 */ 18130 public void transformMatrixToGlobal(Matrix m) { 18131 final ViewParent parent = mParent; 18132 if (parent instanceof View) { 18133 final View vp = (View) parent; 18134 vp.transformMatrixToGlobal(m); 18135 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 18136 } else if (parent instanceof ViewRootImpl) { 18137 final ViewRootImpl vr = (ViewRootImpl) parent; 18138 vr.transformMatrixToGlobal(m); 18139 m.preTranslate(0, -vr.mCurScrollY); 18140 } 18141 18142 m.preTranslate(mLeft, mTop); 18143 18144 if (!hasIdentityMatrix()) { 18145 m.preConcat(getMatrix()); 18146 } 18147 } 18148 18149 /** 18150 * Modifies the input matrix such that it maps on-screen coordinates to 18151 * view-local coordinates. 18152 * 18153 * @param m input matrix to modify 18154 * @hide 18155 */ 18156 public void transformMatrixToLocal(Matrix m) { 18157 final ViewParent parent = mParent; 18158 if (parent instanceof View) { 18159 final View vp = (View) parent; 18160 vp.transformMatrixToLocal(m); 18161 m.postTranslate(vp.mScrollX, vp.mScrollY); 18162 } else if (parent instanceof ViewRootImpl) { 18163 final ViewRootImpl vr = (ViewRootImpl) parent; 18164 vr.transformMatrixToLocal(m); 18165 m.postTranslate(0, vr.mCurScrollY); 18166 } 18167 18168 m.postTranslate(-mLeft, -mTop); 18169 18170 if (!hasIdentityMatrix()) { 18171 m.postConcat(getInverseMatrix()); 18172 } 18173 } 18174 18175 /** 18176 * @hide 18177 */ 18178 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 18179 @ViewDebug.IntToString(from = 0, to = "x"), 18180 @ViewDebug.IntToString(from = 1, to = "y") 18181 }) 18182 public int[] getLocationOnScreen() { 18183 int[] location = new int[2]; 18184 getLocationOnScreen(location); 18185 return location; 18186 } 18187 18188 /** 18189 * <p>Computes the coordinates of this view on the screen. The argument 18190 * must be an array of two integers. After the method returns, the array 18191 * contains the x and y location in that order.</p> 18192 * 18193 * @param location an array of two integers in which to hold the coordinates 18194 */ 18195 public void getLocationOnScreen(@Size(2) int[] location) { 18196 getLocationInWindow(location); 18197 18198 final AttachInfo info = mAttachInfo; 18199 if (info != null) { 18200 location[0] += info.mWindowLeft; 18201 location[1] += info.mWindowTop; 18202 } 18203 } 18204 18205 /** 18206 * <p>Computes the coordinates of this view in its window. The argument 18207 * must be an array of two integers. After the method returns, the array 18208 * contains the x and y location in that order.</p> 18209 * 18210 * @param location an array of two integers in which to hold the coordinates 18211 */ 18212 public void getLocationInWindow(@Size(2) int[] location) { 18213 if (location == null || location.length < 2) { 18214 throw new IllegalArgumentException("location must be an array of two integers"); 18215 } 18216 18217 if (mAttachInfo == null) { 18218 // When the view is not attached to a window, this method does not make sense 18219 location[0] = location[1] = 0; 18220 return; 18221 } 18222 18223 float[] position = mAttachInfo.mTmpTransformLocation; 18224 position[0] = position[1] = 0.0f; 18225 18226 if (!hasIdentityMatrix()) { 18227 getMatrix().mapPoints(position); 18228 } 18229 18230 position[0] += mLeft; 18231 position[1] += mTop; 18232 18233 ViewParent viewParent = mParent; 18234 while (viewParent instanceof View) { 18235 final View view = (View) viewParent; 18236 18237 position[0] -= view.mScrollX; 18238 position[1] -= view.mScrollY; 18239 18240 if (!view.hasIdentityMatrix()) { 18241 view.getMatrix().mapPoints(position); 18242 } 18243 18244 position[0] += view.mLeft; 18245 position[1] += view.mTop; 18246 18247 viewParent = view.mParent; 18248 } 18249 18250 if (viewParent instanceof ViewRootImpl) { 18251 // *cough* 18252 final ViewRootImpl vr = (ViewRootImpl) viewParent; 18253 position[1] -= vr.mCurScrollY; 18254 } 18255 18256 location[0] = (int) (position[0] + 0.5f); 18257 location[1] = (int) (position[1] + 0.5f); 18258 } 18259 18260 /** 18261 * {@hide} 18262 * @param id the id of the view to be found 18263 * @return the view of the specified id, null if cannot be found 18264 */ 18265 protected View findViewTraversal(@IdRes int id) { 18266 if (id == mID) { 18267 return this; 18268 } 18269 return null; 18270 } 18271 18272 /** 18273 * {@hide} 18274 * @param tag the tag of the view to be found 18275 * @return the view of specified tag, null if cannot be found 18276 */ 18277 protected View findViewWithTagTraversal(Object tag) { 18278 if (tag != null && tag.equals(mTag)) { 18279 return this; 18280 } 18281 return null; 18282 } 18283 18284 /** 18285 * {@hide} 18286 * @param predicate The predicate to evaluate. 18287 * @param childToSkip If not null, ignores this child during the recursive traversal. 18288 * @return The first view that matches the predicate or null. 18289 */ 18290 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 18291 if (predicate.apply(this)) { 18292 return this; 18293 } 18294 return null; 18295 } 18296 18297 /** 18298 * Look for a child view with the given id. If this view has the given 18299 * id, return this view. 18300 * 18301 * @param id The id to search for. 18302 * @return The view that has the given id in the hierarchy or null 18303 */ 18304 @Nullable 18305 public final View findViewById(@IdRes int id) { 18306 if (id < 0) { 18307 return null; 18308 } 18309 return findViewTraversal(id); 18310 } 18311 18312 /** 18313 * Finds a view by its unuque and stable accessibility id. 18314 * 18315 * @param accessibilityId The searched accessibility id. 18316 * @return The found view. 18317 */ 18318 final View findViewByAccessibilityId(int accessibilityId) { 18319 if (accessibilityId < 0) { 18320 return null; 18321 } 18322 View view = findViewByAccessibilityIdTraversal(accessibilityId); 18323 if (view != null) { 18324 return view.includeForAccessibility() ? view : null; 18325 } 18326 return null; 18327 } 18328 18329 /** 18330 * Performs the traversal to find a view by its unuque and stable accessibility id. 18331 * 18332 * <strong>Note:</strong>This method does not stop at the root namespace 18333 * boundary since the user can touch the screen at an arbitrary location 18334 * potentially crossing the root namespace bounday which will send an 18335 * accessibility event to accessibility services and they should be able 18336 * to obtain the event source. Also accessibility ids are guaranteed to be 18337 * unique in the window. 18338 * 18339 * @param accessibilityId The accessibility id. 18340 * @return The found view. 18341 * 18342 * @hide 18343 */ 18344 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 18345 if (getAccessibilityViewId() == accessibilityId) { 18346 return this; 18347 } 18348 return null; 18349 } 18350 18351 /** 18352 * Look for a child view with the given tag. If this view has the given 18353 * tag, return this view. 18354 * 18355 * @param tag The tag to search for, using "tag.equals(getTag())". 18356 * @return The View that has the given tag in the hierarchy or null 18357 */ 18358 public final View findViewWithTag(Object tag) { 18359 if (tag == null) { 18360 return null; 18361 } 18362 return findViewWithTagTraversal(tag); 18363 } 18364 18365 /** 18366 * {@hide} 18367 * Look for a child view that matches the specified predicate. 18368 * If this view matches the predicate, return this view. 18369 * 18370 * @param predicate The predicate to evaluate. 18371 * @return The first view that matches the predicate or null. 18372 */ 18373 public final View findViewByPredicate(Predicate<View> predicate) { 18374 return findViewByPredicateTraversal(predicate, null); 18375 } 18376 18377 /** 18378 * {@hide} 18379 * Look for a child view that matches the specified predicate, 18380 * starting with the specified view and its descendents and then 18381 * recusively searching the ancestors and siblings of that view 18382 * until this view is reached. 18383 * 18384 * This method is useful in cases where the predicate does not match 18385 * a single unique view (perhaps multiple views use the same id) 18386 * and we are trying to find the view that is "closest" in scope to the 18387 * starting view. 18388 * 18389 * @param start The view to start from. 18390 * @param predicate The predicate to evaluate. 18391 * @return The first view that matches the predicate or null. 18392 */ 18393 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 18394 View childToSkip = null; 18395 for (;;) { 18396 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 18397 if (view != null || start == this) { 18398 return view; 18399 } 18400 18401 ViewParent parent = start.getParent(); 18402 if (parent == null || !(parent instanceof View)) { 18403 return null; 18404 } 18405 18406 childToSkip = start; 18407 start = (View) parent; 18408 } 18409 } 18410 18411 /** 18412 * Sets the identifier for this view. The identifier does not have to be 18413 * unique in this view's hierarchy. The identifier should be a positive 18414 * number. 18415 * 18416 * @see #NO_ID 18417 * @see #getId() 18418 * @see #findViewById(int) 18419 * 18420 * @param id a number used to identify the view 18421 * 18422 * @attr ref android.R.styleable#View_id 18423 */ 18424 public void setId(@IdRes int id) { 18425 mID = id; 18426 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 18427 mID = generateViewId(); 18428 } 18429 } 18430 18431 /** 18432 * {@hide} 18433 * 18434 * @param isRoot true if the view belongs to the root namespace, false 18435 * otherwise 18436 */ 18437 public void setIsRootNamespace(boolean isRoot) { 18438 if (isRoot) { 18439 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 18440 } else { 18441 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 18442 } 18443 } 18444 18445 /** 18446 * {@hide} 18447 * 18448 * @return true if the view belongs to the root namespace, false otherwise 18449 */ 18450 public boolean isRootNamespace() { 18451 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 18452 } 18453 18454 /** 18455 * Returns this view's identifier. 18456 * 18457 * @return a positive integer used to identify the view or {@link #NO_ID} 18458 * if the view has no ID 18459 * 18460 * @see #setId(int) 18461 * @see #findViewById(int) 18462 * @attr ref android.R.styleable#View_id 18463 */ 18464 @IdRes 18465 @ViewDebug.CapturedViewProperty 18466 public int getId() { 18467 return mID; 18468 } 18469 18470 /** 18471 * Returns this view's tag. 18472 * 18473 * @return the Object stored in this view as a tag, or {@code null} if not 18474 * set 18475 * 18476 * @see #setTag(Object) 18477 * @see #getTag(int) 18478 */ 18479 @ViewDebug.ExportedProperty 18480 public Object getTag() { 18481 return mTag; 18482 } 18483 18484 /** 18485 * Sets the tag associated with this view. A tag can be used to mark 18486 * a view in its hierarchy and does not have to be unique within the 18487 * hierarchy. Tags can also be used to store data within a view without 18488 * resorting to another data structure. 18489 * 18490 * @param tag an Object to tag the view with 18491 * 18492 * @see #getTag() 18493 * @see #setTag(int, Object) 18494 */ 18495 public void setTag(final Object tag) { 18496 mTag = tag; 18497 } 18498 18499 /** 18500 * Returns the tag associated with this view and the specified key. 18501 * 18502 * @param key The key identifying the tag 18503 * 18504 * @return the Object stored in this view as a tag, or {@code null} if not 18505 * set 18506 * 18507 * @see #setTag(int, Object) 18508 * @see #getTag() 18509 */ 18510 public Object getTag(int key) { 18511 if (mKeyedTags != null) return mKeyedTags.get(key); 18512 return null; 18513 } 18514 18515 /** 18516 * Sets a tag associated with this view and a key. A tag can be used 18517 * to mark a view in its hierarchy and does not have to be unique within 18518 * the hierarchy. Tags can also be used to store data within a view 18519 * without resorting to another data structure. 18520 * 18521 * The specified key should be an id declared in the resources of the 18522 * application to ensure it is unique (see the <a 18523 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 18524 * Keys identified as belonging to 18525 * the Android framework or not associated with any package will cause 18526 * an {@link IllegalArgumentException} to be thrown. 18527 * 18528 * @param key The key identifying the tag 18529 * @param tag An Object to tag the view with 18530 * 18531 * @throws IllegalArgumentException If they specified key is not valid 18532 * 18533 * @see #setTag(Object) 18534 * @see #getTag(int) 18535 */ 18536 public void setTag(int key, final Object tag) { 18537 // If the package id is 0x00 or 0x01, it's either an undefined package 18538 // or a framework id 18539 if ((key >>> 24) < 2) { 18540 throw new IllegalArgumentException("The key must be an application-specific " 18541 + "resource id."); 18542 } 18543 18544 setKeyedTag(key, tag); 18545 } 18546 18547 /** 18548 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 18549 * framework id. 18550 * 18551 * @hide 18552 */ 18553 public void setTagInternal(int key, Object tag) { 18554 if ((key >>> 24) != 0x1) { 18555 throw new IllegalArgumentException("The key must be a framework-specific " 18556 + "resource id."); 18557 } 18558 18559 setKeyedTag(key, tag); 18560 } 18561 18562 private void setKeyedTag(int key, Object tag) { 18563 if (mKeyedTags == null) { 18564 mKeyedTags = new SparseArray<Object>(2); 18565 } 18566 18567 mKeyedTags.put(key, tag); 18568 } 18569 18570 /** 18571 * Prints information about this view in the log output, with the tag 18572 * {@link #VIEW_LOG_TAG}. 18573 * 18574 * @hide 18575 */ 18576 public void debug() { 18577 debug(0); 18578 } 18579 18580 /** 18581 * Prints information about this view in the log output, with the tag 18582 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 18583 * indentation defined by the <code>depth</code>. 18584 * 18585 * @param depth the indentation level 18586 * 18587 * @hide 18588 */ 18589 protected void debug(int depth) { 18590 String output = debugIndent(depth - 1); 18591 18592 output += "+ " + this; 18593 int id = getId(); 18594 if (id != -1) { 18595 output += " (id=" + id + ")"; 18596 } 18597 Object tag = getTag(); 18598 if (tag != null) { 18599 output += " (tag=" + tag + ")"; 18600 } 18601 Log.d(VIEW_LOG_TAG, output); 18602 18603 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 18604 output = debugIndent(depth) + " FOCUSED"; 18605 Log.d(VIEW_LOG_TAG, output); 18606 } 18607 18608 output = debugIndent(depth); 18609 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 18610 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 18611 + "} "; 18612 Log.d(VIEW_LOG_TAG, output); 18613 18614 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 18615 || mPaddingBottom != 0) { 18616 output = debugIndent(depth); 18617 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 18618 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 18619 Log.d(VIEW_LOG_TAG, output); 18620 } 18621 18622 output = debugIndent(depth); 18623 output += "mMeasureWidth=" + mMeasuredWidth + 18624 " mMeasureHeight=" + mMeasuredHeight; 18625 Log.d(VIEW_LOG_TAG, output); 18626 18627 output = debugIndent(depth); 18628 if (mLayoutParams == null) { 18629 output += "BAD! no layout params"; 18630 } else { 18631 output = mLayoutParams.debug(output); 18632 } 18633 Log.d(VIEW_LOG_TAG, output); 18634 18635 output = debugIndent(depth); 18636 output += "flags={"; 18637 output += View.printFlags(mViewFlags); 18638 output += "}"; 18639 Log.d(VIEW_LOG_TAG, output); 18640 18641 output = debugIndent(depth); 18642 output += "privateFlags={"; 18643 output += View.printPrivateFlags(mPrivateFlags); 18644 output += "}"; 18645 Log.d(VIEW_LOG_TAG, output); 18646 } 18647 18648 /** 18649 * Creates a string of whitespaces used for indentation. 18650 * 18651 * @param depth the indentation level 18652 * @return a String containing (depth * 2 + 3) * 2 white spaces 18653 * 18654 * @hide 18655 */ 18656 protected static String debugIndent(int depth) { 18657 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 18658 for (int i = 0; i < (depth * 2) + 3; i++) { 18659 spaces.append(' ').append(' '); 18660 } 18661 return spaces.toString(); 18662 } 18663 18664 /** 18665 * <p>Return the offset of the widget's text baseline from the widget's top 18666 * boundary. If this widget does not support baseline alignment, this 18667 * method returns -1. </p> 18668 * 18669 * @return the offset of the baseline within the widget's bounds or -1 18670 * if baseline alignment is not supported 18671 */ 18672 @ViewDebug.ExportedProperty(category = "layout") 18673 public int getBaseline() { 18674 return -1; 18675 } 18676 18677 /** 18678 * Returns whether the view hierarchy is currently undergoing a layout pass. This 18679 * information is useful to avoid situations such as calling {@link #requestLayout()} during 18680 * a layout pass. 18681 * 18682 * @return whether the view hierarchy is currently undergoing a layout pass 18683 */ 18684 public boolean isInLayout() { 18685 ViewRootImpl viewRoot = getViewRootImpl(); 18686 return (viewRoot != null && viewRoot.isInLayout()); 18687 } 18688 18689 /** 18690 * Call this when something has changed which has invalidated the 18691 * layout of this view. This will schedule a layout pass of the view 18692 * tree. This should not be called while the view hierarchy is currently in a layout 18693 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 18694 * end of the current layout pass (and then layout will run again) or after the current 18695 * frame is drawn and the next layout occurs. 18696 * 18697 * <p>Subclasses which override this method should call the superclass method to 18698 * handle possible request-during-layout errors correctly.</p> 18699 */ 18700 @CallSuper 18701 public void requestLayout() { 18702 if (mMeasureCache != null) mMeasureCache.clear(); 18703 18704 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 18705 // Only trigger request-during-layout logic if this is the view requesting it, 18706 // not the views in its parent hierarchy 18707 ViewRootImpl viewRoot = getViewRootImpl(); 18708 if (viewRoot != null && viewRoot.isInLayout()) { 18709 if (!viewRoot.requestLayoutDuringLayout(this)) { 18710 return; 18711 } 18712 } 18713 mAttachInfo.mViewRequestingLayout = this; 18714 } 18715 18716 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 18717 mPrivateFlags |= PFLAG_INVALIDATED; 18718 18719 if (mParent != null && !mParent.isLayoutRequested()) { 18720 mParent.requestLayout(); 18721 } 18722 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 18723 mAttachInfo.mViewRequestingLayout = null; 18724 } 18725 } 18726 18727 /** 18728 * Forces this view to be laid out during the next layout pass. 18729 * This method does not call requestLayout() or forceLayout() 18730 * on the parent. 18731 */ 18732 public void forceLayout() { 18733 if (mMeasureCache != null) mMeasureCache.clear(); 18734 18735 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 18736 mPrivateFlags |= PFLAG_INVALIDATED; 18737 } 18738 18739 /** 18740 * <p> 18741 * This is called to find out how big a view should be. The parent 18742 * supplies constraint information in the width and height parameters. 18743 * </p> 18744 * 18745 * <p> 18746 * The actual measurement work of a view is performed in 18747 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 18748 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 18749 * </p> 18750 * 18751 * 18752 * @param widthMeasureSpec Horizontal space requirements as imposed by the 18753 * parent 18754 * @param heightMeasureSpec Vertical space requirements as imposed by the 18755 * parent 18756 * 18757 * @see #onMeasure(int, int) 18758 */ 18759 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 18760 boolean optical = isLayoutModeOptical(this); 18761 if (optical != isLayoutModeOptical(mParent)) { 18762 Insets insets = getOpticalInsets(); 18763 int oWidth = insets.left + insets.right; 18764 int oHeight = insets.top + insets.bottom; 18765 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 18766 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 18767 } 18768 18769 // Suppress sign extension for the low bytes 18770 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 18771 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 18772 18773 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 18774 final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY && 18775 MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 18776 final boolean matchingSize = isExactly && 18777 getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) && 18778 getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 18779 if (forceLayout || !matchingSize && 18780 (widthMeasureSpec != mOldWidthMeasureSpec || 18781 heightMeasureSpec != mOldHeightMeasureSpec)) { 18782 18783 // first clears the measured dimension flag 18784 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 18785 18786 resolveRtlPropertiesIfNeeded(); 18787 18788 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 18789 if (cacheIndex < 0 || sIgnoreMeasureCache) { 18790 // measure ourselves, this should set the measured dimension flag back 18791 onMeasure(widthMeasureSpec, heightMeasureSpec); 18792 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 18793 } else { 18794 long value = mMeasureCache.valueAt(cacheIndex); 18795 // Casting a long to int drops the high 32 bits, no mask needed 18796 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 18797 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 18798 } 18799 18800 // flag not set, setMeasuredDimension() was not invoked, we raise 18801 // an exception to warn the developer 18802 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 18803 throw new IllegalStateException("View with id " + getId() + ": " 18804 + getClass().getName() + "#onMeasure() did not set the" 18805 + " measured dimension by calling" 18806 + " setMeasuredDimension()"); 18807 } 18808 18809 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 18810 } 18811 18812 mOldWidthMeasureSpec = widthMeasureSpec; 18813 mOldHeightMeasureSpec = heightMeasureSpec; 18814 18815 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 18816 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 18817 } 18818 18819 /** 18820 * <p> 18821 * Measure the view and its content to determine the measured width and the 18822 * measured height. This method is invoked by {@link #measure(int, int)} and 18823 * should be overridden by subclasses to provide accurate and efficient 18824 * measurement of their contents. 18825 * </p> 18826 * 18827 * <p> 18828 * <strong>CONTRACT:</strong> When overriding this method, you 18829 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 18830 * measured width and height of this view. Failure to do so will trigger an 18831 * <code>IllegalStateException</code>, thrown by 18832 * {@link #measure(int, int)}. Calling the superclass' 18833 * {@link #onMeasure(int, int)} is a valid use. 18834 * </p> 18835 * 18836 * <p> 18837 * The base class implementation of measure defaults to the background size, 18838 * unless a larger size is allowed by the MeasureSpec. Subclasses should 18839 * override {@link #onMeasure(int, int)} to provide better measurements of 18840 * their content. 18841 * </p> 18842 * 18843 * <p> 18844 * If this method is overridden, it is the subclass's responsibility to make 18845 * sure the measured height and width are at least the view's minimum height 18846 * and width ({@link #getSuggestedMinimumHeight()} and 18847 * {@link #getSuggestedMinimumWidth()}). 18848 * </p> 18849 * 18850 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 18851 * The requirements are encoded with 18852 * {@link android.view.View.MeasureSpec}. 18853 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 18854 * The requirements are encoded with 18855 * {@link android.view.View.MeasureSpec}. 18856 * 18857 * @see #getMeasuredWidth() 18858 * @see #getMeasuredHeight() 18859 * @see #setMeasuredDimension(int, int) 18860 * @see #getSuggestedMinimumHeight() 18861 * @see #getSuggestedMinimumWidth() 18862 * @see android.view.View.MeasureSpec#getMode(int) 18863 * @see android.view.View.MeasureSpec#getSize(int) 18864 */ 18865 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 18866 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 18867 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 18868 } 18869 18870 /** 18871 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 18872 * measured width and measured height. Failing to do so will trigger an 18873 * exception at measurement time.</p> 18874 * 18875 * @param measuredWidth The measured width of this view. May be a complex 18876 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18877 * {@link #MEASURED_STATE_TOO_SMALL}. 18878 * @param measuredHeight The measured height of this view. May be a complex 18879 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18880 * {@link #MEASURED_STATE_TOO_SMALL}. 18881 */ 18882 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 18883 boolean optical = isLayoutModeOptical(this); 18884 if (optical != isLayoutModeOptical(mParent)) { 18885 Insets insets = getOpticalInsets(); 18886 int opticalWidth = insets.left + insets.right; 18887 int opticalHeight = insets.top + insets.bottom; 18888 18889 measuredWidth += optical ? opticalWidth : -opticalWidth; 18890 measuredHeight += optical ? opticalHeight : -opticalHeight; 18891 } 18892 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 18893 } 18894 18895 /** 18896 * Sets the measured dimension without extra processing for things like optical bounds. 18897 * Useful for reapplying consistent values that have already been cooked with adjustments 18898 * for optical bounds, etc. such as those from the measurement cache. 18899 * 18900 * @param measuredWidth The measured width of this view. May be a complex 18901 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18902 * {@link #MEASURED_STATE_TOO_SMALL}. 18903 * @param measuredHeight The measured height of this view. May be a complex 18904 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 18905 * {@link #MEASURED_STATE_TOO_SMALL}. 18906 */ 18907 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 18908 mMeasuredWidth = measuredWidth; 18909 mMeasuredHeight = measuredHeight; 18910 18911 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 18912 } 18913 18914 /** 18915 * Merge two states as returned by {@link #getMeasuredState()}. 18916 * @param curState The current state as returned from a view or the result 18917 * of combining multiple views. 18918 * @param newState The new view state to combine. 18919 * @return Returns a new integer reflecting the combination of the two 18920 * states. 18921 */ 18922 public static int combineMeasuredStates(int curState, int newState) { 18923 return curState | newState; 18924 } 18925 18926 /** 18927 * Version of {@link #resolveSizeAndState(int, int, int)} 18928 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 18929 */ 18930 public static int resolveSize(int size, int measureSpec) { 18931 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 18932 } 18933 18934 /** 18935 * Utility to reconcile a desired size and state, with constraints imposed 18936 * by a MeasureSpec. Will take the desired size, unless a different size 18937 * is imposed by the constraints. The returned value is a compound integer, 18938 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 18939 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 18940 * resulting size is smaller than the size the view wants to be. 18941 * 18942 * @param size How big the view wants to be. 18943 * @param measureSpec Constraints imposed by the parent. 18944 * @param childMeasuredState Size information bit mask for the view's 18945 * children. 18946 * @return Size information bit mask as defined by 18947 * {@link #MEASURED_SIZE_MASK} and 18948 * {@link #MEASURED_STATE_TOO_SMALL}. 18949 */ 18950 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 18951 final int specMode = MeasureSpec.getMode(measureSpec); 18952 final int specSize = MeasureSpec.getSize(measureSpec); 18953 final int result; 18954 switch (specMode) { 18955 case MeasureSpec.AT_MOST: 18956 if (specSize < size) { 18957 result = specSize | MEASURED_STATE_TOO_SMALL; 18958 } else { 18959 result = size; 18960 } 18961 break; 18962 case MeasureSpec.EXACTLY: 18963 result = specSize; 18964 break; 18965 case MeasureSpec.UNSPECIFIED: 18966 default: 18967 result = size; 18968 } 18969 return result | (childMeasuredState & MEASURED_STATE_MASK); 18970 } 18971 18972 /** 18973 * Utility to return a default size. Uses the supplied size if the 18974 * MeasureSpec imposed no constraints. Will get larger if allowed 18975 * by the MeasureSpec. 18976 * 18977 * @param size Default size for this view 18978 * @param measureSpec Constraints imposed by the parent 18979 * @return The size this view should be. 18980 */ 18981 public static int getDefaultSize(int size, int measureSpec) { 18982 int result = size; 18983 int specMode = MeasureSpec.getMode(measureSpec); 18984 int specSize = MeasureSpec.getSize(measureSpec); 18985 18986 switch (specMode) { 18987 case MeasureSpec.UNSPECIFIED: 18988 result = size; 18989 break; 18990 case MeasureSpec.AT_MOST: 18991 case MeasureSpec.EXACTLY: 18992 result = specSize; 18993 break; 18994 } 18995 return result; 18996 } 18997 18998 /** 18999 * Returns the suggested minimum height that the view should use. This 19000 * returns the maximum of the view's minimum height 19001 * and the background's minimum height 19002 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 19003 * <p> 19004 * When being used in {@link #onMeasure(int, int)}, the caller should still 19005 * ensure the returned height is within the requirements of the parent. 19006 * 19007 * @return The suggested minimum height of the view. 19008 */ 19009 protected int getSuggestedMinimumHeight() { 19010 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 19011 19012 } 19013 19014 /** 19015 * Returns the suggested minimum width that the view should use. This 19016 * returns the maximum of the view's minimum width) 19017 * and the background's minimum width 19018 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 19019 * <p> 19020 * When being used in {@link #onMeasure(int, int)}, the caller should still 19021 * ensure the returned width is within the requirements of the parent. 19022 * 19023 * @return The suggested minimum width of the view. 19024 */ 19025 protected int getSuggestedMinimumWidth() { 19026 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 19027 } 19028 19029 /** 19030 * Returns the minimum height of the view. 19031 * 19032 * @return the minimum height the view will try to be. 19033 * 19034 * @see #setMinimumHeight(int) 19035 * 19036 * @attr ref android.R.styleable#View_minHeight 19037 */ 19038 public int getMinimumHeight() { 19039 return mMinHeight; 19040 } 19041 19042 /** 19043 * Sets the minimum height of the view. It is not guaranteed the view will 19044 * be able to achieve this minimum height (for example, if its parent layout 19045 * constrains it with less available height). 19046 * 19047 * @param minHeight The minimum height the view will try to be. 19048 * 19049 * @see #getMinimumHeight() 19050 * 19051 * @attr ref android.R.styleable#View_minHeight 19052 */ 19053 public void setMinimumHeight(int minHeight) { 19054 mMinHeight = minHeight; 19055 requestLayout(); 19056 } 19057 19058 /** 19059 * Returns the minimum width of the view. 19060 * 19061 * @return the minimum width the view will try to be. 19062 * 19063 * @see #setMinimumWidth(int) 19064 * 19065 * @attr ref android.R.styleable#View_minWidth 19066 */ 19067 public int getMinimumWidth() { 19068 return mMinWidth; 19069 } 19070 19071 /** 19072 * Sets the minimum width of the view. It is not guaranteed the view will 19073 * be able to achieve this minimum width (for example, if its parent layout 19074 * constrains it with less available width). 19075 * 19076 * @param minWidth The minimum width the view will try to be. 19077 * 19078 * @see #getMinimumWidth() 19079 * 19080 * @attr ref android.R.styleable#View_minWidth 19081 */ 19082 public void setMinimumWidth(int minWidth) { 19083 mMinWidth = minWidth; 19084 requestLayout(); 19085 19086 } 19087 19088 /** 19089 * Get the animation currently associated with this view. 19090 * 19091 * @return The animation that is currently playing or 19092 * scheduled to play for this view. 19093 */ 19094 public Animation getAnimation() { 19095 return mCurrentAnimation; 19096 } 19097 19098 /** 19099 * Start the specified animation now. 19100 * 19101 * @param animation the animation to start now 19102 */ 19103 public void startAnimation(Animation animation) { 19104 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 19105 setAnimation(animation); 19106 invalidateParentCaches(); 19107 invalidate(true); 19108 } 19109 19110 /** 19111 * Cancels any animations for this view. 19112 */ 19113 public void clearAnimation() { 19114 if (mCurrentAnimation != null) { 19115 mCurrentAnimation.detach(); 19116 } 19117 mCurrentAnimation = null; 19118 invalidateParentIfNeeded(); 19119 } 19120 19121 /** 19122 * Sets the next animation to play for this view. 19123 * If you want the animation to play immediately, use 19124 * {@link #startAnimation(android.view.animation.Animation)} instead. 19125 * This method provides allows fine-grained 19126 * control over the start time and invalidation, but you 19127 * must make sure that 1) the animation has a start time set, and 19128 * 2) the view's parent (which controls animations on its children) 19129 * will be invalidated when the animation is supposed to 19130 * start. 19131 * 19132 * @param animation The next animation, or null. 19133 */ 19134 public void setAnimation(Animation animation) { 19135 mCurrentAnimation = animation; 19136 19137 if (animation != null) { 19138 // If the screen is off assume the animation start time is now instead of 19139 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 19140 // would cause the animation to start when the screen turns back on 19141 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 19142 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 19143 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 19144 } 19145 animation.reset(); 19146 } 19147 } 19148 19149 /** 19150 * Invoked by a parent ViewGroup to notify the start of the animation 19151 * currently associated with this view. If you override this method, 19152 * always call super.onAnimationStart(); 19153 * 19154 * @see #setAnimation(android.view.animation.Animation) 19155 * @see #getAnimation() 19156 */ 19157 @CallSuper 19158 protected void onAnimationStart() { 19159 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 19160 } 19161 19162 /** 19163 * Invoked by a parent ViewGroup to notify the end of the animation 19164 * currently associated with this view. If you override this method, 19165 * always call super.onAnimationEnd(); 19166 * 19167 * @see #setAnimation(android.view.animation.Animation) 19168 * @see #getAnimation() 19169 */ 19170 @CallSuper 19171 protected void onAnimationEnd() { 19172 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 19173 } 19174 19175 /** 19176 * Invoked if there is a Transform that involves alpha. Subclass that can 19177 * draw themselves with the specified alpha should return true, and then 19178 * respect that alpha when their onDraw() is called. If this returns false 19179 * then the view may be redirected to draw into an offscreen buffer to 19180 * fulfill the request, which will look fine, but may be slower than if the 19181 * subclass handles it internally. The default implementation returns false. 19182 * 19183 * @param alpha The alpha (0..255) to apply to the view's drawing 19184 * @return true if the view can draw with the specified alpha. 19185 */ 19186 protected boolean onSetAlpha(int alpha) { 19187 return false; 19188 } 19189 19190 /** 19191 * This is used by the RootView to perform an optimization when 19192 * the view hierarchy contains one or several SurfaceView. 19193 * SurfaceView is always considered transparent, but its children are not, 19194 * therefore all View objects remove themselves from the global transparent 19195 * region (passed as a parameter to this function). 19196 * 19197 * @param region The transparent region for this ViewAncestor (window). 19198 * 19199 * @return Returns true if the effective visibility of the view at this 19200 * point is opaque, regardless of the transparent region; returns false 19201 * if it is possible for underlying windows to be seen behind the view. 19202 * 19203 * {@hide} 19204 */ 19205 public boolean gatherTransparentRegion(Region region) { 19206 final AttachInfo attachInfo = mAttachInfo; 19207 if (region != null && attachInfo != null) { 19208 final int pflags = mPrivateFlags; 19209 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 19210 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 19211 // remove it from the transparent region. 19212 final int[] location = attachInfo.mTransparentLocation; 19213 getLocationInWindow(location); 19214 region.op(location[0], location[1], location[0] + mRight - mLeft, 19215 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 19216 } else { 19217 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 19218 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 19219 // the background drawable's non-transparent parts from this transparent region. 19220 applyDrawableToTransparentRegion(mBackground, region); 19221 } 19222 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 19223 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 19224 // Similarly, we remove the foreground drawable's non-transparent parts. 19225 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 19226 } 19227 } 19228 } 19229 return true; 19230 } 19231 19232 /** 19233 * Play a sound effect for this view. 19234 * 19235 * <p>The framework will play sound effects for some built in actions, such as 19236 * clicking, but you may wish to play these effects in your widget, 19237 * for instance, for internal navigation. 19238 * 19239 * <p>The sound effect will only be played if sound effects are enabled by the user, and 19240 * {@link #isSoundEffectsEnabled()} is true. 19241 * 19242 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 19243 */ 19244 public void playSoundEffect(int soundConstant) { 19245 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 19246 return; 19247 } 19248 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 19249 } 19250 19251 /** 19252 * BZZZTT!!1! 19253 * 19254 * <p>Provide haptic feedback to the user for this view. 19255 * 19256 * <p>The framework will provide haptic feedback for some built in actions, 19257 * such as long presses, but you may wish to provide feedback for your 19258 * own widget. 19259 * 19260 * <p>The feedback will only be performed if 19261 * {@link #isHapticFeedbackEnabled()} is true. 19262 * 19263 * @param feedbackConstant One of the constants defined in 19264 * {@link HapticFeedbackConstants} 19265 */ 19266 public boolean performHapticFeedback(int feedbackConstant) { 19267 return performHapticFeedback(feedbackConstant, 0); 19268 } 19269 19270 /** 19271 * BZZZTT!!1! 19272 * 19273 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 19274 * 19275 * @param feedbackConstant One of the constants defined in 19276 * {@link HapticFeedbackConstants} 19277 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 19278 */ 19279 public boolean performHapticFeedback(int feedbackConstant, int flags) { 19280 if (mAttachInfo == null) { 19281 return false; 19282 } 19283 //noinspection SimplifiableIfStatement 19284 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 19285 && !isHapticFeedbackEnabled()) { 19286 return false; 19287 } 19288 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 19289 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 19290 } 19291 19292 /** 19293 * Request that the visibility of the status bar or other screen/window 19294 * decorations be changed. 19295 * 19296 * <p>This method is used to put the over device UI into temporary modes 19297 * where the user's attention is focused more on the application content, 19298 * by dimming or hiding surrounding system affordances. This is typically 19299 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 19300 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 19301 * to be placed behind the action bar (and with these flags other system 19302 * affordances) so that smooth transitions between hiding and showing them 19303 * can be done. 19304 * 19305 * <p>Two representative examples of the use of system UI visibility is 19306 * implementing a content browsing application (like a magazine reader) 19307 * and a video playing application. 19308 * 19309 * <p>The first code shows a typical implementation of a View in a content 19310 * browsing application. In this implementation, the application goes 19311 * into a content-oriented mode by hiding the status bar and action bar, 19312 * and putting the navigation elements into lights out mode. The user can 19313 * then interact with content while in this mode. Such an application should 19314 * provide an easy way for the user to toggle out of the mode (such as to 19315 * check information in the status bar or access notifications). In the 19316 * implementation here, this is done simply by tapping on the content. 19317 * 19318 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 19319 * content} 19320 * 19321 * <p>This second code sample shows a typical implementation of a View 19322 * in a video playing application. In this situation, while the video is 19323 * playing the application would like to go into a complete full-screen mode, 19324 * to use as much of the display as possible for the video. When in this state 19325 * the user can not interact with the application; the system intercepts 19326 * touching on the screen to pop the UI out of full screen mode. See 19327 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 19328 * 19329 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 19330 * content} 19331 * 19332 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19333 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 19334 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 19335 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 19336 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 19337 */ 19338 public void setSystemUiVisibility(int visibility) { 19339 if (visibility != mSystemUiVisibility) { 19340 mSystemUiVisibility = visibility; 19341 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 19342 mParent.recomputeViewAttributes(this); 19343 } 19344 } 19345 } 19346 19347 /** 19348 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 19349 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19350 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 19351 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 19352 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 19353 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 19354 */ 19355 public int getSystemUiVisibility() { 19356 return mSystemUiVisibility; 19357 } 19358 19359 /** 19360 * Returns the current system UI visibility that is currently set for 19361 * the entire window. This is the combination of the 19362 * {@link #setSystemUiVisibility(int)} values supplied by all of the 19363 * views in the window. 19364 */ 19365 public int getWindowSystemUiVisibility() { 19366 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 19367 } 19368 19369 /** 19370 * Override to find out when the window's requested system UI visibility 19371 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 19372 * This is different from the callbacks received through 19373 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 19374 * in that this is only telling you about the local request of the window, 19375 * not the actual values applied by the system. 19376 */ 19377 public void onWindowSystemUiVisibilityChanged(int visible) { 19378 } 19379 19380 /** 19381 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 19382 * the view hierarchy. 19383 */ 19384 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 19385 onWindowSystemUiVisibilityChanged(visible); 19386 } 19387 19388 /** 19389 * Set a listener to receive callbacks when the visibility of the system bar changes. 19390 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 19391 */ 19392 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 19393 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 19394 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 19395 mParent.recomputeViewAttributes(this); 19396 } 19397 } 19398 19399 /** 19400 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 19401 * the view hierarchy. 19402 */ 19403 public void dispatchSystemUiVisibilityChanged(int visibility) { 19404 ListenerInfo li = mListenerInfo; 19405 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 19406 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 19407 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 19408 } 19409 } 19410 19411 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 19412 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 19413 if (val != mSystemUiVisibility) { 19414 setSystemUiVisibility(val); 19415 return true; 19416 } 19417 return false; 19418 } 19419 19420 /** @hide */ 19421 public void setDisabledSystemUiVisibility(int flags) { 19422 if (mAttachInfo != null) { 19423 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 19424 mAttachInfo.mDisabledSystemUiVisibility = flags; 19425 if (mParent != null) { 19426 mParent.recomputeViewAttributes(this); 19427 } 19428 } 19429 } 19430 } 19431 19432 /** 19433 * Creates an image that the system displays during the drag and drop 19434 * operation. This is called a "drag shadow". The default implementation 19435 * for a DragShadowBuilder based on a View returns an image that has exactly the same 19436 * appearance as the given View. The default also positions the center of the drag shadow 19437 * directly under the touch point. If no View is provided (the constructor with no parameters 19438 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 19439 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 19440 * default is an invisible drag shadow. 19441 * <p> 19442 * You are not required to use the View you provide to the constructor as the basis of the 19443 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 19444 * anything you want as the drag shadow. 19445 * </p> 19446 * <p> 19447 * You pass a DragShadowBuilder object to the system when you start the drag. The system 19448 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 19449 * size and position of the drag shadow. It uses this data to construct a 19450 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 19451 * so that your application can draw the shadow image in the Canvas. 19452 * </p> 19453 * 19454 * <div class="special reference"> 19455 * <h3>Developer Guides</h3> 19456 * <p>For a guide to implementing drag and drop features, read the 19457 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19458 * </div> 19459 */ 19460 public static class DragShadowBuilder { 19461 private final WeakReference<View> mView; 19462 19463 /** 19464 * Constructs a shadow image builder based on a View. By default, the resulting drag 19465 * shadow will have the same appearance and dimensions as the View, with the touch point 19466 * over the center of the View. 19467 * @param view A View. Any View in scope can be used. 19468 */ 19469 public DragShadowBuilder(View view) { 19470 mView = new WeakReference<View>(view); 19471 } 19472 19473 /** 19474 * Construct a shadow builder object with no associated View. This 19475 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 19476 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 19477 * to supply the drag shadow's dimensions and appearance without 19478 * reference to any View object. If they are not overridden, then the result is an 19479 * invisible drag shadow. 19480 */ 19481 public DragShadowBuilder() { 19482 mView = new WeakReference<View>(null); 19483 } 19484 19485 /** 19486 * Returns the View object that had been passed to the 19487 * {@link #View.DragShadowBuilder(View)} 19488 * constructor. If that View parameter was {@code null} or if the 19489 * {@link #View.DragShadowBuilder()} 19490 * constructor was used to instantiate the builder object, this method will return 19491 * null. 19492 * 19493 * @return The View object associate with this builder object. 19494 */ 19495 @SuppressWarnings({"JavadocReference"}) 19496 final public View getView() { 19497 return mView.get(); 19498 } 19499 19500 /** 19501 * Provides the metrics for the shadow image. These include the dimensions of 19502 * the shadow image, and the point within that shadow that should 19503 * be centered under the touch location while dragging. 19504 * <p> 19505 * The default implementation sets the dimensions of the shadow to be the 19506 * same as the dimensions of the View itself and centers the shadow under 19507 * the touch point. 19508 * </p> 19509 * 19510 * @param shadowSize A {@link android.graphics.Point} containing the width and height 19511 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 19512 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 19513 * image. 19514 * 19515 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 19516 * shadow image that should be underneath the touch point during the drag and drop 19517 * operation. Your application must set {@link android.graphics.Point#x} to the 19518 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 19519 */ 19520 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 19521 final View view = mView.get(); 19522 if (view != null) { 19523 shadowSize.set(view.getWidth(), view.getHeight()); 19524 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 19525 } else { 19526 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 19527 } 19528 } 19529 19530 /** 19531 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 19532 * based on the dimensions it received from the 19533 * {@link #onProvideShadowMetrics(Point, Point)} callback. 19534 * 19535 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 19536 */ 19537 public void onDrawShadow(Canvas canvas) { 19538 final View view = mView.get(); 19539 if (view != null) { 19540 view.draw(canvas); 19541 } else { 19542 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 19543 } 19544 } 19545 } 19546 19547 /** 19548 * Starts a drag and drop operation. When your application calls this method, it passes a 19549 * {@link android.view.View.DragShadowBuilder} object to the system. The 19550 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 19551 * to get metrics for the drag shadow, and then calls the object's 19552 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 19553 * <p> 19554 * Once the system has the drag shadow, it begins the drag and drop operation by sending 19555 * drag events to all the View objects in your application that are currently visible. It does 19556 * this either by calling the View object's drag listener (an implementation of 19557 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 19558 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 19559 * Both are passed a {@link android.view.DragEvent} object that has a 19560 * {@link android.view.DragEvent#getAction()} value of 19561 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 19562 * </p> 19563 * <p> 19564 * Your application can invoke startDrag() on any attached View object. The View object does not 19565 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 19566 * be related to the View the user selected for dragging. 19567 * </p> 19568 * @param data A {@link android.content.ClipData} object pointing to the data to be 19569 * transferred by the drag and drop operation. 19570 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 19571 * drag shadow. 19572 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 19573 * drop operation. This Object is put into every DragEvent object sent by the system during the 19574 * current drag. 19575 * <p> 19576 * myLocalState is a lightweight mechanism for the sending information from the dragged View 19577 * to the target Views. For example, it can contain flags that differentiate between a 19578 * a copy operation and a move operation. 19579 * </p> 19580 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 19581 * so the parameter should be set to 0. 19582 * @return {@code true} if the method completes successfully, or 19583 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 19584 * do a drag, and so no drag operation is in progress. 19585 */ 19586 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 19587 Object myLocalState, int flags) { 19588 if (ViewDebug.DEBUG_DRAG) { 19589 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 19590 } 19591 boolean okay = false; 19592 19593 Point shadowSize = new Point(); 19594 Point shadowTouchPoint = new Point(); 19595 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 19596 19597 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 19598 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 19599 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 19600 } 19601 19602 if (ViewDebug.DEBUG_DRAG) { 19603 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 19604 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 19605 } 19606 Surface surface = new Surface(); 19607 try { 19608 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 19609 flags, shadowSize.x, shadowSize.y, surface); 19610 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 19611 + " surface=" + surface); 19612 if (token != null) { 19613 Canvas canvas = surface.lockCanvas(null); 19614 try { 19615 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 19616 shadowBuilder.onDrawShadow(canvas); 19617 } finally { 19618 surface.unlockCanvasAndPost(canvas); 19619 } 19620 19621 final ViewRootImpl root = getViewRootImpl(); 19622 19623 // Cache the local state object for delivery with DragEvents 19624 root.setLocalDragState(myLocalState); 19625 19626 // repurpose 'shadowSize' for the last touch point 19627 root.getLastTouchPoint(shadowSize); 19628 19629 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 19630 shadowSize.x, shadowSize.y, 19631 shadowTouchPoint.x, shadowTouchPoint.y, data); 19632 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 19633 19634 // Off and running! Release our local surface instance; the drag 19635 // shadow surface is now managed by the system process. 19636 surface.release(); 19637 } 19638 } catch (Exception e) { 19639 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 19640 surface.destroy(); 19641 } 19642 19643 return okay; 19644 } 19645 19646 /** 19647 * Handles drag events sent by the system following a call to 19648 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 19649 *<p> 19650 * When the system calls this method, it passes a 19651 * {@link android.view.DragEvent} object. A call to 19652 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 19653 * in DragEvent. The method uses these to determine what is happening in the drag and drop 19654 * operation. 19655 * @param event The {@link android.view.DragEvent} sent by the system. 19656 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 19657 * in DragEvent, indicating the type of drag event represented by this object. 19658 * @return {@code true} if the method was successful, otherwise {@code false}. 19659 * <p> 19660 * The method should return {@code true} in response to an action type of 19661 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 19662 * operation. 19663 * </p> 19664 * <p> 19665 * The method should also return {@code true} in response to an action type of 19666 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 19667 * {@code false} if it didn't. 19668 * </p> 19669 */ 19670 public boolean onDragEvent(DragEvent event) { 19671 return false; 19672 } 19673 19674 /** 19675 * Detects if this View is enabled and has a drag event listener. 19676 * If both are true, then it calls the drag event listener with the 19677 * {@link android.view.DragEvent} it received. If the drag event listener returns 19678 * {@code true}, then dispatchDragEvent() returns {@code true}. 19679 * <p> 19680 * For all other cases, the method calls the 19681 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 19682 * method and returns its result. 19683 * </p> 19684 * <p> 19685 * This ensures that a drag event is always consumed, even if the View does not have a drag 19686 * event listener. However, if the View has a listener and the listener returns true, then 19687 * onDragEvent() is not called. 19688 * </p> 19689 */ 19690 public boolean dispatchDragEvent(DragEvent event) { 19691 ListenerInfo li = mListenerInfo; 19692 //noinspection SimplifiableIfStatement 19693 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 19694 && li.mOnDragListener.onDrag(this, event)) { 19695 return true; 19696 } 19697 return onDragEvent(event); 19698 } 19699 19700 boolean canAcceptDrag() { 19701 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 19702 } 19703 19704 /** 19705 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 19706 * it is ever exposed at all. 19707 * @hide 19708 */ 19709 public void onCloseSystemDialogs(String reason) { 19710 } 19711 19712 /** 19713 * Given a Drawable whose bounds have been set to draw into this view, 19714 * update a Region being computed for 19715 * {@link #gatherTransparentRegion(android.graphics.Region)} so 19716 * that any non-transparent parts of the Drawable are removed from the 19717 * given transparent region. 19718 * 19719 * @param dr The Drawable whose transparency is to be applied to the region. 19720 * @param region A Region holding the current transparency information, 19721 * where any parts of the region that are set are considered to be 19722 * transparent. On return, this region will be modified to have the 19723 * transparency information reduced by the corresponding parts of the 19724 * Drawable that are not transparent. 19725 * {@hide} 19726 */ 19727 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 19728 if (DBG) { 19729 Log.i("View", "Getting transparent region for: " + this); 19730 } 19731 final Region r = dr.getTransparentRegion(); 19732 final Rect db = dr.getBounds(); 19733 final AttachInfo attachInfo = mAttachInfo; 19734 if (r != null && attachInfo != null) { 19735 final int w = getRight()-getLeft(); 19736 final int h = getBottom()-getTop(); 19737 if (db.left > 0) { 19738 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 19739 r.op(0, 0, db.left, h, Region.Op.UNION); 19740 } 19741 if (db.right < w) { 19742 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 19743 r.op(db.right, 0, w, h, Region.Op.UNION); 19744 } 19745 if (db.top > 0) { 19746 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 19747 r.op(0, 0, w, db.top, Region.Op.UNION); 19748 } 19749 if (db.bottom < h) { 19750 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 19751 r.op(0, db.bottom, w, h, Region.Op.UNION); 19752 } 19753 final int[] location = attachInfo.mTransparentLocation; 19754 getLocationInWindow(location); 19755 r.translate(location[0], location[1]); 19756 region.op(r, Region.Op.INTERSECT); 19757 } else { 19758 region.op(db, Region.Op.DIFFERENCE); 19759 } 19760 } 19761 19762 private void checkForLongClick(int delayOffset) { 19763 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 19764 mHasPerformedLongPress = false; 19765 19766 if (mPendingCheckForLongPress == null) { 19767 mPendingCheckForLongPress = new CheckForLongPress(); 19768 } 19769 mPendingCheckForLongPress.rememberWindowAttachCount(); 19770 postDelayed(mPendingCheckForLongPress, 19771 ViewConfiguration.getLongPressTimeout() - delayOffset); 19772 } 19773 } 19774 19775 /** 19776 * Inflate a view from an XML resource. This convenience method wraps the {@link 19777 * LayoutInflater} class, which provides a full range of options for view inflation. 19778 * 19779 * @param context The Context object for your activity or application. 19780 * @param resource The resource ID to inflate 19781 * @param root A view group that will be the parent. Used to properly inflate the 19782 * layout_* parameters. 19783 * @see LayoutInflater 19784 */ 19785 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 19786 LayoutInflater factory = LayoutInflater.from(context); 19787 return factory.inflate(resource, root); 19788 } 19789 19790 /** 19791 * Scroll the view with standard behavior for scrolling beyond the normal 19792 * content boundaries. Views that call this method should override 19793 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 19794 * results of an over-scroll operation. 19795 * 19796 * Views can use this method to handle any touch or fling-based scrolling. 19797 * 19798 * @param deltaX Change in X in pixels 19799 * @param deltaY Change in Y in pixels 19800 * @param scrollX Current X scroll value in pixels before applying deltaX 19801 * @param scrollY Current Y scroll value in pixels before applying deltaY 19802 * @param scrollRangeX Maximum content scroll range along the X axis 19803 * @param scrollRangeY Maximum content scroll range along the Y axis 19804 * @param maxOverScrollX Number of pixels to overscroll by in either direction 19805 * along the X axis. 19806 * @param maxOverScrollY Number of pixels to overscroll by in either direction 19807 * along the Y axis. 19808 * @param isTouchEvent true if this scroll operation is the result of a touch event. 19809 * @return true if scrolling was clamped to an over-scroll boundary along either 19810 * axis, false otherwise. 19811 */ 19812 @SuppressWarnings({"UnusedParameters"}) 19813 protected boolean overScrollBy(int deltaX, int deltaY, 19814 int scrollX, int scrollY, 19815 int scrollRangeX, int scrollRangeY, 19816 int maxOverScrollX, int maxOverScrollY, 19817 boolean isTouchEvent) { 19818 final int overScrollMode = mOverScrollMode; 19819 final boolean canScrollHorizontal = 19820 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 19821 final boolean canScrollVertical = 19822 computeVerticalScrollRange() > computeVerticalScrollExtent(); 19823 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 19824 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 19825 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 19826 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 19827 19828 int newScrollX = scrollX + deltaX; 19829 if (!overScrollHorizontal) { 19830 maxOverScrollX = 0; 19831 } 19832 19833 int newScrollY = scrollY + deltaY; 19834 if (!overScrollVertical) { 19835 maxOverScrollY = 0; 19836 } 19837 19838 // Clamp values if at the limits and record 19839 final int left = -maxOverScrollX; 19840 final int right = maxOverScrollX + scrollRangeX; 19841 final int top = -maxOverScrollY; 19842 final int bottom = maxOverScrollY + scrollRangeY; 19843 19844 boolean clampedX = false; 19845 if (newScrollX > right) { 19846 newScrollX = right; 19847 clampedX = true; 19848 } else if (newScrollX < left) { 19849 newScrollX = left; 19850 clampedX = true; 19851 } 19852 19853 boolean clampedY = false; 19854 if (newScrollY > bottom) { 19855 newScrollY = bottom; 19856 clampedY = true; 19857 } else if (newScrollY < top) { 19858 newScrollY = top; 19859 clampedY = true; 19860 } 19861 19862 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 19863 19864 return clampedX || clampedY; 19865 } 19866 19867 /** 19868 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 19869 * respond to the results of an over-scroll operation. 19870 * 19871 * @param scrollX New X scroll value in pixels 19872 * @param scrollY New Y scroll value in pixels 19873 * @param clampedX True if scrollX was clamped to an over-scroll boundary 19874 * @param clampedY True if scrollY was clamped to an over-scroll boundary 19875 */ 19876 protected void onOverScrolled(int scrollX, int scrollY, 19877 boolean clampedX, boolean clampedY) { 19878 // Intentionally empty. 19879 } 19880 19881 /** 19882 * Returns the over-scroll mode for this view. The result will be 19883 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 19884 * (allow over-scrolling only if the view content is larger than the container), 19885 * or {@link #OVER_SCROLL_NEVER}. 19886 * 19887 * @return This view's over-scroll mode. 19888 */ 19889 public int getOverScrollMode() { 19890 return mOverScrollMode; 19891 } 19892 19893 /** 19894 * Set the over-scroll mode for this view. Valid over-scroll modes are 19895 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 19896 * (allow over-scrolling only if the view content is larger than the container), 19897 * or {@link #OVER_SCROLL_NEVER}. 19898 * 19899 * Setting the over-scroll mode of a view will have an effect only if the 19900 * view is capable of scrolling. 19901 * 19902 * @param overScrollMode The new over-scroll mode for this view. 19903 */ 19904 public void setOverScrollMode(int overScrollMode) { 19905 if (overScrollMode != OVER_SCROLL_ALWAYS && 19906 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 19907 overScrollMode != OVER_SCROLL_NEVER) { 19908 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 19909 } 19910 mOverScrollMode = overScrollMode; 19911 } 19912 19913 /** 19914 * Enable or disable nested scrolling for this view. 19915 * 19916 * <p>If this property is set to true the view will be permitted to initiate nested 19917 * scrolling operations with a compatible parent view in the current hierarchy. If this 19918 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 19919 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 19920 * the nested scroll.</p> 19921 * 19922 * @param enabled true to enable nested scrolling, false to disable 19923 * 19924 * @see #isNestedScrollingEnabled() 19925 */ 19926 public void setNestedScrollingEnabled(boolean enabled) { 19927 if (enabled) { 19928 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 19929 } else { 19930 stopNestedScroll(); 19931 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 19932 } 19933 } 19934 19935 /** 19936 * Returns true if nested scrolling is enabled for this view. 19937 * 19938 * <p>If nested scrolling is enabled and this View class implementation supports it, 19939 * this view will act as a nested scrolling child view when applicable, forwarding data 19940 * about the scroll operation in progress to a compatible and cooperating nested scrolling 19941 * parent.</p> 19942 * 19943 * @return true if nested scrolling is enabled 19944 * 19945 * @see #setNestedScrollingEnabled(boolean) 19946 */ 19947 public boolean isNestedScrollingEnabled() { 19948 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 19949 PFLAG3_NESTED_SCROLLING_ENABLED; 19950 } 19951 19952 /** 19953 * Begin a nestable scroll operation along the given axes. 19954 * 19955 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 19956 * 19957 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 19958 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 19959 * In the case of touch scrolling the nested scroll will be terminated automatically in 19960 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 19961 * In the event of programmatic scrolling the caller must explicitly call 19962 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 19963 * 19964 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 19965 * If it returns false the caller may ignore the rest of this contract until the next scroll. 19966 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 19967 * 19968 * <p>At each incremental step of the scroll the caller should invoke 19969 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 19970 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 19971 * parent at least partially consumed the scroll and the caller should adjust the amount it 19972 * scrolls by.</p> 19973 * 19974 * <p>After applying the remainder of the scroll delta the caller should invoke 19975 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 19976 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 19977 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 19978 * </p> 19979 * 19980 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 19981 * {@link #SCROLL_AXIS_VERTICAL}. 19982 * @return true if a cooperative parent was found and nested scrolling has been enabled for 19983 * the current gesture. 19984 * 19985 * @see #stopNestedScroll() 19986 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 19987 * @see #dispatchNestedScroll(int, int, int, int, int[]) 19988 */ 19989 public boolean startNestedScroll(int axes) { 19990 if (hasNestedScrollingParent()) { 19991 // Already in progress 19992 return true; 19993 } 19994 if (isNestedScrollingEnabled()) { 19995 ViewParent p = getParent(); 19996 View child = this; 19997 while (p != null) { 19998 try { 19999 if (p.onStartNestedScroll(child, this, axes)) { 20000 mNestedScrollingParent = p; 20001 p.onNestedScrollAccepted(child, this, axes); 20002 return true; 20003 } 20004 } catch (AbstractMethodError e) { 20005 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 20006 "method onStartNestedScroll", e); 20007 // Allow the search upward to continue 20008 } 20009 if (p instanceof View) { 20010 child = (View) p; 20011 } 20012 p = p.getParent(); 20013 } 20014 } 20015 return false; 20016 } 20017 20018 /** 20019 * Stop a nested scroll in progress. 20020 * 20021 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 20022 * 20023 * @see #startNestedScroll(int) 20024 */ 20025 public void stopNestedScroll() { 20026 if (mNestedScrollingParent != null) { 20027 mNestedScrollingParent.onStopNestedScroll(this); 20028 mNestedScrollingParent = null; 20029 } 20030 } 20031 20032 /** 20033 * Returns true if this view has a nested scrolling parent. 20034 * 20035 * <p>The presence of a nested scrolling parent indicates that this view has initiated 20036 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 20037 * 20038 * @return whether this view has a nested scrolling parent 20039 */ 20040 public boolean hasNestedScrollingParent() { 20041 return mNestedScrollingParent != null; 20042 } 20043 20044 /** 20045 * Dispatch one step of a nested scroll in progress. 20046 * 20047 * <p>Implementations of views that support nested scrolling should call this to report 20048 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 20049 * is not currently in progress or nested scrolling is not 20050 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 20051 * 20052 * <p>Compatible View implementations should also call 20053 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 20054 * consuming a component of the scroll event themselves.</p> 20055 * 20056 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 20057 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 20058 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 20059 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 20060 * @param offsetInWindow Optional. If not null, on return this will contain the offset 20061 * in local view coordinates of this view from before this operation 20062 * to after it completes. View implementations may use this to adjust 20063 * expected input coordinate tracking. 20064 * @return true if the event was dispatched, false if it could not be dispatched. 20065 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 20066 */ 20067 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 20068 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 20069 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20070 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 20071 int startX = 0; 20072 int startY = 0; 20073 if (offsetInWindow != null) { 20074 getLocationInWindow(offsetInWindow); 20075 startX = offsetInWindow[0]; 20076 startY = offsetInWindow[1]; 20077 } 20078 20079 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 20080 dxUnconsumed, dyUnconsumed); 20081 20082 if (offsetInWindow != null) { 20083 getLocationInWindow(offsetInWindow); 20084 offsetInWindow[0] -= startX; 20085 offsetInWindow[1] -= startY; 20086 } 20087 return true; 20088 } else if (offsetInWindow != null) { 20089 // No motion, no dispatch. Keep offsetInWindow up to date. 20090 offsetInWindow[0] = 0; 20091 offsetInWindow[1] = 0; 20092 } 20093 } 20094 return false; 20095 } 20096 20097 /** 20098 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 20099 * 20100 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 20101 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 20102 * scrolling operation to consume some or all of the scroll operation before the child view 20103 * consumes it.</p> 20104 * 20105 * @param dx Horizontal scroll distance in pixels 20106 * @param dy Vertical scroll distance in pixels 20107 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 20108 * and consumed[1] the consumed dy. 20109 * @param offsetInWindow Optional. If not null, on return this will contain the offset 20110 * in local view coordinates of this view from before this operation 20111 * to after it completes. View implementations may use this to adjust 20112 * expected input coordinate tracking. 20113 * @return true if the parent consumed some or all of the scroll delta 20114 * @see #dispatchNestedScroll(int, int, int, int, int[]) 20115 */ 20116 public boolean dispatchNestedPreScroll(int dx, int dy, 20117 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 20118 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20119 if (dx != 0 || dy != 0) { 20120 int startX = 0; 20121 int startY = 0; 20122 if (offsetInWindow != null) { 20123 getLocationInWindow(offsetInWindow); 20124 startX = offsetInWindow[0]; 20125 startY = offsetInWindow[1]; 20126 } 20127 20128 if (consumed == null) { 20129 if (mTempNestedScrollConsumed == null) { 20130 mTempNestedScrollConsumed = new int[2]; 20131 } 20132 consumed = mTempNestedScrollConsumed; 20133 } 20134 consumed[0] = 0; 20135 consumed[1] = 0; 20136 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 20137 20138 if (offsetInWindow != null) { 20139 getLocationInWindow(offsetInWindow); 20140 offsetInWindow[0] -= startX; 20141 offsetInWindow[1] -= startY; 20142 } 20143 return consumed[0] != 0 || consumed[1] != 0; 20144 } else if (offsetInWindow != null) { 20145 offsetInWindow[0] = 0; 20146 offsetInWindow[1] = 0; 20147 } 20148 } 20149 return false; 20150 } 20151 20152 /** 20153 * Dispatch a fling to a nested scrolling parent. 20154 * 20155 * <p>This method should be used to indicate that a nested scrolling child has detected 20156 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 20157 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 20158 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 20159 * along a scrollable axis.</p> 20160 * 20161 * <p>If a nested scrolling child view would normally fling but it is at the edge of 20162 * its own content, it can use this method to delegate the fling to its nested scrolling 20163 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 20164 * 20165 * @param velocityX Horizontal fling velocity in pixels per second 20166 * @param velocityY Vertical fling velocity in pixels per second 20167 * @param consumed true if the child consumed the fling, false otherwise 20168 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 20169 */ 20170 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 20171 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20172 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 20173 } 20174 return false; 20175 } 20176 20177 /** 20178 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 20179 * 20180 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 20181 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 20182 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 20183 * before the child view consumes it. If this method returns <code>true</code>, a nested 20184 * parent view consumed the fling and this view should not scroll as a result.</p> 20185 * 20186 * <p>For a better user experience, only one view in a nested scrolling chain should consume 20187 * the fling at a time. If a parent view consumed the fling this method will return false. 20188 * Custom view implementations should account for this in two ways:</p> 20189 * 20190 * <ul> 20191 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 20192 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 20193 * position regardless.</li> 20194 * <li>If a nested parent does consume the fling, this view should not scroll at all, 20195 * even to settle back to a valid idle position.</li> 20196 * </ul> 20197 * 20198 * <p>Views should also not offer fling velocities to nested parent views along an axis 20199 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 20200 * should not offer a horizontal fling velocity to its parents since scrolling along that 20201 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 20202 * 20203 * @param velocityX Horizontal fling velocity in pixels per second 20204 * @param velocityY Vertical fling velocity in pixels per second 20205 * @return true if a nested scrolling parent consumed the fling 20206 */ 20207 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 20208 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20209 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 20210 } 20211 return false; 20212 } 20213 20214 /** 20215 * Gets a scale factor that determines the distance the view should scroll 20216 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 20217 * @return The vertical scroll scale factor. 20218 * @hide 20219 */ 20220 protected float getVerticalScrollFactor() { 20221 if (mVerticalScrollFactor == 0) { 20222 TypedValue outValue = new TypedValue(); 20223 if (!mContext.getTheme().resolveAttribute( 20224 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 20225 throw new IllegalStateException( 20226 "Expected theme to define listPreferredItemHeight."); 20227 } 20228 mVerticalScrollFactor = outValue.getDimension( 20229 mContext.getResources().getDisplayMetrics()); 20230 } 20231 return mVerticalScrollFactor; 20232 } 20233 20234 /** 20235 * Gets a scale factor that determines the distance the view should scroll 20236 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 20237 * @return The horizontal scroll scale factor. 20238 * @hide 20239 */ 20240 protected float getHorizontalScrollFactor() { 20241 // TODO: Should use something else. 20242 return getVerticalScrollFactor(); 20243 } 20244 20245 /** 20246 * Return the value specifying the text direction or policy that was set with 20247 * {@link #setTextDirection(int)}. 20248 * 20249 * @return the defined text direction. It can be one of: 20250 * 20251 * {@link #TEXT_DIRECTION_INHERIT}, 20252 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 20253 * {@link #TEXT_DIRECTION_ANY_RTL}, 20254 * {@link #TEXT_DIRECTION_LTR}, 20255 * {@link #TEXT_DIRECTION_RTL}, 20256 * {@link #TEXT_DIRECTION_LOCALE}, 20257 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 20258 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 20259 * 20260 * @attr ref android.R.styleable#View_textDirection 20261 * 20262 * @hide 20263 */ 20264 @ViewDebug.ExportedProperty(category = "text", mapping = { 20265 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 20266 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 20267 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 20268 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 20269 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 20270 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 20271 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 20272 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 20273 }) 20274 public int getRawTextDirection() { 20275 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 20276 } 20277 20278 /** 20279 * Set the text direction. 20280 * 20281 * @param textDirection the direction to set. Should be one of: 20282 * 20283 * {@link #TEXT_DIRECTION_INHERIT}, 20284 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 20285 * {@link #TEXT_DIRECTION_ANY_RTL}, 20286 * {@link #TEXT_DIRECTION_LTR}, 20287 * {@link #TEXT_DIRECTION_RTL}, 20288 * {@link #TEXT_DIRECTION_LOCALE} 20289 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 20290 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 20291 * 20292 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 20293 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 20294 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 20295 * 20296 * @attr ref android.R.styleable#View_textDirection 20297 */ 20298 public void setTextDirection(int textDirection) { 20299 if (getRawTextDirection() != textDirection) { 20300 // Reset the current text direction and the resolved one 20301 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 20302 resetResolvedTextDirection(); 20303 // Set the new text direction 20304 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 20305 // Do resolution 20306 resolveTextDirection(); 20307 // Notify change 20308 onRtlPropertiesChanged(getLayoutDirection()); 20309 // Refresh 20310 requestLayout(); 20311 invalidate(true); 20312 } 20313 } 20314 20315 /** 20316 * Return the resolved text direction. 20317 * 20318 * @return the resolved text direction. Returns one of: 20319 * 20320 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 20321 * {@link #TEXT_DIRECTION_ANY_RTL}, 20322 * {@link #TEXT_DIRECTION_LTR}, 20323 * {@link #TEXT_DIRECTION_RTL}, 20324 * {@link #TEXT_DIRECTION_LOCALE}, 20325 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 20326 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 20327 * 20328 * @attr ref android.R.styleable#View_textDirection 20329 */ 20330 @ViewDebug.ExportedProperty(category = "text", mapping = { 20331 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 20332 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 20333 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 20334 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 20335 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 20336 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 20337 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 20338 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 20339 }) 20340 public int getTextDirection() { 20341 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 20342 } 20343 20344 /** 20345 * Resolve the text direction. 20346 * 20347 * @return true if resolution has been done, false otherwise. 20348 * 20349 * @hide 20350 */ 20351 public boolean resolveTextDirection() { 20352 // Reset any previous text direction resolution 20353 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 20354 20355 if (hasRtlSupport()) { 20356 // Set resolved text direction flag depending on text direction flag 20357 final int textDirection = getRawTextDirection(); 20358 switch(textDirection) { 20359 case TEXT_DIRECTION_INHERIT: 20360 if (!canResolveTextDirection()) { 20361 // We cannot do the resolution if there is no parent, so use the default one 20362 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20363 // Resolution will need to happen again later 20364 return false; 20365 } 20366 20367 // Parent has not yet resolved, so we still return the default 20368 try { 20369 if (!mParent.isTextDirectionResolved()) { 20370 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20371 // Resolution will need to happen again later 20372 return false; 20373 } 20374 } catch (AbstractMethodError e) { 20375 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20376 " does not fully implement ViewParent", e); 20377 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 20378 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20379 return true; 20380 } 20381 20382 // Set current resolved direction to the same value as the parent's one 20383 int parentResolvedDirection; 20384 try { 20385 parentResolvedDirection = mParent.getTextDirection(); 20386 } catch (AbstractMethodError e) { 20387 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20388 " does not fully implement ViewParent", e); 20389 parentResolvedDirection = TEXT_DIRECTION_LTR; 20390 } 20391 switch (parentResolvedDirection) { 20392 case TEXT_DIRECTION_FIRST_STRONG: 20393 case TEXT_DIRECTION_ANY_RTL: 20394 case TEXT_DIRECTION_LTR: 20395 case TEXT_DIRECTION_RTL: 20396 case TEXT_DIRECTION_LOCALE: 20397 case TEXT_DIRECTION_FIRST_STRONG_LTR: 20398 case TEXT_DIRECTION_FIRST_STRONG_RTL: 20399 mPrivateFlags2 |= 20400 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 20401 break; 20402 default: 20403 // Default resolved direction is "first strong" heuristic 20404 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20405 } 20406 break; 20407 case TEXT_DIRECTION_FIRST_STRONG: 20408 case TEXT_DIRECTION_ANY_RTL: 20409 case TEXT_DIRECTION_LTR: 20410 case TEXT_DIRECTION_RTL: 20411 case TEXT_DIRECTION_LOCALE: 20412 case TEXT_DIRECTION_FIRST_STRONG_LTR: 20413 case TEXT_DIRECTION_FIRST_STRONG_RTL: 20414 // Resolved direction is the same as text direction 20415 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 20416 break; 20417 default: 20418 // Default resolved direction is "first strong" heuristic 20419 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20420 } 20421 } else { 20422 // Default resolved direction is "first strong" heuristic 20423 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20424 } 20425 20426 // Set to resolved 20427 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 20428 return true; 20429 } 20430 20431 /** 20432 * Check if text direction resolution can be done. 20433 * 20434 * @return true if text direction resolution can be done otherwise return false. 20435 */ 20436 public boolean canResolveTextDirection() { 20437 switch (getRawTextDirection()) { 20438 case TEXT_DIRECTION_INHERIT: 20439 if (mParent != null) { 20440 try { 20441 return mParent.canResolveTextDirection(); 20442 } catch (AbstractMethodError e) { 20443 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20444 " does not fully implement ViewParent", e); 20445 } 20446 } 20447 return false; 20448 20449 default: 20450 return true; 20451 } 20452 } 20453 20454 /** 20455 * Reset resolved text direction. Text direction will be resolved during a call to 20456 * {@link #onMeasure(int, int)}. 20457 * 20458 * @hide 20459 */ 20460 public void resetResolvedTextDirection() { 20461 // Reset any previous text direction resolution 20462 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 20463 // Set to default value 20464 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 20465 } 20466 20467 /** 20468 * @return true if text direction is inherited. 20469 * 20470 * @hide 20471 */ 20472 public boolean isTextDirectionInherited() { 20473 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 20474 } 20475 20476 /** 20477 * @return true if text direction is resolved. 20478 */ 20479 public boolean isTextDirectionResolved() { 20480 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 20481 } 20482 20483 /** 20484 * Return the value specifying the text alignment or policy that was set with 20485 * {@link #setTextAlignment(int)}. 20486 * 20487 * @return the defined text alignment. It can be one of: 20488 * 20489 * {@link #TEXT_ALIGNMENT_INHERIT}, 20490 * {@link #TEXT_ALIGNMENT_GRAVITY}, 20491 * {@link #TEXT_ALIGNMENT_CENTER}, 20492 * {@link #TEXT_ALIGNMENT_TEXT_START}, 20493 * {@link #TEXT_ALIGNMENT_TEXT_END}, 20494 * {@link #TEXT_ALIGNMENT_VIEW_START}, 20495 * {@link #TEXT_ALIGNMENT_VIEW_END} 20496 * 20497 * @attr ref android.R.styleable#View_textAlignment 20498 * 20499 * @hide 20500 */ 20501 @ViewDebug.ExportedProperty(category = "text", mapping = { 20502 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 20503 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 20504 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 20505 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 20506 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 20507 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 20508 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 20509 }) 20510 @TextAlignment 20511 public int getRawTextAlignment() { 20512 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 20513 } 20514 20515 /** 20516 * Set the text alignment. 20517 * 20518 * @param textAlignment The text alignment to set. Should be one of 20519 * 20520 * {@link #TEXT_ALIGNMENT_INHERIT}, 20521 * {@link #TEXT_ALIGNMENT_GRAVITY}, 20522 * {@link #TEXT_ALIGNMENT_CENTER}, 20523 * {@link #TEXT_ALIGNMENT_TEXT_START}, 20524 * {@link #TEXT_ALIGNMENT_TEXT_END}, 20525 * {@link #TEXT_ALIGNMENT_VIEW_START}, 20526 * {@link #TEXT_ALIGNMENT_VIEW_END} 20527 * 20528 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 20529 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 20530 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 20531 * 20532 * @attr ref android.R.styleable#View_textAlignment 20533 */ 20534 public void setTextAlignment(@TextAlignment int textAlignment) { 20535 if (textAlignment != getRawTextAlignment()) { 20536 // Reset the current and resolved text alignment 20537 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 20538 resetResolvedTextAlignment(); 20539 // Set the new text alignment 20540 mPrivateFlags2 |= 20541 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 20542 // Do resolution 20543 resolveTextAlignment(); 20544 // Notify change 20545 onRtlPropertiesChanged(getLayoutDirection()); 20546 // Refresh 20547 requestLayout(); 20548 invalidate(true); 20549 } 20550 } 20551 20552 /** 20553 * Return the resolved text alignment. 20554 * 20555 * @return the resolved text alignment. Returns one of: 20556 * 20557 * {@link #TEXT_ALIGNMENT_GRAVITY}, 20558 * {@link #TEXT_ALIGNMENT_CENTER}, 20559 * {@link #TEXT_ALIGNMENT_TEXT_START}, 20560 * {@link #TEXT_ALIGNMENT_TEXT_END}, 20561 * {@link #TEXT_ALIGNMENT_VIEW_START}, 20562 * {@link #TEXT_ALIGNMENT_VIEW_END} 20563 * 20564 * @attr ref android.R.styleable#View_textAlignment 20565 */ 20566 @ViewDebug.ExportedProperty(category = "text", mapping = { 20567 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 20568 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 20569 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 20570 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 20571 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 20572 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 20573 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 20574 }) 20575 @TextAlignment 20576 public int getTextAlignment() { 20577 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 20578 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 20579 } 20580 20581 /** 20582 * Resolve the text alignment. 20583 * 20584 * @return true if resolution has been done, false otherwise. 20585 * 20586 * @hide 20587 */ 20588 public boolean resolveTextAlignment() { 20589 // Reset any previous text alignment resolution 20590 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 20591 20592 if (hasRtlSupport()) { 20593 // Set resolved text alignment flag depending on text alignment flag 20594 final int textAlignment = getRawTextAlignment(); 20595 switch (textAlignment) { 20596 case TEXT_ALIGNMENT_INHERIT: 20597 // Check if we can resolve the text alignment 20598 if (!canResolveTextAlignment()) { 20599 // We cannot do the resolution if there is no parent so use the default 20600 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20601 // Resolution will need to happen again later 20602 return false; 20603 } 20604 20605 // Parent has not yet resolved, so we still return the default 20606 try { 20607 if (!mParent.isTextAlignmentResolved()) { 20608 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20609 // Resolution will need to happen again later 20610 return false; 20611 } 20612 } catch (AbstractMethodError e) { 20613 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20614 " does not fully implement ViewParent", e); 20615 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 20616 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20617 return true; 20618 } 20619 20620 int parentResolvedTextAlignment; 20621 try { 20622 parentResolvedTextAlignment = mParent.getTextAlignment(); 20623 } catch (AbstractMethodError e) { 20624 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20625 " does not fully implement ViewParent", e); 20626 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 20627 } 20628 switch (parentResolvedTextAlignment) { 20629 case TEXT_ALIGNMENT_GRAVITY: 20630 case TEXT_ALIGNMENT_TEXT_START: 20631 case TEXT_ALIGNMENT_TEXT_END: 20632 case TEXT_ALIGNMENT_CENTER: 20633 case TEXT_ALIGNMENT_VIEW_START: 20634 case TEXT_ALIGNMENT_VIEW_END: 20635 // Resolved text alignment is the same as the parent resolved 20636 // text alignment 20637 mPrivateFlags2 |= 20638 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 20639 break; 20640 default: 20641 // Use default resolved text alignment 20642 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20643 } 20644 break; 20645 case TEXT_ALIGNMENT_GRAVITY: 20646 case TEXT_ALIGNMENT_TEXT_START: 20647 case TEXT_ALIGNMENT_TEXT_END: 20648 case TEXT_ALIGNMENT_CENTER: 20649 case TEXT_ALIGNMENT_VIEW_START: 20650 case TEXT_ALIGNMENT_VIEW_END: 20651 // Resolved text alignment is the same as text alignment 20652 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 20653 break; 20654 default: 20655 // Use default resolved text alignment 20656 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20657 } 20658 } else { 20659 // Use default resolved text alignment 20660 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20661 } 20662 20663 // Set the resolved 20664 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 20665 return true; 20666 } 20667 20668 /** 20669 * Check if text alignment resolution can be done. 20670 * 20671 * @return true if text alignment resolution can be done otherwise return false. 20672 */ 20673 public boolean canResolveTextAlignment() { 20674 switch (getRawTextAlignment()) { 20675 case TEXT_DIRECTION_INHERIT: 20676 if (mParent != null) { 20677 try { 20678 return mParent.canResolveTextAlignment(); 20679 } catch (AbstractMethodError e) { 20680 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 20681 " does not fully implement ViewParent", e); 20682 } 20683 } 20684 return false; 20685 20686 default: 20687 return true; 20688 } 20689 } 20690 20691 /** 20692 * Reset resolved text alignment. Text alignment will be resolved during a call to 20693 * {@link #onMeasure(int, int)}. 20694 * 20695 * @hide 20696 */ 20697 public void resetResolvedTextAlignment() { 20698 // Reset any previous text alignment resolution 20699 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 20700 // Set to default 20701 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 20702 } 20703 20704 /** 20705 * @return true if text alignment is inherited. 20706 * 20707 * @hide 20708 */ 20709 public boolean isTextAlignmentInherited() { 20710 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 20711 } 20712 20713 /** 20714 * @return true if text alignment is resolved. 20715 */ 20716 public boolean isTextAlignmentResolved() { 20717 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 20718 } 20719 20720 /** 20721 * Generate a value suitable for use in {@link #setId(int)}. 20722 * This value will not collide with ID values generated at build time by aapt for R.id. 20723 * 20724 * @return a generated ID value 20725 */ 20726 public static int generateViewId() { 20727 for (;;) { 20728 final int result = sNextGeneratedId.get(); 20729 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 20730 int newValue = result + 1; 20731 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 20732 if (sNextGeneratedId.compareAndSet(result, newValue)) { 20733 return result; 20734 } 20735 } 20736 } 20737 20738 /** 20739 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 20740 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 20741 * a normal View or a ViewGroup with 20742 * {@link android.view.ViewGroup#isTransitionGroup()} true. 20743 * @hide 20744 */ 20745 public void captureTransitioningViews(List<View> transitioningViews) { 20746 if (getVisibility() == View.VISIBLE) { 20747 transitioningViews.add(this); 20748 } 20749 } 20750 20751 /** 20752 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 20753 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 20754 * @hide 20755 */ 20756 public void findNamedViews(Map<String, View> namedElements) { 20757 if (getVisibility() == VISIBLE || mGhostView != null) { 20758 String transitionName = getTransitionName(); 20759 if (transitionName != null) { 20760 namedElements.put(transitionName, this); 20761 } 20762 } 20763 } 20764 20765 // 20766 // Properties 20767 // 20768 /** 20769 * A Property wrapper around the <code>alpha</code> functionality handled by the 20770 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 20771 */ 20772 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 20773 @Override 20774 public void setValue(View object, float value) { 20775 object.setAlpha(value); 20776 } 20777 20778 @Override 20779 public Float get(View object) { 20780 return object.getAlpha(); 20781 } 20782 }; 20783 20784 /** 20785 * A Property wrapper around the <code>translationX</code> functionality handled by the 20786 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 20787 */ 20788 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 20789 @Override 20790 public void setValue(View object, float value) { 20791 object.setTranslationX(value); 20792 } 20793 20794 @Override 20795 public Float get(View object) { 20796 return object.getTranslationX(); 20797 } 20798 }; 20799 20800 /** 20801 * A Property wrapper around the <code>translationY</code> functionality handled by the 20802 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 20803 */ 20804 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 20805 @Override 20806 public void setValue(View object, float value) { 20807 object.setTranslationY(value); 20808 } 20809 20810 @Override 20811 public Float get(View object) { 20812 return object.getTranslationY(); 20813 } 20814 }; 20815 20816 /** 20817 * A Property wrapper around the <code>translationZ</code> functionality handled by the 20818 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 20819 */ 20820 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 20821 @Override 20822 public void setValue(View object, float value) { 20823 object.setTranslationZ(value); 20824 } 20825 20826 @Override 20827 public Float get(View object) { 20828 return object.getTranslationZ(); 20829 } 20830 }; 20831 20832 /** 20833 * A Property wrapper around the <code>x</code> functionality handled by the 20834 * {@link View#setX(float)} and {@link View#getX()} methods. 20835 */ 20836 public static final Property<View, Float> X = new FloatProperty<View>("x") { 20837 @Override 20838 public void setValue(View object, float value) { 20839 object.setX(value); 20840 } 20841 20842 @Override 20843 public Float get(View object) { 20844 return object.getX(); 20845 } 20846 }; 20847 20848 /** 20849 * A Property wrapper around the <code>y</code> functionality handled by the 20850 * {@link View#setY(float)} and {@link View#getY()} methods. 20851 */ 20852 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 20853 @Override 20854 public void setValue(View object, float value) { 20855 object.setY(value); 20856 } 20857 20858 @Override 20859 public Float get(View object) { 20860 return object.getY(); 20861 } 20862 }; 20863 20864 /** 20865 * A Property wrapper around the <code>z</code> functionality handled by the 20866 * {@link View#setZ(float)} and {@link View#getZ()} methods. 20867 */ 20868 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 20869 @Override 20870 public void setValue(View object, float value) { 20871 object.setZ(value); 20872 } 20873 20874 @Override 20875 public Float get(View object) { 20876 return object.getZ(); 20877 } 20878 }; 20879 20880 /** 20881 * A Property wrapper around the <code>rotation</code> functionality handled by the 20882 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 20883 */ 20884 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 20885 @Override 20886 public void setValue(View object, float value) { 20887 object.setRotation(value); 20888 } 20889 20890 @Override 20891 public Float get(View object) { 20892 return object.getRotation(); 20893 } 20894 }; 20895 20896 /** 20897 * A Property wrapper around the <code>rotationX</code> functionality handled by the 20898 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 20899 */ 20900 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 20901 @Override 20902 public void setValue(View object, float value) { 20903 object.setRotationX(value); 20904 } 20905 20906 @Override 20907 public Float get(View object) { 20908 return object.getRotationX(); 20909 } 20910 }; 20911 20912 /** 20913 * A Property wrapper around the <code>rotationY</code> functionality handled by the 20914 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 20915 */ 20916 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 20917 @Override 20918 public void setValue(View object, float value) { 20919 object.setRotationY(value); 20920 } 20921 20922 @Override 20923 public Float get(View object) { 20924 return object.getRotationY(); 20925 } 20926 }; 20927 20928 /** 20929 * A Property wrapper around the <code>scaleX</code> functionality handled by the 20930 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 20931 */ 20932 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 20933 @Override 20934 public void setValue(View object, float value) { 20935 object.setScaleX(value); 20936 } 20937 20938 @Override 20939 public Float get(View object) { 20940 return object.getScaleX(); 20941 } 20942 }; 20943 20944 /** 20945 * A Property wrapper around the <code>scaleY</code> functionality handled by the 20946 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 20947 */ 20948 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 20949 @Override 20950 public void setValue(View object, float value) { 20951 object.setScaleY(value); 20952 } 20953 20954 @Override 20955 public Float get(View object) { 20956 return object.getScaleY(); 20957 } 20958 }; 20959 20960 /** 20961 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 20962 * Each MeasureSpec represents a requirement for either the width or the height. 20963 * A MeasureSpec is comprised of a size and a mode. There are three possible 20964 * modes: 20965 * <dl> 20966 * <dt>UNSPECIFIED</dt> 20967 * <dd> 20968 * The parent has not imposed any constraint on the child. It can be whatever size 20969 * it wants. 20970 * </dd> 20971 * 20972 * <dt>EXACTLY</dt> 20973 * <dd> 20974 * The parent has determined an exact size for the child. The child is going to be 20975 * given those bounds regardless of how big it wants to be. 20976 * </dd> 20977 * 20978 * <dt>AT_MOST</dt> 20979 * <dd> 20980 * The child can be as large as it wants up to the specified size. 20981 * </dd> 20982 * </dl> 20983 * 20984 * MeasureSpecs are implemented as ints to reduce object allocation. This class 20985 * is provided to pack and unpack the <size, mode> tuple into the int. 20986 */ 20987 public static class MeasureSpec { 20988 private static final int MODE_SHIFT = 30; 20989 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 20990 20991 /** 20992 * Measure specification mode: The parent has not imposed any constraint 20993 * on the child. It can be whatever size it wants. 20994 */ 20995 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 20996 20997 /** 20998 * Measure specification mode: The parent has determined an exact size 20999 * for the child. The child is going to be given those bounds regardless 21000 * of how big it wants to be. 21001 */ 21002 public static final int EXACTLY = 1 << MODE_SHIFT; 21003 21004 /** 21005 * Measure specification mode: The child can be as large as it wants up 21006 * to the specified size. 21007 */ 21008 public static final int AT_MOST = 2 << MODE_SHIFT; 21009 21010 /** 21011 * Creates a measure specification based on the supplied size and mode. 21012 * 21013 * The mode must always be one of the following: 21014 * <ul> 21015 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 21016 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 21017 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 21018 * </ul> 21019 * 21020 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 21021 * implementation was such that the order of arguments did not matter 21022 * and overflow in either value could impact the resulting MeasureSpec. 21023 * {@link android.widget.RelativeLayout} was affected by this bug. 21024 * Apps targeting API levels greater than 17 will get the fixed, more strict 21025 * behavior.</p> 21026 * 21027 * @param size the size of the measure specification 21028 * @param mode the mode of the measure specification 21029 * @return the measure specification based on size and mode 21030 */ 21031 public static int makeMeasureSpec(int size, int mode) { 21032 if (sUseBrokenMakeMeasureSpec) { 21033 return size + mode; 21034 } else { 21035 return (size & ~MODE_MASK) | (mode & MODE_MASK); 21036 } 21037 } 21038 21039 /** 21040 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 21041 * will automatically get a size of 0. Older apps expect this. 21042 * 21043 * @hide internal use only for compatibility with system widgets and older apps 21044 */ 21045 public static int makeSafeMeasureSpec(int size, int mode) { 21046 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 21047 return 0; 21048 } 21049 return makeMeasureSpec(size, mode); 21050 } 21051 21052 /** 21053 * Extracts the mode from the supplied measure specification. 21054 * 21055 * @param measureSpec the measure specification to extract the mode from 21056 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 21057 * {@link android.view.View.MeasureSpec#AT_MOST} or 21058 * {@link android.view.View.MeasureSpec#EXACTLY} 21059 */ 21060 public static int getMode(int measureSpec) { 21061 return (measureSpec & MODE_MASK); 21062 } 21063 21064 /** 21065 * Extracts the size from the supplied measure specification. 21066 * 21067 * @param measureSpec the measure specification to extract the size from 21068 * @return the size in pixels defined in the supplied measure specification 21069 */ 21070 public static int getSize(int measureSpec) { 21071 return (measureSpec & ~MODE_MASK); 21072 } 21073 21074 static int adjust(int measureSpec, int delta) { 21075 final int mode = getMode(measureSpec); 21076 int size = getSize(measureSpec); 21077 if (mode == UNSPECIFIED) { 21078 // No need to adjust size for UNSPECIFIED mode. 21079 return makeMeasureSpec(size, UNSPECIFIED); 21080 } 21081 size += delta; 21082 if (size < 0) { 21083 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 21084 ") spec: " + toString(measureSpec) + " delta: " + delta); 21085 size = 0; 21086 } 21087 return makeMeasureSpec(size, mode); 21088 } 21089 21090 /** 21091 * Returns a String representation of the specified measure 21092 * specification. 21093 * 21094 * @param measureSpec the measure specification to convert to a String 21095 * @return a String with the following format: "MeasureSpec: MODE SIZE" 21096 */ 21097 public static String toString(int measureSpec) { 21098 int mode = getMode(measureSpec); 21099 int size = getSize(measureSpec); 21100 21101 StringBuilder sb = new StringBuilder("MeasureSpec: "); 21102 21103 if (mode == UNSPECIFIED) 21104 sb.append("UNSPECIFIED "); 21105 else if (mode == EXACTLY) 21106 sb.append("EXACTLY "); 21107 else if (mode == AT_MOST) 21108 sb.append("AT_MOST "); 21109 else 21110 sb.append(mode).append(" "); 21111 21112 sb.append(size); 21113 return sb.toString(); 21114 } 21115 } 21116 21117 private final class CheckForLongPress implements Runnable { 21118 private int mOriginalWindowAttachCount; 21119 21120 @Override 21121 public void run() { 21122 if (isPressed() && (mParent != null) 21123 && mOriginalWindowAttachCount == mWindowAttachCount) { 21124 if (performLongClick()) { 21125 mHasPerformedLongPress = true; 21126 } 21127 } 21128 } 21129 21130 public void rememberWindowAttachCount() { 21131 mOriginalWindowAttachCount = mWindowAttachCount; 21132 } 21133 } 21134 21135 private final class CheckForTap implements Runnable { 21136 public float x; 21137 public float y; 21138 21139 @Override 21140 public void run() { 21141 mPrivateFlags &= ~PFLAG_PREPRESSED; 21142 setPressed(true, x, y); 21143 checkForLongClick(ViewConfiguration.getTapTimeout()); 21144 } 21145 } 21146 21147 private final class PerformClick implements Runnable { 21148 @Override 21149 public void run() { 21150 performClick(); 21151 } 21152 } 21153 21154 /** @hide */ 21155 public void hackTurnOffWindowResizeAnim(boolean off) { 21156 mAttachInfo.mTurnOffWindowResizeAnim = off; 21157 } 21158 21159 /** 21160 * This method returns a ViewPropertyAnimator object, which can be used to animate 21161 * specific properties on this View. 21162 * 21163 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 21164 */ 21165 public ViewPropertyAnimator animate() { 21166 if (mAnimator == null) { 21167 mAnimator = new ViewPropertyAnimator(this); 21168 } 21169 return mAnimator; 21170 } 21171 21172 /** 21173 * Sets the name of the View to be used to identify Views in Transitions. 21174 * Names should be unique in the View hierarchy. 21175 * 21176 * @param transitionName The name of the View to uniquely identify it for Transitions. 21177 */ 21178 public final void setTransitionName(String transitionName) { 21179 mTransitionName = transitionName; 21180 } 21181 21182 /** 21183 * Returns the name of the View to be used to identify Views in Transitions. 21184 * Names should be unique in the View hierarchy. 21185 * 21186 * <p>This returns null if the View has not been given a name.</p> 21187 * 21188 * @return The name used of the View to be used to identify Views in Transitions or null 21189 * if no name has been given. 21190 */ 21191 @ViewDebug.ExportedProperty 21192 public String getTransitionName() { 21193 return mTransitionName; 21194 } 21195 21196 /** 21197 * Interface definition for a callback to be invoked when a hardware key event is 21198 * dispatched to this view. The callback will be invoked before the key event is 21199 * given to the view. This is only useful for hardware keyboards; a software input 21200 * method has no obligation to trigger this listener. 21201 */ 21202 public interface OnKeyListener { 21203 /** 21204 * Called when a hardware key is dispatched to a view. This allows listeners to 21205 * get a chance to respond before the target view. 21206 * <p>Key presses in software keyboards will generally NOT trigger this method, 21207 * although some may elect to do so in some situations. Do not assume a 21208 * software input method has to be key-based; even if it is, it may use key presses 21209 * in a different way than you expect, so there is no way to reliably catch soft 21210 * input key presses. 21211 * 21212 * @param v The view the key has been dispatched to. 21213 * @param keyCode The code for the physical key that was pressed 21214 * @param event The KeyEvent object containing full information about 21215 * the event. 21216 * @return True if the listener has consumed the event, false otherwise. 21217 */ 21218 boolean onKey(View v, int keyCode, KeyEvent event); 21219 } 21220 21221 /** 21222 * Interface definition for a callback to be invoked when a touch event is 21223 * dispatched to this view. The callback will be invoked before the touch 21224 * event is given to the view. 21225 */ 21226 public interface OnTouchListener { 21227 /** 21228 * Called when a touch event is dispatched to a view. This allows listeners to 21229 * get a chance to respond before the target view. 21230 * 21231 * @param v The view the touch event has been dispatched to. 21232 * @param event The MotionEvent object containing full information about 21233 * the event. 21234 * @return True if the listener has consumed the event, false otherwise. 21235 */ 21236 boolean onTouch(View v, MotionEvent event); 21237 } 21238 21239 /** 21240 * Interface definition for a callback to be invoked when a hover event is 21241 * dispatched to this view. The callback will be invoked before the hover 21242 * event is given to the view. 21243 */ 21244 public interface OnHoverListener { 21245 /** 21246 * Called when a hover event is dispatched to a view. This allows listeners to 21247 * get a chance to respond before the target view. 21248 * 21249 * @param v The view the hover event has been dispatched to. 21250 * @param event The MotionEvent object containing full information about 21251 * the event. 21252 * @return True if the listener has consumed the event, false otherwise. 21253 */ 21254 boolean onHover(View v, MotionEvent event); 21255 } 21256 21257 /** 21258 * Interface definition for a callback to be invoked when a generic motion event is 21259 * dispatched to this view. The callback will be invoked before the generic motion 21260 * event is given to the view. 21261 */ 21262 public interface OnGenericMotionListener { 21263 /** 21264 * Called when a generic motion event is dispatched to a view. This allows listeners to 21265 * get a chance to respond before the target view. 21266 * 21267 * @param v The view the generic motion event has been dispatched to. 21268 * @param event The MotionEvent object containing full information about 21269 * the event. 21270 * @return True if the listener has consumed the event, false otherwise. 21271 */ 21272 boolean onGenericMotion(View v, MotionEvent event); 21273 } 21274 21275 /** 21276 * Interface definition for a callback to be invoked when a view has been clicked and held. 21277 */ 21278 public interface OnLongClickListener { 21279 /** 21280 * Called when a view has been clicked and held. 21281 * 21282 * @param v The view that was clicked and held. 21283 * 21284 * @return true if the callback consumed the long click, false otherwise. 21285 */ 21286 boolean onLongClick(View v); 21287 } 21288 21289 /** 21290 * Interface definition for a callback to be invoked when a drag is being dispatched 21291 * to this view. The callback will be invoked before the hosting view's own 21292 * onDrag(event) method. If the listener wants to fall back to the hosting view's 21293 * onDrag(event) behavior, it should return 'false' from this callback. 21294 * 21295 * <div class="special reference"> 21296 * <h3>Developer Guides</h3> 21297 * <p>For a guide to implementing drag and drop features, read the 21298 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 21299 * </div> 21300 */ 21301 public interface OnDragListener { 21302 /** 21303 * Called when a drag event is dispatched to a view. This allows listeners 21304 * to get a chance to override base View behavior. 21305 * 21306 * @param v The View that received the drag event. 21307 * @param event The {@link android.view.DragEvent} object for the drag event. 21308 * @return {@code true} if the drag event was handled successfully, or {@code false} 21309 * if the drag event was not handled. Note that {@code false} will trigger the View 21310 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 21311 */ 21312 boolean onDrag(View v, DragEvent event); 21313 } 21314 21315 /** 21316 * Interface definition for a callback to be invoked when the focus state of 21317 * a view changed. 21318 */ 21319 public interface OnFocusChangeListener { 21320 /** 21321 * Called when the focus state of a view has changed. 21322 * 21323 * @param v The view whose state has changed. 21324 * @param hasFocus The new focus state of v. 21325 */ 21326 void onFocusChange(View v, boolean hasFocus); 21327 } 21328 21329 /** 21330 * Interface definition for a callback to be invoked when a view is clicked. 21331 */ 21332 public interface OnClickListener { 21333 /** 21334 * Called when a view has been clicked. 21335 * 21336 * @param v The view that was clicked. 21337 */ 21338 void onClick(View v); 21339 } 21340 21341 /** 21342 * Interface definition for a callback to be invoked when a view is context clicked. 21343 */ 21344 public interface OnContextClickListener { 21345 /** 21346 * Called when a view is context clicked. 21347 * 21348 * @param v The view that has been context clicked. 21349 * @return true if the callback consumed the context click, false otherwise. 21350 */ 21351 boolean onContextClick(View v); 21352 } 21353 21354 /** 21355 * Interface definition for a callback to be invoked when the context menu 21356 * for this view is being built. 21357 */ 21358 public interface OnCreateContextMenuListener { 21359 /** 21360 * Called when the context menu for this view is being built. It is not 21361 * safe to hold onto the menu after this method returns. 21362 * 21363 * @param menu The context menu that is being built 21364 * @param v The view for which the context menu is being built 21365 * @param menuInfo Extra information about the item for which the 21366 * context menu should be shown. This information will vary 21367 * depending on the class of v. 21368 */ 21369 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 21370 } 21371 21372 /** 21373 * Interface definition for a callback to be invoked when the status bar changes 21374 * visibility. This reports <strong>global</strong> changes to the system UI 21375 * state, not what the application is requesting. 21376 * 21377 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 21378 */ 21379 public interface OnSystemUiVisibilityChangeListener { 21380 /** 21381 * Called when the status bar changes visibility because of a call to 21382 * {@link View#setSystemUiVisibility(int)}. 21383 * 21384 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 21385 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 21386 * This tells you the <strong>global</strong> state of these UI visibility 21387 * flags, not what your app is currently applying. 21388 */ 21389 public void onSystemUiVisibilityChange(int visibility); 21390 } 21391 21392 /** 21393 * Interface definition for a callback to be invoked when this view is attached 21394 * or detached from its window. 21395 */ 21396 public interface OnAttachStateChangeListener { 21397 /** 21398 * Called when the view is attached to a window. 21399 * @param v The view that was attached 21400 */ 21401 public void onViewAttachedToWindow(View v); 21402 /** 21403 * Called when the view is detached from a window. 21404 * @param v The view that was detached 21405 */ 21406 public void onViewDetachedFromWindow(View v); 21407 } 21408 21409 /** 21410 * Listener for applying window insets on a view in a custom way. 21411 * 21412 * <p>Apps may choose to implement this interface if they want to apply custom policy 21413 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 21414 * is set, its 21415 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 21416 * method will be called instead of the View's own 21417 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 21418 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 21419 * the View's normal behavior as part of its own.</p> 21420 */ 21421 public interface OnApplyWindowInsetsListener { 21422 /** 21423 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 21424 * on a View, this listener method will be called instead of the view's own 21425 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 21426 * 21427 * @param v The view applying window insets 21428 * @param insets The insets to apply 21429 * @return The insets supplied, minus any insets that were consumed 21430 */ 21431 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 21432 } 21433 21434 private final class UnsetPressedState implements Runnable { 21435 @Override 21436 public void run() { 21437 setPressed(false); 21438 } 21439 } 21440 21441 /** 21442 * Base class for derived classes that want to save and restore their own 21443 * state in {@link android.view.View#onSaveInstanceState()}. 21444 */ 21445 public static class BaseSavedState extends AbsSavedState { 21446 String mStartActivityRequestWhoSaved; 21447 21448 /** 21449 * Constructor used when reading from a parcel. Reads the state of the superclass. 21450 * 21451 * @param source 21452 */ 21453 public BaseSavedState(Parcel source) { 21454 super(source); 21455 mStartActivityRequestWhoSaved = source.readString(); 21456 } 21457 21458 /** 21459 * Constructor called by derived classes when creating their SavedState objects 21460 * 21461 * @param superState The state of the superclass of this view 21462 */ 21463 public BaseSavedState(Parcelable superState) { 21464 super(superState); 21465 } 21466 21467 @Override 21468 public void writeToParcel(Parcel out, int flags) { 21469 super.writeToParcel(out, flags); 21470 out.writeString(mStartActivityRequestWhoSaved); 21471 } 21472 21473 public static final Parcelable.Creator<BaseSavedState> CREATOR = 21474 new Parcelable.Creator<BaseSavedState>() { 21475 public BaseSavedState createFromParcel(Parcel in) { 21476 return new BaseSavedState(in); 21477 } 21478 21479 public BaseSavedState[] newArray(int size) { 21480 return new BaseSavedState[size]; 21481 } 21482 }; 21483 } 21484 21485 /** 21486 * A set of information given to a view when it is attached to its parent 21487 * window. 21488 */ 21489 final static class AttachInfo { 21490 interface Callbacks { 21491 void playSoundEffect(int effectId); 21492 boolean performHapticFeedback(int effectId, boolean always); 21493 } 21494 21495 /** 21496 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 21497 * to a Handler. This class contains the target (View) to invalidate and 21498 * the coordinates of the dirty rectangle. 21499 * 21500 * For performance purposes, this class also implements a pool of up to 21501 * POOL_LIMIT objects that get reused. This reduces memory allocations 21502 * whenever possible. 21503 */ 21504 static class InvalidateInfo { 21505 private static final int POOL_LIMIT = 10; 21506 21507 private static final SynchronizedPool<InvalidateInfo> sPool = 21508 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 21509 21510 View target; 21511 21512 int left; 21513 int top; 21514 int right; 21515 int bottom; 21516 21517 public static InvalidateInfo obtain() { 21518 InvalidateInfo instance = sPool.acquire(); 21519 return (instance != null) ? instance : new InvalidateInfo(); 21520 } 21521 21522 public void recycle() { 21523 target = null; 21524 sPool.release(this); 21525 } 21526 } 21527 21528 final IWindowSession mSession; 21529 21530 final IWindow mWindow; 21531 21532 final IBinder mWindowToken; 21533 21534 final Display mDisplay; 21535 21536 final Callbacks mRootCallbacks; 21537 21538 IWindowId mIWindowId; 21539 WindowId mWindowId; 21540 21541 /** 21542 * The top view of the hierarchy. 21543 */ 21544 View mRootView; 21545 21546 IBinder mPanelParentWindowToken; 21547 21548 boolean mHardwareAccelerated; 21549 boolean mHardwareAccelerationRequested; 21550 HardwareRenderer mHardwareRenderer; 21551 List<RenderNode> mPendingAnimatingRenderNodes; 21552 21553 /** 21554 * The state of the display to which the window is attached, as reported 21555 * by {@link Display#getState()}. Note that the display state constants 21556 * declared by {@link Display} do not exactly line up with the screen state 21557 * constants declared by {@link View} (there are more display states than 21558 * screen states). 21559 */ 21560 int mDisplayState = Display.STATE_UNKNOWN; 21561 21562 /** 21563 * Scale factor used by the compatibility mode 21564 */ 21565 float mApplicationScale; 21566 21567 /** 21568 * Indicates whether the application is in compatibility mode 21569 */ 21570 boolean mScalingRequired; 21571 21572 /** 21573 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 21574 */ 21575 boolean mTurnOffWindowResizeAnim; 21576 21577 /** 21578 * Left position of this view's window 21579 */ 21580 int mWindowLeft; 21581 21582 /** 21583 * Top position of this view's window 21584 */ 21585 int mWindowTop; 21586 21587 /** 21588 * Indicates whether views need to use 32-bit drawing caches 21589 */ 21590 boolean mUse32BitDrawingCache; 21591 21592 /** 21593 * For windows that are full-screen but using insets to layout inside 21594 * of the screen areas, these are the current insets to appear inside 21595 * the overscan area of the display. 21596 */ 21597 final Rect mOverscanInsets = new Rect(); 21598 21599 /** 21600 * For windows that are full-screen but using insets to layout inside 21601 * of the screen decorations, these are the current insets for the 21602 * content of the window. 21603 */ 21604 final Rect mContentInsets = new Rect(); 21605 21606 /** 21607 * For windows that are full-screen but using insets to layout inside 21608 * of the screen decorations, these are the current insets for the 21609 * actual visible parts of the window. 21610 */ 21611 final Rect mVisibleInsets = new Rect(); 21612 21613 /** 21614 * For windows that are full-screen but using insets to layout inside 21615 * of the screen decorations, these are the current insets for the 21616 * stable system windows. 21617 */ 21618 final Rect mStableInsets = new Rect(); 21619 21620 /** 21621 * For windows that include areas that are not covered by real surface these are the outsets 21622 * for real surface. 21623 */ 21624 final Rect mOutsets = new Rect(); 21625 21626 /** 21627 * The internal insets given by this window. This value is 21628 * supplied by the client (through 21629 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 21630 * be given to the window manager when changed to be used in laying 21631 * out windows behind it. 21632 */ 21633 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 21634 = new ViewTreeObserver.InternalInsetsInfo(); 21635 21636 /** 21637 * Set to true when mGivenInternalInsets is non-empty. 21638 */ 21639 boolean mHasNonEmptyGivenInternalInsets; 21640 21641 /** 21642 * All views in the window's hierarchy that serve as scroll containers, 21643 * used to determine if the window can be resized or must be panned 21644 * to adjust for a soft input area. 21645 */ 21646 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 21647 21648 final KeyEvent.DispatcherState mKeyDispatchState 21649 = new KeyEvent.DispatcherState(); 21650 21651 /** 21652 * Indicates whether the view's window currently has the focus. 21653 */ 21654 boolean mHasWindowFocus; 21655 21656 /** 21657 * The current visibility of the window. 21658 */ 21659 int mWindowVisibility; 21660 21661 /** 21662 * Indicates the time at which drawing started to occur. 21663 */ 21664 long mDrawingTime; 21665 21666 /** 21667 * Indicates whether or not ignoring the DIRTY_MASK flags. 21668 */ 21669 boolean mIgnoreDirtyState; 21670 21671 /** 21672 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 21673 * to avoid clearing that flag prematurely. 21674 */ 21675 boolean mSetIgnoreDirtyState = false; 21676 21677 /** 21678 * Indicates whether the view's window is currently in touch mode. 21679 */ 21680 boolean mInTouchMode; 21681 21682 /** 21683 * Indicates whether the view has requested unbuffered input dispatching for the current 21684 * event stream. 21685 */ 21686 boolean mUnbufferedDispatchRequested; 21687 21688 /** 21689 * Indicates that ViewAncestor should trigger a global layout change 21690 * the next time it performs a traversal 21691 */ 21692 boolean mRecomputeGlobalAttributes; 21693 21694 /** 21695 * Always report new attributes at next traversal. 21696 */ 21697 boolean mForceReportNewAttributes; 21698 21699 /** 21700 * Set during a traveral if any views want to keep the screen on. 21701 */ 21702 boolean mKeepScreenOn; 21703 21704 /** 21705 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 21706 */ 21707 int mSystemUiVisibility; 21708 21709 /** 21710 * Hack to force certain system UI visibility flags to be cleared. 21711 */ 21712 int mDisabledSystemUiVisibility; 21713 21714 /** 21715 * Last global system UI visibility reported by the window manager. 21716 */ 21717 int mGlobalSystemUiVisibility; 21718 21719 /** 21720 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 21721 * attached. 21722 */ 21723 boolean mHasSystemUiListeners; 21724 21725 /** 21726 * Set if the window has requested to extend into the overscan region 21727 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 21728 */ 21729 boolean mOverscanRequested; 21730 21731 /** 21732 * Set if the visibility of any views has changed. 21733 */ 21734 boolean mViewVisibilityChanged; 21735 21736 /** 21737 * Set to true if a view has been scrolled. 21738 */ 21739 boolean mViewScrollChanged; 21740 21741 /** 21742 * Set to true if high contrast mode enabled 21743 */ 21744 boolean mHighContrastText; 21745 21746 /** 21747 * Global to the view hierarchy used as a temporary for dealing with 21748 * x/y points in the transparent region computations. 21749 */ 21750 final int[] mTransparentLocation = new int[2]; 21751 21752 /** 21753 * Global to the view hierarchy used as a temporary for dealing with 21754 * x/y points in the ViewGroup.invalidateChild implementation. 21755 */ 21756 final int[] mInvalidateChildLocation = new int[2]; 21757 21758 /** 21759 * Global to the view hierarchy used as a temporary for dealng with 21760 * computing absolute on-screen location. 21761 */ 21762 final int[] mTmpLocation = new int[2]; 21763 21764 /** 21765 * Global to the view hierarchy used as a temporary for dealing with 21766 * x/y location when view is transformed. 21767 */ 21768 final float[] mTmpTransformLocation = new float[2]; 21769 21770 /** 21771 * The view tree observer used to dispatch global events like 21772 * layout, pre-draw, touch mode change, etc. 21773 */ 21774 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 21775 21776 /** 21777 * A Canvas used by the view hierarchy to perform bitmap caching. 21778 */ 21779 Canvas mCanvas; 21780 21781 /** 21782 * The view root impl. 21783 */ 21784 final ViewRootImpl mViewRootImpl; 21785 21786 /** 21787 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 21788 * handler can be used to pump events in the UI events queue. 21789 */ 21790 final Handler mHandler; 21791 21792 /** 21793 * Temporary for use in computing invalidate rectangles while 21794 * calling up the hierarchy. 21795 */ 21796 final Rect mTmpInvalRect = new Rect(); 21797 21798 /** 21799 * Temporary for use in computing hit areas with transformed views 21800 */ 21801 final RectF mTmpTransformRect = new RectF(); 21802 21803 /** 21804 * Temporary for use in computing hit areas with transformed views 21805 */ 21806 final RectF mTmpTransformRect1 = new RectF(); 21807 21808 /** 21809 * Temporary list of rectanges. 21810 */ 21811 final List<RectF> mTmpRectList = new ArrayList<>(); 21812 21813 /** 21814 * Temporary for use in transforming invalidation rect 21815 */ 21816 final Matrix mTmpMatrix = new Matrix(); 21817 21818 /** 21819 * Temporary for use in transforming invalidation rect 21820 */ 21821 final Transformation mTmpTransformation = new Transformation(); 21822 21823 /** 21824 * Temporary for use in querying outlines from OutlineProviders 21825 */ 21826 final Outline mTmpOutline = new Outline(); 21827 21828 /** 21829 * Temporary list for use in collecting focusable descendents of a view. 21830 */ 21831 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 21832 21833 /** 21834 * The id of the window for accessibility purposes. 21835 */ 21836 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 21837 21838 /** 21839 * Flags related to accessibility processing. 21840 * 21841 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 21842 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 21843 */ 21844 int mAccessibilityFetchFlags; 21845 21846 /** 21847 * The drawable for highlighting accessibility focus. 21848 */ 21849 Drawable mAccessibilityFocusDrawable; 21850 21851 /** 21852 * Show where the margins, bounds and layout bounds are for each view. 21853 */ 21854 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 21855 21856 /** 21857 * Point used to compute visible regions. 21858 */ 21859 final Point mPoint = new Point(); 21860 21861 /** 21862 * Used to track which View originated a requestLayout() call, used when 21863 * requestLayout() is called during layout. 21864 */ 21865 View mViewRequestingLayout; 21866 21867 /** 21868 * Creates a new set of attachment information with the specified 21869 * events handler and thread. 21870 * 21871 * @param handler the events handler the view must use 21872 */ 21873 AttachInfo(IWindowSession session, IWindow window, Display display, 21874 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 21875 mSession = session; 21876 mWindow = window; 21877 mWindowToken = window.asBinder(); 21878 mDisplay = display; 21879 mViewRootImpl = viewRootImpl; 21880 mHandler = handler; 21881 mRootCallbacks = effectPlayer; 21882 } 21883 } 21884 21885 /** 21886 * <p>ScrollabilityCache holds various fields used by a View when scrolling 21887 * is supported. This avoids keeping too many unused fields in most 21888 * instances of View.</p> 21889 */ 21890 private static class ScrollabilityCache implements Runnable { 21891 21892 /** 21893 * Scrollbars are not visible 21894 */ 21895 public static final int OFF = 0; 21896 21897 /** 21898 * Scrollbars are visible 21899 */ 21900 public static final int ON = 1; 21901 21902 /** 21903 * Scrollbars are fading away 21904 */ 21905 public static final int FADING = 2; 21906 21907 public boolean fadeScrollBars; 21908 21909 public int fadingEdgeLength; 21910 public int scrollBarDefaultDelayBeforeFade; 21911 public int scrollBarFadeDuration; 21912 21913 public int scrollBarSize; 21914 public ScrollBarDrawable scrollBar; 21915 public float[] interpolatorValues; 21916 public View host; 21917 21918 public final Paint paint; 21919 public final Matrix matrix; 21920 public Shader shader; 21921 21922 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 21923 21924 private static final float[] OPAQUE = { 255 }; 21925 private static final float[] TRANSPARENT = { 0.0f }; 21926 21927 /** 21928 * When fading should start. This time moves into the future every time 21929 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 21930 */ 21931 public long fadeStartTime; 21932 21933 21934 /** 21935 * The current state of the scrollbars: ON, OFF, or FADING 21936 */ 21937 public int state = OFF; 21938 21939 private int mLastColor; 21940 21941 public ScrollabilityCache(ViewConfiguration configuration, View host) { 21942 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 21943 scrollBarSize = configuration.getScaledScrollBarSize(); 21944 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 21945 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 21946 21947 paint = new Paint(); 21948 matrix = new Matrix(); 21949 // use use a height of 1, and then wack the matrix each time we 21950 // actually use it. 21951 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 21952 paint.setShader(shader); 21953 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 21954 21955 this.host = host; 21956 } 21957 21958 public void setFadeColor(int color) { 21959 if (color != mLastColor) { 21960 mLastColor = color; 21961 21962 if (color != 0) { 21963 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 21964 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 21965 paint.setShader(shader); 21966 // Restore the default transfer mode (src_over) 21967 paint.setXfermode(null); 21968 } else { 21969 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 21970 paint.setShader(shader); 21971 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 21972 } 21973 } 21974 } 21975 21976 public void run() { 21977 long now = AnimationUtils.currentAnimationTimeMillis(); 21978 if (now >= fadeStartTime) { 21979 21980 // the animation fades the scrollbars out by changing 21981 // the opacity (alpha) from fully opaque to fully 21982 // transparent 21983 int nextFrame = (int) now; 21984 int framesCount = 0; 21985 21986 Interpolator interpolator = scrollBarInterpolator; 21987 21988 // Start opaque 21989 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 21990 21991 // End transparent 21992 nextFrame += scrollBarFadeDuration; 21993 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 21994 21995 state = FADING; 21996 21997 // Kick off the fade animation 21998 host.invalidate(true); 21999 } 22000 } 22001 } 22002 22003 /** 22004 * Resuable callback for sending 22005 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 22006 */ 22007 private class SendViewScrolledAccessibilityEvent implements Runnable { 22008 public volatile boolean mIsPending; 22009 22010 public void run() { 22011 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 22012 mIsPending = false; 22013 } 22014 } 22015 22016 /** 22017 * <p> 22018 * This class represents a delegate that can be registered in a {@link View} 22019 * to enhance accessibility support via composition rather via inheritance. 22020 * It is specifically targeted to widget developers that extend basic View 22021 * classes i.e. classes in package android.view, that would like their 22022 * applications to be backwards compatible. 22023 * </p> 22024 * <div class="special reference"> 22025 * <h3>Developer Guides</h3> 22026 * <p>For more information about making applications accessible, read the 22027 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 22028 * developer guide.</p> 22029 * </div> 22030 * <p> 22031 * A scenario in which a developer would like to use an accessibility delegate 22032 * is overriding a method introduced in a later API version then the minimal API 22033 * version supported by the application. For example, the method 22034 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 22035 * in API version 4 when the accessibility APIs were first introduced. If a 22036 * developer would like his application to run on API version 4 devices (assuming 22037 * all other APIs used by the application are version 4 or lower) and take advantage 22038 * of this method, instead of overriding the method which would break the application's 22039 * backwards compatibility, he can override the corresponding method in this 22040 * delegate and register the delegate in the target View if the API version of 22041 * the system is high enough i.e. the API version is same or higher to the API 22042 * version that introduced 22043 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 22044 * </p> 22045 * <p> 22046 * Here is an example implementation: 22047 * </p> 22048 * <code><pre><p> 22049 * if (Build.VERSION.SDK_INT >= 14) { 22050 * // If the API version is equal of higher than the version in 22051 * // which onInitializeAccessibilityNodeInfo was introduced we 22052 * // register a delegate with a customized implementation. 22053 * View view = findViewById(R.id.view_id); 22054 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 22055 * public void onInitializeAccessibilityNodeInfo(View host, 22056 * AccessibilityNodeInfo info) { 22057 * // Let the default implementation populate the info. 22058 * super.onInitializeAccessibilityNodeInfo(host, info); 22059 * // Set some other information. 22060 * info.setEnabled(host.isEnabled()); 22061 * } 22062 * }); 22063 * } 22064 * </code></pre></p> 22065 * <p> 22066 * This delegate contains methods that correspond to the accessibility methods 22067 * in View. If a delegate has been specified the implementation in View hands 22068 * off handling to the corresponding method in this delegate. The default 22069 * implementation the delegate methods behaves exactly as the corresponding 22070 * method in View for the case of no accessibility delegate been set. Hence, 22071 * to customize the behavior of a View method, clients can override only the 22072 * corresponding delegate method without altering the behavior of the rest 22073 * accessibility related methods of the host view. 22074 * </p> 22075 */ 22076 public static class AccessibilityDelegate { 22077 22078 /** 22079 * Sends an accessibility event of the given type. If accessibility is not 22080 * enabled this method has no effect. 22081 * <p> 22082 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 22083 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 22084 * been set. 22085 * </p> 22086 * 22087 * @param host The View hosting the delegate. 22088 * @param eventType The type of the event to send. 22089 * 22090 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 22091 */ 22092 public void sendAccessibilityEvent(View host, int eventType) { 22093 host.sendAccessibilityEventInternal(eventType); 22094 } 22095 22096 /** 22097 * Performs the specified accessibility action on the view. For 22098 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 22099 * <p> 22100 * The default implementation behaves as 22101 * {@link View#performAccessibilityAction(int, Bundle) 22102 * View#performAccessibilityAction(int, Bundle)} for the case of 22103 * no accessibility delegate been set. 22104 * </p> 22105 * 22106 * @param action The action to perform. 22107 * @return Whether the action was performed. 22108 * 22109 * @see View#performAccessibilityAction(int, Bundle) 22110 * View#performAccessibilityAction(int, Bundle) 22111 */ 22112 public boolean performAccessibilityAction(View host, int action, Bundle args) { 22113 return host.performAccessibilityActionInternal(action, args); 22114 } 22115 22116 /** 22117 * Sends an accessibility event. This method behaves exactly as 22118 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 22119 * empty {@link AccessibilityEvent} and does not perform a check whether 22120 * accessibility is enabled. 22121 * <p> 22122 * The default implementation behaves as 22123 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 22124 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 22125 * the case of no accessibility delegate been set. 22126 * </p> 22127 * 22128 * @param host The View hosting the delegate. 22129 * @param event The event to send. 22130 * 22131 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 22132 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 22133 */ 22134 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 22135 host.sendAccessibilityEventUncheckedInternal(event); 22136 } 22137 22138 /** 22139 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 22140 * to its children for adding their text content to the event. 22141 * <p> 22142 * The default implementation behaves as 22143 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 22144 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 22145 * the case of no accessibility delegate been set. 22146 * </p> 22147 * 22148 * @param host The View hosting the delegate. 22149 * @param event The event. 22150 * @return True if the event population was completed. 22151 * 22152 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 22153 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 22154 */ 22155 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 22156 return host.dispatchPopulateAccessibilityEventInternal(event); 22157 } 22158 22159 /** 22160 * Gives a chance to the host View to populate the accessibility event with its 22161 * text content. 22162 * <p> 22163 * The default implementation behaves as 22164 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 22165 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 22166 * the case of no accessibility delegate been set. 22167 * </p> 22168 * 22169 * @param host The View hosting the delegate. 22170 * @param event The accessibility event which to populate. 22171 * 22172 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 22173 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 22174 */ 22175 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 22176 host.onPopulateAccessibilityEventInternal(event); 22177 } 22178 22179 /** 22180 * Initializes an {@link AccessibilityEvent} with information about the 22181 * the host View which is the event source. 22182 * <p> 22183 * The default implementation behaves as 22184 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 22185 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 22186 * the case of no accessibility delegate been set. 22187 * </p> 22188 * 22189 * @param host The View hosting the delegate. 22190 * @param event The event to initialize. 22191 * 22192 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 22193 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 22194 */ 22195 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 22196 host.onInitializeAccessibilityEventInternal(event); 22197 } 22198 22199 /** 22200 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 22201 * <p> 22202 * The default implementation behaves as 22203 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 22204 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 22205 * the case of no accessibility delegate been set. 22206 * </p> 22207 * 22208 * @param host The View hosting the delegate. 22209 * @param info The instance to initialize. 22210 * 22211 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 22212 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 22213 */ 22214 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 22215 host.onInitializeAccessibilityNodeInfoInternal(info); 22216 } 22217 22218 /** 22219 * Called when a child of the host View has requested sending an 22220 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 22221 * to augment the event. 22222 * <p> 22223 * The default implementation behaves as 22224 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 22225 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 22226 * the case of no accessibility delegate been set. 22227 * </p> 22228 * 22229 * @param host The View hosting the delegate. 22230 * @param child The child which requests sending the event. 22231 * @param event The event to be sent. 22232 * @return True if the event should be sent 22233 * 22234 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 22235 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 22236 */ 22237 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 22238 AccessibilityEvent event) { 22239 return host.onRequestSendAccessibilityEventInternal(child, event); 22240 } 22241 22242 /** 22243 * Gets the provider for managing a virtual view hierarchy rooted at this View 22244 * and reported to {@link android.accessibilityservice.AccessibilityService}s 22245 * that explore the window content. 22246 * <p> 22247 * The default implementation behaves as 22248 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 22249 * the case of no accessibility delegate been set. 22250 * </p> 22251 * 22252 * @return The provider. 22253 * 22254 * @see AccessibilityNodeProvider 22255 */ 22256 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 22257 return null; 22258 } 22259 22260 /** 22261 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 22262 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 22263 * This method is responsible for obtaining an accessibility node info from a 22264 * pool of reusable instances and calling 22265 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 22266 * view to initialize the former. 22267 * <p> 22268 * <strong>Note:</strong> The client is responsible for recycling the obtained 22269 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 22270 * creation. 22271 * </p> 22272 * <p> 22273 * The default implementation behaves as 22274 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 22275 * the case of no accessibility delegate been set. 22276 * </p> 22277 * @return A populated {@link AccessibilityNodeInfo}. 22278 * 22279 * @see AccessibilityNodeInfo 22280 * 22281 * @hide 22282 */ 22283 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 22284 return host.createAccessibilityNodeInfoInternal(); 22285 } 22286 } 22287 22288 private class MatchIdPredicate implements Predicate<View> { 22289 public int mId; 22290 22291 @Override 22292 public boolean apply(View view) { 22293 return (view.mID == mId); 22294 } 22295 } 22296 22297 private class MatchLabelForPredicate implements Predicate<View> { 22298 private int mLabeledId; 22299 22300 @Override 22301 public boolean apply(View view) { 22302 return (view.mLabelForId == mLabeledId); 22303 } 22304 } 22305 22306 private class SendViewStateChangedAccessibilityEvent implements Runnable { 22307 private int mChangeTypes = 0; 22308 private boolean mPosted; 22309 private boolean mPostedWithDelay; 22310 private long mLastEventTimeMillis; 22311 22312 @Override 22313 public void run() { 22314 mPosted = false; 22315 mPostedWithDelay = false; 22316 mLastEventTimeMillis = SystemClock.uptimeMillis(); 22317 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 22318 final AccessibilityEvent event = AccessibilityEvent.obtain(); 22319 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 22320 event.setContentChangeTypes(mChangeTypes); 22321 sendAccessibilityEventUnchecked(event); 22322 } 22323 mChangeTypes = 0; 22324 } 22325 22326 public void runOrPost(int changeType) { 22327 mChangeTypes |= changeType; 22328 22329 // If this is a live region or the child of a live region, collect 22330 // all events from this frame and send them on the next frame. 22331 if (inLiveRegion()) { 22332 // If we're already posted with a delay, remove that. 22333 if (mPostedWithDelay) { 22334 removeCallbacks(this); 22335 mPostedWithDelay = false; 22336 } 22337 // Only post if we're not already posted. 22338 if (!mPosted) { 22339 post(this); 22340 mPosted = true; 22341 } 22342 return; 22343 } 22344 22345 if (mPosted) { 22346 return; 22347 } 22348 22349 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 22350 final long minEventIntevalMillis = 22351 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 22352 if (timeSinceLastMillis >= minEventIntevalMillis) { 22353 removeCallbacks(this); 22354 run(); 22355 } else { 22356 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 22357 mPostedWithDelay = true; 22358 } 22359 } 22360 } 22361 22362 private boolean inLiveRegion() { 22363 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 22364 return true; 22365 } 22366 22367 ViewParent parent = getParent(); 22368 while (parent instanceof View) { 22369 if (((View) parent).getAccessibilityLiveRegion() 22370 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 22371 return true; 22372 } 22373 parent = parent.getParent(); 22374 } 22375 22376 return false; 22377 } 22378 22379 /** 22380 * Dump all private flags in readable format, useful for documentation and 22381 * sanity checking. 22382 */ 22383 private static void dumpFlags() { 22384 final HashMap<String, String> found = Maps.newHashMap(); 22385 try { 22386 for (Field field : View.class.getDeclaredFields()) { 22387 final int modifiers = field.getModifiers(); 22388 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 22389 if (field.getType().equals(int.class)) { 22390 final int value = field.getInt(null); 22391 dumpFlag(found, field.getName(), value); 22392 } else if (field.getType().equals(int[].class)) { 22393 final int[] values = (int[]) field.get(null); 22394 for (int i = 0; i < values.length; i++) { 22395 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 22396 } 22397 } 22398 } 22399 } 22400 } catch (IllegalAccessException e) { 22401 throw new RuntimeException(e); 22402 } 22403 22404 final ArrayList<String> keys = Lists.newArrayList(); 22405 keys.addAll(found.keySet()); 22406 Collections.sort(keys); 22407 for (String key : keys) { 22408 Log.d(VIEW_LOG_TAG, found.get(key)); 22409 } 22410 } 22411 22412 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 22413 // Sort flags by prefix, then by bits, always keeping unique keys 22414 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 22415 final int prefix = name.indexOf('_'); 22416 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 22417 final String output = bits + " " + name; 22418 found.put(key, output); 22419 } 22420 22421 /** {@hide} */ 22422 public void encode(@NonNull ViewHierarchyEncoder stream) { 22423 stream.beginObject(this); 22424 encodeProperties(stream); 22425 stream.endObject(); 22426 } 22427 22428 /** {@hide} */ 22429 @CallSuper 22430 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 22431 Object resolveId = ViewDebug.resolveId(getContext(), mID); 22432 if (resolveId instanceof String) { 22433 stream.addProperty("id", (String) resolveId); 22434 } else { 22435 stream.addProperty("id", mID); 22436 } 22437 22438 stream.addProperty("misc:transformation.alpha", 22439 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 22440 stream.addProperty("misc:transitionName", getTransitionName()); 22441 22442 // layout 22443 stream.addProperty("layout:left", mLeft); 22444 stream.addProperty("layout:right", mRight); 22445 stream.addProperty("layout:top", mTop); 22446 stream.addProperty("layout:bottom", mBottom); 22447 stream.addProperty("layout:width", getWidth()); 22448 stream.addProperty("layout:height", getHeight()); 22449 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 22450 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 22451 stream.addProperty("layout:hasTransientState", hasTransientState()); 22452 stream.addProperty("layout:baseline", getBaseline()); 22453 22454 // layout params 22455 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 22456 if (layoutParams != null) { 22457 stream.addPropertyKey("layoutParams"); 22458 layoutParams.encode(stream); 22459 } 22460 22461 // scrolling 22462 stream.addProperty("scrolling:scrollX", mScrollX); 22463 stream.addProperty("scrolling:scrollY", mScrollY); 22464 22465 // padding 22466 stream.addProperty("padding:paddingLeft", mPaddingLeft); 22467 stream.addProperty("padding:paddingRight", mPaddingRight); 22468 stream.addProperty("padding:paddingTop", mPaddingTop); 22469 stream.addProperty("padding:paddingBottom", mPaddingBottom); 22470 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 22471 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 22472 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 22473 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 22474 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 22475 22476 // measurement 22477 stream.addProperty("measurement:minHeight", mMinHeight); 22478 stream.addProperty("measurement:minWidth", mMinWidth); 22479 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 22480 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 22481 22482 // drawing 22483 stream.addProperty("drawing:elevation", getElevation()); 22484 stream.addProperty("drawing:translationX", getTranslationX()); 22485 stream.addProperty("drawing:translationY", getTranslationY()); 22486 stream.addProperty("drawing:translationZ", getTranslationZ()); 22487 stream.addProperty("drawing:rotation", getRotation()); 22488 stream.addProperty("drawing:rotationX", getRotationX()); 22489 stream.addProperty("drawing:rotationY", getRotationY()); 22490 stream.addProperty("drawing:scaleX", getScaleX()); 22491 stream.addProperty("drawing:scaleY", getScaleY()); 22492 stream.addProperty("drawing:pivotX", getPivotX()); 22493 stream.addProperty("drawing:pivotY", getPivotY()); 22494 stream.addProperty("drawing:opaque", isOpaque()); 22495 stream.addProperty("drawing:alpha", getAlpha()); 22496 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 22497 stream.addProperty("drawing:shadow", hasShadow()); 22498 stream.addProperty("drawing:solidColor", getSolidColor()); 22499 stream.addProperty("drawing:layerType", mLayerType); 22500 stream.addProperty("drawing:willNotDraw", willNotDraw()); 22501 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 22502 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 22503 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 22504 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 22505 22506 // focus 22507 stream.addProperty("focus:hasFocus", hasFocus()); 22508 stream.addProperty("focus:isFocused", isFocused()); 22509 stream.addProperty("focus:isFocusable", isFocusable()); 22510 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 22511 22512 stream.addProperty("misc:clickable", isClickable()); 22513 stream.addProperty("misc:pressed", isPressed()); 22514 stream.addProperty("misc:selected", isSelected()); 22515 stream.addProperty("misc:touchMode", isInTouchMode()); 22516 stream.addProperty("misc:hovered", isHovered()); 22517 stream.addProperty("misc:activated", isActivated()); 22518 22519 stream.addProperty("misc:visibility", getVisibility()); 22520 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 22521 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 22522 22523 stream.addProperty("misc:enabled", isEnabled()); 22524 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 22525 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 22526 22527 // theme attributes 22528 Resources.Theme theme = getContext().getTheme(); 22529 if (theme != null) { 22530 stream.addPropertyKey("theme"); 22531 theme.encode(stream); 22532 } 22533 22534 // view attribute information 22535 int n = mAttributes != null ? mAttributes.length : 0; 22536 stream.addProperty("meta:__attrCount__", n/2); 22537 for (int i = 0; i < n; i += 2) { 22538 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 22539 } 22540 22541 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 22542 22543 // text 22544 stream.addProperty("text:textDirection", getTextDirection()); 22545 stream.addProperty("text:textAlignment", getTextAlignment()); 22546 22547 // accessibility 22548 CharSequence contentDescription = getContentDescription(); 22549 stream.addProperty("accessibility:contentDescription", 22550 contentDescription == null ? "" : contentDescription.toString()); 22551 stream.addProperty("accessibility:labelFor", getLabelFor()); 22552 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 22553 } 22554} 22555