View.java revision 910beb8f5d9042163e2ad0dbb744d9f147db9604
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.IntRange; 28import android.annotation.LayoutRes; 29import android.annotation.NonNull; 30import android.annotation.Nullable; 31import android.annotation.Size; 32import android.annotation.UiThread; 33import android.content.ClipData; 34import android.content.Context; 35import android.content.ContextWrapper; 36import android.content.Intent; 37import android.content.res.ColorStateList; 38import android.content.res.Configuration; 39import android.content.res.Resources; 40import android.content.res.TypedArray; 41import android.graphics.Bitmap; 42import android.graphics.Canvas; 43import android.graphics.Insets; 44import android.graphics.Interpolator; 45import android.graphics.LinearGradient; 46import android.graphics.Matrix; 47import android.graphics.Outline; 48import android.graphics.Paint; 49import android.graphics.PixelFormat; 50import android.graphics.Point; 51import android.graphics.PorterDuff; 52import android.graphics.PorterDuffXfermode; 53import android.graphics.Rect; 54import android.graphics.RectF; 55import android.graphics.Region; 56import android.graphics.Shader; 57import android.graphics.drawable.ColorDrawable; 58import android.graphics.drawable.Drawable; 59import android.hardware.display.DisplayManagerGlobal; 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.CharacterTextSegmentIterator; 84import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 85import android.view.AccessibilityIterators.TextSegmentIterator; 86import android.view.AccessibilityIterators.WordTextSegmentIterator; 87import android.view.ViewGroup.LayoutParams; 88import android.view.accessibility.AccessibilityEvent; 89import android.view.accessibility.AccessibilityEventSource; 90import android.view.accessibility.AccessibilityManager; 91import android.view.accessibility.AccessibilityNodeInfo; 92import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 93import android.view.accessibility.AccessibilityNodeProvider; 94import android.view.animation.Animation; 95import android.view.animation.AnimationUtils; 96import android.view.animation.Transformation; 97import android.view.inputmethod.EditorInfo; 98import android.view.inputmethod.InputConnection; 99import android.view.inputmethod.InputMethodManager; 100import android.widget.Checkable; 101import android.widget.FrameLayout; 102import android.widget.ScrollBarDrawable; 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.android.internal.widget.ScrollBarUtils; 110import com.google.android.collect.Lists; 111import com.google.android.collect.Maps; 112 113import java.lang.NullPointerException; 114import java.lang.annotation.Retention; 115import java.lang.annotation.RetentionPolicy; 116import java.lang.ref.WeakReference; 117import java.lang.reflect.Field; 118import java.lang.reflect.InvocationTargetException; 119import java.lang.reflect.Method; 120import java.lang.reflect.Modifier; 121import java.util.ArrayList; 122import java.util.Arrays; 123import java.util.Collections; 124import java.util.HashMap; 125import java.util.List; 126import java.util.Locale; 127import java.util.Map; 128import java.util.concurrent.CopyOnWriteArrayList; 129import java.util.concurrent.atomic.AtomicInteger; 130 131/** 132 * <p> 133 * This class represents the basic building block for user interface components. A View 134 * occupies a rectangular area on the screen and is responsible for drawing and 135 * event handling. View is the base class for <em>widgets</em>, which are 136 * used to create interactive UI components (buttons, text fields, etc.). The 137 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 138 * are invisible containers that hold other Views (or other ViewGroups) and define 139 * their layout properties. 140 * </p> 141 * 142 * <div class="special reference"> 143 * <h3>Developer Guides</h3> 144 * <p>For information about using this class to develop your application's user interface, 145 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 146 * </div> 147 * 148 * <a name="Using"></a> 149 * <h3>Using Views</h3> 150 * <p> 151 * All of the views in a window are arranged in a single tree. You can add views 152 * either from code or by specifying a tree of views in one or more XML layout 153 * files. There are many specialized subclasses of views that act as controls or 154 * are capable of displaying text, images, or other content. 155 * </p> 156 * <p> 157 * Once you have created a tree of views, there are typically a few types of 158 * common operations you may wish to perform: 159 * <ul> 160 * <li><strong>Set properties:</strong> for example setting the text of a 161 * {@link android.widget.TextView}. The available properties and the methods 162 * that set them will vary among the different subclasses of views. Note that 163 * properties that are known at build time can be set in the XML layout 164 * files.</li> 165 * <li><strong>Set focus:</strong> The framework will handled moving focus in 166 * response to user input. To force focus to a specific view, call 167 * {@link #requestFocus}.</li> 168 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 169 * that will be notified when something interesting happens to the view. For 170 * example, all views will let you set a listener to be notified when the view 171 * gains or loses focus. You can register such a listener using 172 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 173 * Other view subclasses offer more specialized listeners. For example, a Button 174 * exposes a listener to notify clients when the button is clicked.</li> 175 * <li><strong>Set visibility:</strong> You can hide or show views using 176 * {@link #setVisibility(int)}.</li> 177 * </ul> 178 * </p> 179 * <p><em> 180 * Note: The Android framework is responsible for measuring, laying out and 181 * drawing views. You should not call methods that perform these actions on 182 * views yourself unless you are actually implementing a 183 * {@link android.view.ViewGroup}. 184 * </em></p> 185 * 186 * <a name="Lifecycle"></a> 187 * <h3>Implementing a Custom View</h3> 188 * 189 * <p> 190 * To implement a custom view, you will usually begin by providing overrides for 191 * some of the standard methods that the framework calls on all views. You do 192 * not need to override all of these methods. In fact, you can start by just 193 * overriding {@link #onDraw(android.graphics.Canvas)}. 194 * <table border="2" width="85%" align="center" cellpadding="5"> 195 * <thead> 196 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 197 * </thead> 198 * 199 * <tbody> 200 * <tr> 201 * <td rowspan="2">Creation</td> 202 * <td>Constructors</td> 203 * <td>There is a form of the constructor that are called when the view 204 * is created from code and a form that is called when the view is 205 * inflated from a layout file. The second form should parse and apply 206 * any attributes defined in the layout file. 207 * </td> 208 * </tr> 209 * <tr> 210 * <td><code>{@link #onFinishInflate()}</code></td> 211 * <td>Called after a view and all of its children has been inflated 212 * from XML.</td> 213 * </tr> 214 * 215 * <tr> 216 * <td rowspan="3">Layout</td> 217 * <td><code>{@link #onMeasure(int, int)}</code></td> 218 * <td>Called to determine the size requirements for this view and all 219 * of its children. 220 * </td> 221 * </tr> 222 * <tr> 223 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 224 * <td>Called when this view should assign a size and position to all 225 * of its children. 226 * </td> 227 * </tr> 228 * <tr> 229 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 230 * <td>Called when the size of this view has changed. 231 * </td> 232 * </tr> 233 * 234 * <tr> 235 * <td>Drawing</td> 236 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 237 * <td>Called when the view should render its content. 238 * </td> 239 * </tr> 240 * 241 * <tr> 242 * <td rowspan="4">Event processing</td> 243 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 244 * <td>Called when a new hardware key event occurs. 245 * </td> 246 * </tr> 247 * <tr> 248 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 249 * <td>Called when a hardware key up event occurs. 250 * </td> 251 * </tr> 252 * <tr> 253 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 254 * <td>Called when a trackball motion event occurs. 255 * </td> 256 * </tr> 257 * <tr> 258 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 259 * <td>Called when a touch screen motion event occurs. 260 * </td> 261 * </tr> 262 * 263 * <tr> 264 * <td rowspan="2">Focus</td> 265 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 266 * <td>Called when the view gains or loses focus. 267 * </td> 268 * </tr> 269 * 270 * <tr> 271 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 272 * <td>Called when the window containing the view gains or loses focus. 273 * </td> 274 * </tr> 275 * 276 * <tr> 277 * <td rowspan="3">Attaching</td> 278 * <td><code>{@link #onAttachedToWindow()}</code></td> 279 * <td>Called when the view is attached to a window. 280 * </td> 281 * </tr> 282 * 283 * <tr> 284 * <td><code>{@link #onDetachedFromWindow}</code></td> 285 * <td>Called when the view is detached from its window. 286 * </td> 287 * </tr> 288 * 289 * <tr> 290 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 291 * <td>Called when the visibility of the window containing the view 292 * has changed. 293 * </td> 294 * </tr> 295 * </tbody> 296 * 297 * </table> 298 * </p> 299 * 300 * <a name="IDs"></a> 301 * <h3>IDs</h3> 302 * Views may have an integer id associated with them. These ids are typically 303 * assigned in the layout XML files, and are used to find specific views within 304 * the view tree. A common pattern is to: 305 * <ul> 306 * <li>Define a Button in the layout file and assign it a unique ID. 307 * <pre> 308 * <Button 309 * android:id="@+id/my_button" 310 * android:layout_width="wrap_content" 311 * android:layout_height="wrap_content" 312 * android:text="@string/my_button_text"/> 313 * </pre></li> 314 * <li>From the onCreate method of an Activity, find the Button 315 * <pre class="prettyprint"> 316 * Button myButton = (Button) findViewById(R.id.my_button); 317 * </pre></li> 318 * </ul> 319 * <p> 320 * View IDs need not be unique throughout the tree, but it is good practice to 321 * ensure that they are at least unique within the part of the tree you are 322 * searching. 323 * </p> 324 * 325 * <a name="Position"></a> 326 * <h3>Position</h3> 327 * <p> 328 * The geometry of a view is that of a rectangle. A view has a location, 329 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 330 * two dimensions, expressed as a width and a height. The unit for location 331 * and dimensions is the pixel. 332 * </p> 333 * 334 * <p> 335 * It is possible to retrieve the location of a view by invoking the methods 336 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 337 * coordinate of the rectangle representing the view. The latter returns the 338 * top, or Y, coordinate of the rectangle representing the view. These methods 339 * both return the location of the view relative to its parent. For instance, 340 * when getLeft() returns 20, that means the view is located 20 pixels to the 341 * right of the left edge of its direct parent. 342 * </p> 343 * 344 * <p> 345 * In addition, several convenience methods are offered to avoid unnecessary 346 * computations, namely {@link #getRight()} and {@link #getBottom()}. 347 * These methods return the coordinates of the right and bottom edges of the 348 * rectangle representing the view. For instance, calling {@link #getRight()} 349 * is similar to the following computation: <code>getLeft() + getWidth()</code> 350 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 351 * </p> 352 * 353 * <a name="SizePaddingMargins"></a> 354 * <h3>Size, padding and margins</h3> 355 * <p> 356 * The size of a view is expressed with a width and a height. A view actually 357 * possess two pairs of width and height values. 358 * </p> 359 * 360 * <p> 361 * The first pair is known as <em>measured width</em> and 362 * <em>measured height</em>. These dimensions define how big a view wants to be 363 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 364 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 365 * and {@link #getMeasuredHeight()}. 366 * </p> 367 * 368 * <p> 369 * The second pair is simply known as <em>width</em> and <em>height</em>, or 370 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 371 * dimensions define the actual size of the view on screen, at drawing time and 372 * after layout. These values may, but do not have to, be different from the 373 * measured width and height. The width and height can be obtained by calling 374 * {@link #getWidth()} and {@link #getHeight()}. 375 * </p> 376 * 377 * <p> 378 * To measure its dimensions, a view takes into account its padding. The padding 379 * is expressed in pixels for the left, top, right and bottom parts of the view. 380 * Padding can be used to offset the content of the view by a specific amount of 381 * pixels. For instance, a left padding of 2 will push the view's content by 382 * 2 pixels to the right of the left edge. Padding can be set using the 383 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 384 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 385 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 386 * {@link #getPaddingEnd()}. 387 * </p> 388 * 389 * <p> 390 * Even though a view can define a padding, it does not provide any support for 391 * margins. However, view groups provide such a support. Refer to 392 * {@link android.view.ViewGroup} and 393 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 394 * </p> 395 * 396 * <a name="Layout"></a> 397 * <h3>Layout</h3> 398 * <p> 399 * Layout is a two pass process: a measure pass and a layout pass. The measuring 400 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 401 * of the view tree. Each view pushes dimension specifications down the tree 402 * during the recursion. At the end of the measure pass, every view has stored 403 * its measurements. The second pass happens in 404 * {@link #layout(int,int,int,int)} and is also top-down. During 405 * this pass each parent is responsible for positioning all of its children 406 * using the sizes computed in the measure pass. 407 * </p> 408 * 409 * <p> 410 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 411 * {@link #getMeasuredHeight()} values must be set, along with those for all of 412 * that view's descendants. A view's measured width and measured height values 413 * must respect the constraints imposed by the view's parents. This guarantees 414 * that at the end of the measure pass, all parents accept all of their 415 * children's measurements. A parent view may call measure() more than once on 416 * its children. For example, the parent may measure each child once with 417 * unspecified dimensions to find out how big they want to be, then call 418 * measure() on them again with actual numbers if the sum of all the children's 419 * unconstrained sizes is too big or too small. 420 * </p> 421 * 422 * <p> 423 * The measure pass uses two classes to communicate dimensions. The 424 * {@link MeasureSpec} class is used by views to tell their parents how they 425 * want to be measured and positioned. The base LayoutParams class just 426 * describes how big the view wants to be for both width and height. For each 427 * dimension, it can specify one of: 428 * <ul> 429 * <li> an exact number 430 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 431 * (minus padding) 432 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 433 * enclose its content (plus padding). 434 * </ul> 435 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 436 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 437 * an X and Y value. 438 * </p> 439 * 440 * <p> 441 * MeasureSpecs are used to push requirements down the tree from parent to 442 * child. A MeasureSpec can be in one of three modes: 443 * <ul> 444 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 445 * of a child view. For example, a LinearLayout may call measure() on its child 446 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 447 * tall the child view wants to be given a width of 240 pixels. 448 * <li>EXACTLY: This is used by the parent to impose an exact size on the 449 * child. The child must use this size, and guarantee that all of its 450 * descendants will fit within this size. 451 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 452 * child. The child must guarantee that it and all of its descendants will fit 453 * within this size. 454 * </ul> 455 * </p> 456 * 457 * <p> 458 * To initiate a layout, call {@link #requestLayout}. This method is typically 459 * called by a view on itself when it believes that is can no longer fit within 460 * its current bounds. 461 * </p> 462 * 463 * <a name="Drawing"></a> 464 * <h3>Drawing</h3> 465 * <p> 466 * Drawing is handled by walking the tree and recording the drawing commands of 467 * any View that needs to update. After this, the drawing commands of the 468 * entire tree are issued to screen, clipped to the newly damaged area. 469 * </p> 470 * 471 * <p> 472 * The tree is largely recorded and drawn in order, with parents drawn before 473 * (i.e., behind) their children, with siblings drawn in the order they appear 474 * in the tree. If you set a background drawable for a View, then the View will 475 * draw it before calling back to its <code>onDraw()</code> method. The child 476 * drawing order can be overridden with 477 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 478 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 479 * </p> 480 * 481 * <p> 482 * To force a view to draw, call {@link #invalidate()}. 483 * </p> 484 * 485 * <a name="EventHandlingThreading"></a> 486 * <h3>Event Handling and Threading</h3> 487 * <p> 488 * The basic cycle of a view is as follows: 489 * <ol> 490 * <li>An event comes in and is dispatched to the appropriate view. The view 491 * handles the event and notifies any listeners.</li> 492 * <li>If in the course of processing the event, the view's bounds may need 493 * to be changed, the view will call {@link #requestLayout()}.</li> 494 * <li>Similarly, if in the course of processing the event the view's appearance 495 * may need to be changed, the view will call {@link #invalidate()}.</li> 496 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 497 * the framework will take care of measuring, laying out, and drawing the tree 498 * as appropriate.</li> 499 * </ol> 500 * </p> 501 * 502 * <p><em>Note: The entire view tree is single threaded. You must always be on 503 * the UI thread when calling any method on any view.</em> 504 * If you are doing work on other threads and want to update the state of a view 505 * from that thread, you should use a {@link Handler}. 506 * </p> 507 * 508 * <a name="FocusHandling"></a> 509 * <h3>Focus Handling</h3> 510 * <p> 511 * The framework will handle routine focus movement in response to user input. 512 * This includes changing the focus as views are removed or hidden, or as new 513 * views become available. Views indicate their willingness to take focus 514 * through the {@link #isFocusable} method. To change whether a view can take 515 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 516 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 517 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 518 * </p> 519 * <p> 520 * Focus movement is based on an algorithm which finds the nearest neighbor in a 521 * given direction. In rare cases, the default algorithm may not match the 522 * intended behavior of the developer. In these situations, you can provide 523 * explicit overrides by using these XML attributes in the layout file: 524 * <pre> 525 * nextFocusDown 526 * nextFocusLeft 527 * nextFocusRight 528 * nextFocusUp 529 * </pre> 530 * </p> 531 * 532 * 533 * <p> 534 * To get a particular view to take focus, call {@link #requestFocus()}. 535 * </p> 536 * 537 * <a name="TouchMode"></a> 538 * <h3>Touch Mode</h3> 539 * <p> 540 * When a user is navigating a user interface via directional keys such as a D-pad, it is 541 * necessary to give focus to actionable items such as buttons so the user can see 542 * what will take input. If the device has touch capabilities, however, and the user 543 * begins interacting with the interface by touching it, it is no longer necessary to 544 * always highlight, or give focus to, a particular view. This motivates a mode 545 * for interaction named 'touch mode'. 546 * </p> 547 * <p> 548 * For a touch capable device, once the user touches the screen, the device 549 * will enter touch mode. From this point onward, only views for which 550 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 551 * Other views that are touchable, like buttons, will not take focus when touched; they will 552 * only fire the on click listeners. 553 * </p> 554 * <p> 555 * Any time a user hits a directional key, such as a D-pad direction, the view device will 556 * exit touch mode, and find a view to take focus, so that the user may resume interacting 557 * with the user interface without touching the screen again. 558 * </p> 559 * <p> 560 * The touch mode state is maintained across {@link android.app.Activity}s. Call 561 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 562 * </p> 563 * 564 * <a name="Scrolling"></a> 565 * <h3>Scrolling</h3> 566 * <p> 567 * The framework provides basic support for views that wish to internally 568 * scroll their content. This includes keeping track of the X and Y scroll 569 * offset as well as mechanisms for drawing scrollbars. See 570 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 571 * {@link #awakenScrollBars()} for more details. 572 * </p> 573 * 574 * <a name="Tags"></a> 575 * <h3>Tags</h3> 576 * <p> 577 * Unlike IDs, tags are not used to identify views. Tags are essentially an 578 * extra piece of information that can be associated with a view. They are most 579 * often used as a convenience to store data related to views in the views 580 * themselves rather than by putting them in a separate structure. 581 * </p> 582 * <p> 583 * Tags may be specified with character sequence values in layout XML as either 584 * a single tag using the {@link android.R.styleable#View_tag android:tag} 585 * attribute or multiple tags using the {@code <tag>} child element: 586 * <pre> 587 * <View ... 588 * android:tag="@string/mytag_value" /> 589 * <View ...> 590 * <tag android:id="@+id/mytag" 591 * android:value="@string/mytag_value" /> 592 * </View> 593 * </pre> 594 * </p> 595 * <p> 596 * Tags may also be specified with arbitrary objects from code using 597 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 598 * </p> 599 * 600 * <a name="Themes"></a> 601 * <h3>Themes</h3> 602 * <p> 603 * By default, Views are created using the theme of the Context object supplied 604 * to their constructor; however, a different theme may be specified by using 605 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 606 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 607 * code. 608 * </p> 609 * <p> 610 * When the {@link android.R.styleable#View_theme android:theme} attribute is 611 * used in XML, the specified theme is applied on top of the inflation 612 * context's theme (see {@link LayoutInflater}) and used for the view itself as 613 * well as any child elements. 614 * </p> 615 * <p> 616 * In the following example, both views will be created using the Material dark 617 * color scheme; however, because an overlay theme is used which only defines a 618 * subset of attributes, the value of 619 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 620 * the inflation context's theme (e.g. the Activity theme) will be preserved. 621 * <pre> 622 * <LinearLayout 623 * ... 624 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 625 * <View ...> 626 * </LinearLayout> 627 * </pre> 628 * </p> 629 * 630 * <a name="Properties"></a> 631 * <h3>Properties</h3> 632 * <p> 633 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 634 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 635 * available both in the {@link Property} form as well as in similarly-named setter/getter 636 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 637 * be used to set persistent state associated with these rendering-related properties on the view. 638 * The properties and methods can also be used in conjunction with 639 * {@link android.animation.Animator Animator}-based animations, described more in the 640 * <a href="#Animation">Animation</a> section. 641 * </p> 642 * 643 * <a name="Animation"></a> 644 * <h3>Animation</h3> 645 * <p> 646 * Starting with Android 3.0, the preferred way of animating views is to use the 647 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 648 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 649 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 650 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 651 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 652 * makes animating these View properties particularly easy and efficient. 653 * </p> 654 * <p> 655 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 656 * You can attach an {@link Animation} object to a view using 657 * {@link #setAnimation(Animation)} or 658 * {@link #startAnimation(Animation)}. The animation can alter the scale, 659 * rotation, translation and alpha of a view over time. If the animation is 660 * attached to a view that has children, the animation will affect the entire 661 * subtree rooted by that node. When an animation is started, the framework will 662 * take care of redrawing the appropriate views until the animation completes. 663 * </p> 664 * 665 * <a name="Security"></a> 666 * <h3>Security</h3> 667 * <p> 668 * Sometimes it is essential that an application be able to verify that an action 669 * is being performed with the full knowledge and consent of the user, such as 670 * granting a permission request, making a purchase or clicking on an advertisement. 671 * Unfortunately, a malicious application could try to spoof the user into 672 * performing these actions, unaware, by concealing the intended purpose of the view. 673 * As a remedy, the framework offers a touch filtering mechanism that can be used to 674 * improve the security of views that provide access to sensitive functionality. 675 * </p><p> 676 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 677 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 678 * will discard touches that are received whenever the view's window is obscured by 679 * another visible window. As a result, the view will not receive touches whenever a 680 * toast, dialog or other window appears above the view's window. 681 * </p><p> 682 * For more fine-grained control over security, consider overriding the 683 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 684 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 685 * </p> 686 * 687 * @attr ref android.R.styleable#View_alpha 688 * @attr ref android.R.styleable#View_background 689 * @attr ref android.R.styleable#View_clickable 690 * @attr ref android.R.styleable#View_contentDescription 691 * @attr ref android.R.styleable#View_drawingCacheQuality 692 * @attr ref android.R.styleable#View_duplicateParentState 693 * @attr ref android.R.styleable#View_id 694 * @attr ref android.R.styleable#View_requiresFadingEdge 695 * @attr ref android.R.styleable#View_fadeScrollbars 696 * @attr ref android.R.styleable#View_fadingEdgeLength 697 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 698 * @attr ref android.R.styleable#View_fitsSystemWindows 699 * @attr ref android.R.styleable#View_isScrollContainer 700 * @attr ref android.R.styleable#View_focusable 701 * @attr ref android.R.styleable#View_focusableInTouchMode 702 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 703 * @attr ref android.R.styleable#View_keepScreenOn 704 * @attr ref android.R.styleable#View_layerType 705 * @attr ref android.R.styleable#View_layoutDirection 706 * @attr ref android.R.styleable#View_longClickable 707 * @attr ref android.R.styleable#View_minHeight 708 * @attr ref android.R.styleable#View_minWidth 709 * @attr ref android.R.styleable#View_nextFocusDown 710 * @attr ref android.R.styleable#View_nextFocusLeft 711 * @attr ref android.R.styleable#View_nextFocusRight 712 * @attr ref android.R.styleable#View_nextFocusUp 713 * @attr ref android.R.styleable#View_onClick 714 * @attr ref android.R.styleable#View_padding 715 * @attr ref android.R.styleable#View_paddingBottom 716 * @attr ref android.R.styleable#View_paddingLeft 717 * @attr ref android.R.styleable#View_paddingRight 718 * @attr ref android.R.styleable#View_paddingTop 719 * @attr ref android.R.styleable#View_paddingStart 720 * @attr ref android.R.styleable#View_paddingEnd 721 * @attr ref android.R.styleable#View_saveEnabled 722 * @attr ref android.R.styleable#View_rotation 723 * @attr ref android.R.styleable#View_rotationX 724 * @attr ref android.R.styleable#View_rotationY 725 * @attr ref android.R.styleable#View_scaleX 726 * @attr ref android.R.styleable#View_scaleY 727 * @attr ref android.R.styleable#View_scrollX 728 * @attr ref android.R.styleable#View_scrollY 729 * @attr ref android.R.styleable#View_scrollbarSize 730 * @attr ref android.R.styleable#View_scrollbarStyle 731 * @attr ref android.R.styleable#View_scrollbars 732 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 733 * @attr ref android.R.styleable#View_scrollbarFadeDuration 734 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 735 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 736 * @attr ref android.R.styleable#View_scrollbarThumbVertical 737 * @attr ref android.R.styleable#View_scrollbarTrackVertical 738 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 739 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 740 * @attr ref android.R.styleable#View_stateListAnimator 741 * @attr ref android.R.styleable#View_transitionName 742 * @attr ref android.R.styleable#View_soundEffectsEnabled 743 * @attr ref android.R.styleable#View_tag 744 * @attr ref android.R.styleable#View_textAlignment 745 * @attr ref android.R.styleable#View_textDirection 746 * @attr ref android.R.styleable#View_transformPivotX 747 * @attr ref android.R.styleable#View_transformPivotY 748 * @attr ref android.R.styleable#View_translationX 749 * @attr ref android.R.styleable#View_translationY 750 * @attr ref android.R.styleable#View_translationZ 751 * @attr ref android.R.styleable#View_visibility 752 * @attr ref android.R.styleable#View_theme 753 * 754 * @see android.view.ViewGroup 755 */ 756@UiThread 757public class View implements Drawable.Callback, KeyEvent.Callback, 758 AccessibilityEventSource { 759 private static final boolean DBG = false; 760 761 /** 762 * The logging tag used by this class with android.util.Log. 763 */ 764 protected static final String VIEW_LOG_TAG = "View"; 765 766 /** 767 * When set to true, apps will draw debugging information about their layouts. 768 * 769 * @hide 770 */ 771 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 772 773 /** 774 * When set to true, this view will save its attribute data. 775 * 776 * @hide 777 */ 778 public static boolean mDebugViewAttributes = false; 779 780 /** 781 * Used to mark a View that has no ID. 782 */ 783 public static final int NO_ID = -1; 784 785 /** 786 * Signals that compatibility booleans have been initialized according to 787 * target SDK versions. 788 */ 789 private static boolean sCompatibilityDone = false; 790 791 /** 792 * Use the old (broken) way of building MeasureSpecs. 793 */ 794 private static boolean sUseBrokenMakeMeasureSpec = false; 795 796 /** 797 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 798 */ 799 static boolean sUseZeroUnspecifiedMeasureSpec = false; 800 801 /** 802 * Ignore any optimizations using the measure cache. 803 */ 804 private static boolean sIgnoreMeasureCache = false; 805 806 /** 807 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 808 */ 809 private static boolean sAlwaysRemeasureExactly = false; 810 811 /** 812 * Relax constraints around whether setLayoutParams() must be called after 813 * modifying the layout params. 814 */ 815 private static boolean sLayoutParamsAlwaysChanged = false; 816 817 /** 818 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 819 * without throwing 820 */ 821 static boolean sTextureViewIgnoresDrawableSetters = false; 822 823 /** 824 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 825 * calling setFlags. 826 */ 827 private static final int NOT_FOCUSABLE = 0x00000000; 828 829 /** 830 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 831 * setFlags. 832 */ 833 private static final int FOCUSABLE = 0x00000001; 834 835 /** 836 * Mask for use with setFlags indicating bits used for focus. 837 */ 838 private static final int FOCUSABLE_MASK = 0x00000001; 839 840 /** 841 * This view will adjust its padding to fit sytem windows (e.g. status bar) 842 */ 843 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 844 845 /** @hide */ 846 @IntDef({VISIBLE, INVISIBLE, GONE}) 847 @Retention(RetentionPolicy.SOURCE) 848 public @interface Visibility {} 849 850 /** 851 * This view is visible. 852 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 853 * android:visibility}. 854 */ 855 public static final int VISIBLE = 0x00000000; 856 857 /** 858 * This view is invisible, but it still takes up space for layout purposes. 859 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 860 * android:visibility}. 861 */ 862 public static final int INVISIBLE = 0x00000004; 863 864 /** 865 * This view is invisible, and it doesn't take any space for layout 866 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 867 * android:visibility}. 868 */ 869 public static final int GONE = 0x00000008; 870 871 /** 872 * Mask for use with setFlags indicating bits used for visibility. 873 * {@hide} 874 */ 875 static final int VISIBILITY_MASK = 0x0000000C; 876 877 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 878 879 /** 880 * This view is enabled. Interpretation varies by subclass. 881 * Use with ENABLED_MASK when calling setFlags. 882 * {@hide} 883 */ 884 static final int ENABLED = 0x00000000; 885 886 /** 887 * This view is disabled. Interpretation varies by subclass. 888 * Use with ENABLED_MASK when calling setFlags. 889 * {@hide} 890 */ 891 static final int DISABLED = 0x00000020; 892 893 /** 894 * Mask for use with setFlags indicating bits used for indicating whether 895 * this view is enabled 896 * {@hide} 897 */ 898 static final int ENABLED_MASK = 0x00000020; 899 900 /** 901 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 902 * called and further optimizations will be performed. It is okay to have 903 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 904 * {@hide} 905 */ 906 static final int WILL_NOT_DRAW = 0x00000080; 907 908 /** 909 * Mask for use with setFlags indicating bits used for indicating whether 910 * this view is will draw 911 * {@hide} 912 */ 913 static final int DRAW_MASK = 0x00000080; 914 915 /** 916 * <p>This view doesn't show scrollbars.</p> 917 * {@hide} 918 */ 919 static final int SCROLLBARS_NONE = 0x00000000; 920 921 /** 922 * <p>This view shows horizontal scrollbars.</p> 923 * {@hide} 924 */ 925 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 926 927 /** 928 * <p>This view shows vertical scrollbars.</p> 929 * {@hide} 930 */ 931 static final int SCROLLBARS_VERTICAL = 0x00000200; 932 933 /** 934 * <p>Mask for use with setFlags indicating bits used for indicating which 935 * scrollbars are enabled.</p> 936 * {@hide} 937 */ 938 static final int SCROLLBARS_MASK = 0x00000300; 939 940 /** 941 * Indicates that the view should filter touches when its window is obscured. 942 * Refer to the class comments for more information about this security feature. 943 * {@hide} 944 */ 945 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 946 947 /** 948 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 949 * that they are optional and should be skipped if the window has 950 * requested system UI flags that ignore those insets for layout. 951 */ 952 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 953 954 /** 955 * <p>This view doesn't show fading edges.</p> 956 * {@hide} 957 */ 958 static final int FADING_EDGE_NONE = 0x00000000; 959 960 /** 961 * <p>This view shows horizontal fading edges.</p> 962 * {@hide} 963 */ 964 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 965 966 /** 967 * <p>This view shows vertical fading edges.</p> 968 * {@hide} 969 */ 970 static final int FADING_EDGE_VERTICAL = 0x00002000; 971 972 /** 973 * <p>Mask for use with setFlags indicating bits used for indicating which 974 * fading edges are enabled.</p> 975 * {@hide} 976 */ 977 static final int FADING_EDGE_MASK = 0x00003000; 978 979 /** 980 * <p>Indicates this view can be clicked. When clickable, a View reacts 981 * to clicks by notifying the OnClickListener.<p> 982 * {@hide} 983 */ 984 static final int CLICKABLE = 0x00004000; 985 986 /** 987 * <p>Indicates this view is caching its drawing into a bitmap.</p> 988 * {@hide} 989 */ 990 static final int DRAWING_CACHE_ENABLED = 0x00008000; 991 992 /** 993 * <p>Indicates that no icicle should be saved for this view.<p> 994 * {@hide} 995 */ 996 static final int SAVE_DISABLED = 0x000010000; 997 998 /** 999 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 1000 * property.</p> 1001 * {@hide} 1002 */ 1003 static final int SAVE_DISABLED_MASK = 0x000010000; 1004 1005 /** 1006 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1007 * {@hide} 1008 */ 1009 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1010 1011 /** 1012 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1013 * {@hide} 1014 */ 1015 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1016 1017 /** @hide */ 1018 @Retention(RetentionPolicy.SOURCE) 1019 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1020 public @interface DrawingCacheQuality {} 1021 1022 /** 1023 * <p>Enables low quality mode for the drawing cache.</p> 1024 */ 1025 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1026 1027 /** 1028 * <p>Enables high quality mode for the drawing cache.</p> 1029 */ 1030 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1031 1032 /** 1033 * <p>Enables automatic quality mode for the drawing cache.</p> 1034 */ 1035 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1036 1037 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1038 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1039 }; 1040 1041 /** 1042 * <p>Mask for use with setFlags indicating bits used for the cache 1043 * quality property.</p> 1044 * {@hide} 1045 */ 1046 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1047 1048 /** 1049 * <p> 1050 * Indicates this view can be long clicked. When long clickable, a View 1051 * reacts to long clicks by notifying the OnLongClickListener or showing a 1052 * context menu. 1053 * </p> 1054 * {@hide} 1055 */ 1056 static final int LONG_CLICKABLE = 0x00200000; 1057 1058 /** 1059 * <p>Indicates that this view gets its drawable states from its direct parent 1060 * and ignores its original internal states.</p> 1061 * 1062 * @hide 1063 */ 1064 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1065 1066 /** 1067 * <p> 1068 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1069 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1070 * OnContextClickListener. 1071 * </p> 1072 * {@hide} 1073 */ 1074 static final int CONTEXT_CLICKABLE = 0x00800000; 1075 1076 1077 /** @hide */ 1078 @IntDef({ 1079 SCROLLBARS_INSIDE_OVERLAY, 1080 SCROLLBARS_INSIDE_INSET, 1081 SCROLLBARS_OUTSIDE_OVERLAY, 1082 SCROLLBARS_OUTSIDE_INSET 1083 }) 1084 @Retention(RetentionPolicy.SOURCE) 1085 public @interface ScrollBarStyle {} 1086 1087 /** 1088 * The scrollbar style to display the scrollbars inside the content area, 1089 * without increasing the padding. The scrollbars will be overlaid with 1090 * translucency on the view's content. 1091 */ 1092 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1093 1094 /** 1095 * The scrollbar style to display the scrollbars inside the padded area, 1096 * increasing the padding of the view. The scrollbars will not overlap the 1097 * content area of the view. 1098 */ 1099 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1100 1101 /** 1102 * The scrollbar style to display the scrollbars at the edge of the view, 1103 * without increasing the padding. The scrollbars will be overlaid with 1104 * translucency. 1105 */ 1106 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1107 1108 /** 1109 * The scrollbar style to display the scrollbars at the edge of the view, 1110 * increasing the padding of the view. The scrollbars will only overlap the 1111 * background, if any. 1112 */ 1113 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1114 1115 /** 1116 * Mask to check if the scrollbar style is overlay or inset. 1117 * {@hide} 1118 */ 1119 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1120 1121 /** 1122 * Mask to check if the scrollbar style is inside or outside. 1123 * {@hide} 1124 */ 1125 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1126 1127 /** 1128 * Mask for scrollbar style. 1129 * {@hide} 1130 */ 1131 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1132 1133 /** 1134 * View flag indicating that the screen should remain on while the 1135 * window containing this view is visible to the user. This effectively 1136 * takes care of automatically setting the WindowManager's 1137 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1138 */ 1139 public static final int KEEP_SCREEN_ON = 0x04000000; 1140 1141 /** 1142 * View flag indicating whether this view should have sound effects enabled 1143 * for events such as clicking and touching. 1144 */ 1145 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1146 1147 /** 1148 * View flag indicating whether this view should have haptic feedback 1149 * enabled for events such as long presses. 1150 */ 1151 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1152 1153 /** 1154 * <p>Indicates that the view hierarchy should stop saving state when 1155 * it reaches this view. If state saving is initiated immediately at 1156 * the view, it will be allowed. 1157 * {@hide} 1158 */ 1159 static final int PARENT_SAVE_DISABLED = 0x20000000; 1160 1161 /** 1162 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1163 * {@hide} 1164 */ 1165 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1166 1167 /** @hide */ 1168 @IntDef(flag = true, 1169 value = { 1170 FOCUSABLES_ALL, 1171 FOCUSABLES_TOUCH_MODE 1172 }) 1173 @Retention(RetentionPolicy.SOURCE) 1174 public @interface FocusableMode {} 1175 1176 /** 1177 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1178 * should add all focusable Views regardless if they are focusable in touch mode. 1179 */ 1180 public static final int FOCUSABLES_ALL = 0x00000000; 1181 1182 /** 1183 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1184 * should add only Views focusable in touch mode. 1185 */ 1186 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1187 1188 /** @hide */ 1189 @IntDef({ 1190 FOCUS_BACKWARD, 1191 FOCUS_FORWARD, 1192 FOCUS_LEFT, 1193 FOCUS_UP, 1194 FOCUS_RIGHT, 1195 FOCUS_DOWN 1196 }) 1197 @Retention(RetentionPolicy.SOURCE) 1198 public @interface FocusDirection {} 1199 1200 /** @hide */ 1201 @IntDef({ 1202 FOCUS_LEFT, 1203 FOCUS_UP, 1204 FOCUS_RIGHT, 1205 FOCUS_DOWN 1206 }) 1207 @Retention(RetentionPolicy.SOURCE) 1208 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1209 1210 /** 1211 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1212 * item. 1213 */ 1214 public static final int FOCUS_BACKWARD = 0x00000001; 1215 1216 /** 1217 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1218 * item. 1219 */ 1220 public static final int FOCUS_FORWARD = 0x00000002; 1221 1222 /** 1223 * Use with {@link #focusSearch(int)}. Move focus to the left. 1224 */ 1225 public static final int FOCUS_LEFT = 0x00000011; 1226 1227 /** 1228 * Use with {@link #focusSearch(int)}. Move focus up. 1229 */ 1230 public static final int FOCUS_UP = 0x00000021; 1231 1232 /** 1233 * Use with {@link #focusSearch(int)}. Move focus to the right. 1234 */ 1235 public static final int FOCUS_RIGHT = 0x00000042; 1236 1237 /** 1238 * Use with {@link #focusSearch(int)}. Move focus down. 1239 */ 1240 public static final int FOCUS_DOWN = 0x00000082; 1241 1242 /** 1243 * Bits of {@link #getMeasuredWidthAndState()} and 1244 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1245 */ 1246 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1247 1248 /** 1249 * Bits of {@link #getMeasuredWidthAndState()} and 1250 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1251 */ 1252 public static final int MEASURED_STATE_MASK = 0xff000000; 1253 1254 /** 1255 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1256 * for functions that combine both width and height into a single int, 1257 * such as {@link #getMeasuredState()} and the childState argument of 1258 * {@link #resolveSizeAndState(int, int, int)}. 1259 */ 1260 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1261 1262 /** 1263 * Bit of {@link #getMeasuredWidthAndState()} and 1264 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1265 * is smaller that the space the view would like to have. 1266 */ 1267 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1268 1269 /** 1270 * Base View state sets 1271 */ 1272 // Singles 1273 /** 1274 * Indicates the view has no states set. States are used with 1275 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1276 * view depending on its state. 1277 * 1278 * @see android.graphics.drawable.Drawable 1279 * @see #getDrawableState() 1280 */ 1281 protected static final int[] EMPTY_STATE_SET; 1282 /** 1283 * Indicates the view is enabled. States are used with 1284 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1285 * view depending on its state. 1286 * 1287 * @see android.graphics.drawable.Drawable 1288 * @see #getDrawableState() 1289 */ 1290 protected static final int[] ENABLED_STATE_SET; 1291 /** 1292 * Indicates the view is focused. States are used with 1293 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1294 * view depending on its state. 1295 * 1296 * @see android.graphics.drawable.Drawable 1297 * @see #getDrawableState() 1298 */ 1299 protected static final int[] FOCUSED_STATE_SET; 1300 /** 1301 * Indicates the view is selected. States are used with 1302 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1303 * view depending on its state. 1304 * 1305 * @see android.graphics.drawable.Drawable 1306 * @see #getDrawableState() 1307 */ 1308 protected static final int[] SELECTED_STATE_SET; 1309 /** 1310 * Indicates the view is pressed. States are used with 1311 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1312 * view depending on its state. 1313 * 1314 * @see android.graphics.drawable.Drawable 1315 * @see #getDrawableState() 1316 */ 1317 protected static final int[] PRESSED_STATE_SET; 1318 /** 1319 * Indicates the view's window has focus. States are used with 1320 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1321 * view depending on its state. 1322 * 1323 * @see android.graphics.drawable.Drawable 1324 * @see #getDrawableState() 1325 */ 1326 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1327 // Doubles 1328 /** 1329 * Indicates the view is enabled and has the focus. 1330 * 1331 * @see #ENABLED_STATE_SET 1332 * @see #FOCUSED_STATE_SET 1333 */ 1334 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1335 /** 1336 * Indicates the view is enabled and selected. 1337 * 1338 * @see #ENABLED_STATE_SET 1339 * @see #SELECTED_STATE_SET 1340 */ 1341 protected static final int[] ENABLED_SELECTED_STATE_SET; 1342 /** 1343 * Indicates the view is enabled and that its window has focus. 1344 * 1345 * @see #ENABLED_STATE_SET 1346 * @see #WINDOW_FOCUSED_STATE_SET 1347 */ 1348 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1349 /** 1350 * Indicates the view is focused and selected. 1351 * 1352 * @see #FOCUSED_STATE_SET 1353 * @see #SELECTED_STATE_SET 1354 */ 1355 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1356 /** 1357 * Indicates the view has the focus and that its window has the focus. 1358 * 1359 * @see #FOCUSED_STATE_SET 1360 * @see #WINDOW_FOCUSED_STATE_SET 1361 */ 1362 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1363 /** 1364 * Indicates the view is selected and that its window has the focus. 1365 * 1366 * @see #SELECTED_STATE_SET 1367 * @see #WINDOW_FOCUSED_STATE_SET 1368 */ 1369 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1370 // Triples 1371 /** 1372 * Indicates the view is enabled, focused and selected. 1373 * 1374 * @see #ENABLED_STATE_SET 1375 * @see #FOCUSED_STATE_SET 1376 * @see #SELECTED_STATE_SET 1377 */ 1378 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1379 /** 1380 * Indicates the view is enabled, focused and its window has the focus. 1381 * 1382 * @see #ENABLED_STATE_SET 1383 * @see #FOCUSED_STATE_SET 1384 * @see #WINDOW_FOCUSED_STATE_SET 1385 */ 1386 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1387 /** 1388 * Indicates the view is enabled, selected and its window has the focus. 1389 * 1390 * @see #ENABLED_STATE_SET 1391 * @see #SELECTED_STATE_SET 1392 * @see #WINDOW_FOCUSED_STATE_SET 1393 */ 1394 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1395 /** 1396 * Indicates the view is focused, selected and its window has the focus. 1397 * 1398 * @see #FOCUSED_STATE_SET 1399 * @see #SELECTED_STATE_SET 1400 * @see #WINDOW_FOCUSED_STATE_SET 1401 */ 1402 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1403 /** 1404 * Indicates the view is enabled, focused, selected and its window 1405 * has the focus. 1406 * 1407 * @see #ENABLED_STATE_SET 1408 * @see #FOCUSED_STATE_SET 1409 * @see #SELECTED_STATE_SET 1410 * @see #WINDOW_FOCUSED_STATE_SET 1411 */ 1412 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1413 /** 1414 * Indicates the view is pressed and its window has the focus. 1415 * 1416 * @see #PRESSED_STATE_SET 1417 * @see #WINDOW_FOCUSED_STATE_SET 1418 */ 1419 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1420 /** 1421 * Indicates the view is pressed and selected. 1422 * 1423 * @see #PRESSED_STATE_SET 1424 * @see #SELECTED_STATE_SET 1425 */ 1426 protected static final int[] PRESSED_SELECTED_STATE_SET; 1427 /** 1428 * Indicates the view is pressed, selected and its window has the focus. 1429 * 1430 * @see #PRESSED_STATE_SET 1431 * @see #SELECTED_STATE_SET 1432 * @see #WINDOW_FOCUSED_STATE_SET 1433 */ 1434 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1435 /** 1436 * Indicates the view is pressed and focused. 1437 * 1438 * @see #PRESSED_STATE_SET 1439 * @see #FOCUSED_STATE_SET 1440 */ 1441 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1442 /** 1443 * Indicates the view is pressed, focused and its window has the focus. 1444 * 1445 * @see #PRESSED_STATE_SET 1446 * @see #FOCUSED_STATE_SET 1447 * @see #WINDOW_FOCUSED_STATE_SET 1448 */ 1449 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1450 /** 1451 * Indicates the view is pressed, focused and selected. 1452 * 1453 * @see #PRESSED_STATE_SET 1454 * @see #SELECTED_STATE_SET 1455 * @see #FOCUSED_STATE_SET 1456 */ 1457 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1458 /** 1459 * Indicates the view is pressed, focused, selected and its window has the focus. 1460 * 1461 * @see #PRESSED_STATE_SET 1462 * @see #FOCUSED_STATE_SET 1463 * @see #SELECTED_STATE_SET 1464 * @see #WINDOW_FOCUSED_STATE_SET 1465 */ 1466 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1467 /** 1468 * Indicates the view is pressed and enabled. 1469 * 1470 * @see #PRESSED_STATE_SET 1471 * @see #ENABLED_STATE_SET 1472 */ 1473 protected static final int[] PRESSED_ENABLED_STATE_SET; 1474 /** 1475 * Indicates the view is pressed, enabled and its window has the focus. 1476 * 1477 * @see #PRESSED_STATE_SET 1478 * @see #ENABLED_STATE_SET 1479 * @see #WINDOW_FOCUSED_STATE_SET 1480 */ 1481 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1482 /** 1483 * Indicates the view is pressed, enabled and selected. 1484 * 1485 * @see #PRESSED_STATE_SET 1486 * @see #ENABLED_STATE_SET 1487 * @see #SELECTED_STATE_SET 1488 */ 1489 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1490 /** 1491 * Indicates the view is pressed, enabled, selected and its window has the 1492 * focus. 1493 * 1494 * @see #PRESSED_STATE_SET 1495 * @see #ENABLED_STATE_SET 1496 * @see #SELECTED_STATE_SET 1497 * @see #WINDOW_FOCUSED_STATE_SET 1498 */ 1499 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1500 /** 1501 * Indicates the view is pressed, enabled and focused. 1502 * 1503 * @see #PRESSED_STATE_SET 1504 * @see #ENABLED_STATE_SET 1505 * @see #FOCUSED_STATE_SET 1506 */ 1507 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1508 /** 1509 * Indicates the view is pressed, enabled, focused and its window has the 1510 * focus. 1511 * 1512 * @see #PRESSED_STATE_SET 1513 * @see #ENABLED_STATE_SET 1514 * @see #FOCUSED_STATE_SET 1515 * @see #WINDOW_FOCUSED_STATE_SET 1516 */ 1517 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1518 /** 1519 * Indicates the view is pressed, enabled, focused and selected. 1520 * 1521 * @see #PRESSED_STATE_SET 1522 * @see #ENABLED_STATE_SET 1523 * @see #SELECTED_STATE_SET 1524 * @see #FOCUSED_STATE_SET 1525 */ 1526 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1527 /** 1528 * Indicates the view is pressed, enabled, focused, selected and its window 1529 * has the focus. 1530 * 1531 * @see #PRESSED_STATE_SET 1532 * @see #ENABLED_STATE_SET 1533 * @see #SELECTED_STATE_SET 1534 * @see #FOCUSED_STATE_SET 1535 * @see #WINDOW_FOCUSED_STATE_SET 1536 */ 1537 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1538 1539 static { 1540 EMPTY_STATE_SET = StateSet.get(0); 1541 1542 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1543 1544 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1545 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1546 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1547 1548 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1549 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1550 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1551 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1552 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1553 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1554 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1555 | StateSet.VIEW_STATE_FOCUSED); 1556 1557 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1558 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1559 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1560 ENABLED_SELECTED_STATE_SET = StateSet.get( 1561 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1562 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1563 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1564 | StateSet.VIEW_STATE_ENABLED); 1565 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1566 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1567 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1568 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1569 | StateSet.VIEW_STATE_ENABLED); 1570 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1571 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1572 | StateSet.VIEW_STATE_ENABLED); 1573 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1574 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1575 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1576 1577 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1578 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1579 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1580 PRESSED_SELECTED_STATE_SET = StateSet.get( 1581 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1582 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1583 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1584 | StateSet.VIEW_STATE_PRESSED); 1585 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1586 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1587 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1588 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1589 | StateSet.VIEW_STATE_PRESSED); 1590 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1591 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1592 | StateSet.VIEW_STATE_PRESSED); 1593 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1594 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1595 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1596 PRESSED_ENABLED_STATE_SET = StateSet.get( 1597 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1598 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1599 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1600 | StateSet.VIEW_STATE_PRESSED); 1601 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1602 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1603 | StateSet.VIEW_STATE_PRESSED); 1604 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1605 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1606 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1607 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1608 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1609 | StateSet.VIEW_STATE_PRESSED); 1610 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1611 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1612 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1613 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1614 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1615 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1616 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1617 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1618 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1619 | StateSet.VIEW_STATE_PRESSED); 1620 } 1621 1622 /** 1623 * Accessibility event types that are dispatched for text population. 1624 */ 1625 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1626 AccessibilityEvent.TYPE_VIEW_CLICKED 1627 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1628 | AccessibilityEvent.TYPE_VIEW_SELECTED 1629 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1630 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1631 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1632 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1633 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1634 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1635 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1636 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1637 1638 /** 1639 * Temporary Rect currently for use in setBackground(). This will probably 1640 * be extended in the future to hold our own class with more than just 1641 * a Rect. :) 1642 */ 1643 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1644 1645 /** 1646 * Map used to store views' tags. 1647 */ 1648 private SparseArray<Object> mKeyedTags; 1649 1650 /** 1651 * The next available accessibility id. 1652 */ 1653 private static int sNextAccessibilityViewId; 1654 1655 /** 1656 * The animation currently associated with this view. 1657 * @hide 1658 */ 1659 protected Animation mCurrentAnimation = null; 1660 1661 /** 1662 * Width as measured during measure pass. 1663 * {@hide} 1664 */ 1665 @ViewDebug.ExportedProperty(category = "measurement") 1666 int mMeasuredWidth; 1667 1668 /** 1669 * Height as measured during measure pass. 1670 * {@hide} 1671 */ 1672 @ViewDebug.ExportedProperty(category = "measurement") 1673 int mMeasuredHeight; 1674 1675 /** 1676 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1677 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1678 * its display list. This flag, used only when hw accelerated, allows us to clear the 1679 * flag while retaining this information until it's needed (at getDisplayList() time and 1680 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1681 * 1682 * {@hide} 1683 */ 1684 boolean mRecreateDisplayList = false; 1685 1686 /** 1687 * The view's identifier. 1688 * {@hide} 1689 * 1690 * @see #setId(int) 1691 * @see #getId() 1692 */ 1693 @IdRes 1694 @ViewDebug.ExportedProperty(resolveId = true) 1695 int mID = NO_ID; 1696 1697 /** 1698 * The stable ID of this view for accessibility purposes. 1699 */ 1700 int mAccessibilityViewId = NO_ID; 1701 1702 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1703 1704 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1705 1706 /** 1707 * The view's tag. 1708 * {@hide} 1709 * 1710 * @see #setTag(Object) 1711 * @see #getTag() 1712 */ 1713 protected Object mTag = null; 1714 1715 // for mPrivateFlags: 1716 /** {@hide} */ 1717 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1718 /** {@hide} */ 1719 static final int PFLAG_FOCUSED = 0x00000002; 1720 /** {@hide} */ 1721 static final int PFLAG_SELECTED = 0x00000004; 1722 /** {@hide} */ 1723 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1724 /** {@hide} */ 1725 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1726 /** {@hide} */ 1727 static final int PFLAG_DRAWN = 0x00000020; 1728 /** 1729 * When this flag is set, this view is running an animation on behalf of its 1730 * children and should therefore not cancel invalidate requests, even if they 1731 * lie outside of this view's bounds. 1732 * 1733 * {@hide} 1734 */ 1735 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1736 /** {@hide} */ 1737 static final int PFLAG_SKIP_DRAW = 0x00000080; 1738 /** {@hide} */ 1739 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1740 /** {@hide} */ 1741 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1742 /** {@hide} */ 1743 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1744 /** {@hide} */ 1745 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1746 /** {@hide} */ 1747 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1748 1749 private static final int PFLAG_PRESSED = 0x00004000; 1750 1751 /** {@hide} */ 1752 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1753 /** 1754 * Flag used to indicate that this view should be drawn once more (and only once 1755 * more) after its animation has completed. 1756 * {@hide} 1757 */ 1758 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1759 1760 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1761 1762 /** 1763 * Indicates that the View returned true when onSetAlpha() was called and that 1764 * the alpha must be restored. 1765 * {@hide} 1766 */ 1767 static final int PFLAG_ALPHA_SET = 0x00040000; 1768 1769 /** 1770 * Set by {@link #setScrollContainer(boolean)}. 1771 */ 1772 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1773 1774 /** 1775 * Set by {@link #setScrollContainer(boolean)}. 1776 */ 1777 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1778 1779 /** 1780 * View flag indicating whether this view was invalidated (fully or partially.) 1781 * 1782 * @hide 1783 */ 1784 static final int PFLAG_DIRTY = 0x00200000; 1785 1786 /** 1787 * View flag indicating whether this view was invalidated by an opaque 1788 * invalidate request. 1789 * 1790 * @hide 1791 */ 1792 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1793 1794 /** 1795 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1796 * 1797 * @hide 1798 */ 1799 static final int PFLAG_DIRTY_MASK = 0x00600000; 1800 1801 /** 1802 * Indicates whether the background is opaque. 1803 * 1804 * @hide 1805 */ 1806 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1807 1808 /** 1809 * Indicates whether the scrollbars are opaque. 1810 * 1811 * @hide 1812 */ 1813 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1814 1815 /** 1816 * Indicates whether the view is opaque. 1817 * 1818 * @hide 1819 */ 1820 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1821 1822 /** 1823 * Indicates a prepressed state; 1824 * the short time between ACTION_DOWN and recognizing 1825 * a 'real' press. Prepressed is used to recognize quick taps 1826 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1827 * 1828 * @hide 1829 */ 1830 private static final int PFLAG_PREPRESSED = 0x02000000; 1831 1832 /** 1833 * Indicates whether the view is temporarily detached. 1834 * 1835 * @hide 1836 */ 1837 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1838 1839 /** 1840 * Indicates that we should awaken scroll bars once attached 1841 * 1842 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 1843 * during window attachment and it is no longer needed. Feel free to repurpose it. 1844 * 1845 * @hide 1846 */ 1847 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1848 1849 /** 1850 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1851 * @hide 1852 */ 1853 private static final int PFLAG_HOVERED = 0x10000000; 1854 1855 /** 1856 * no longer needed, should be reused 1857 */ 1858 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1859 1860 /** {@hide} */ 1861 static final int PFLAG_ACTIVATED = 0x40000000; 1862 1863 /** 1864 * Indicates that this view was specifically invalidated, not just dirtied because some 1865 * child view was invalidated. The flag is used to determine when we need to recreate 1866 * a view's display list (as opposed to just returning a reference to its existing 1867 * display list). 1868 * 1869 * @hide 1870 */ 1871 static final int PFLAG_INVALIDATED = 0x80000000; 1872 1873 /** 1874 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1875 * 1876 * |-------|-------|-------|-------| 1877 * 1 PFLAG2_DRAG_CAN_ACCEPT 1878 * 1 PFLAG2_DRAG_HOVERED 1879 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1880 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1881 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1882 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1883 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1884 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1885 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1886 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1887 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1888 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 1889 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 1890 * 111 PFLAG2_TEXT_DIRECTION_MASK 1891 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1892 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1893 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1894 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1895 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1896 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1897 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1898 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1899 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1900 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1901 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1902 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1903 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1904 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1905 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1906 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1907 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1908 * 1 PFLAG2_VIEW_QUICK_REJECTED 1909 * 1 PFLAG2_PADDING_RESOLVED 1910 * 1 PFLAG2_DRAWABLE_RESOLVED 1911 * 1 PFLAG2_HAS_TRANSIENT_STATE 1912 * |-------|-------|-------|-------| 1913 */ 1914 1915 /** 1916 * Indicates that this view has reported that it can accept the current drag's content. 1917 * Cleared when the drag operation concludes. 1918 * @hide 1919 */ 1920 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1921 1922 /** 1923 * Indicates that this view is currently directly under the drag location in a 1924 * drag-and-drop operation involving content that it can accept. Cleared when 1925 * the drag exits the view, or when the drag operation concludes. 1926 * @hide 1927 */ 1928 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1929 1930 /** @hide */ 1931 @IntDef({ 1932 LAYOUT_DIRECTION_LTR, 1933 LAYOUT_DIRECTION_RTL, 1934 LAYOUT_DIRECTION_INHERIT, 1935 LAYOUT_DIRECTION_LOCALE 1936 }) 1937 @Retention(RetentionPolicy.SOURCE) 1938 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1939 public @interface LayoutDir {} 1940 1941 /** @hide */ 1942 @IntDef({ 1943 LAYOUT_DIRECTION_LTR, 1944 LAYOUT_DIRECTION_RTL 1945 }) 1946 @Retention(RetentionPolicy.SOURCE) 1947 public @interface ResolvedLayoutDir {} 1948 1949 /** 1950 * A flag to indicate that the layout direction of this view has not been defined yet. 1951 * @hide 1952 */ 1953 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 1954 1955 /** 1956 * Horizontal layout direction of this view is from Left to Right. 1957 * Use with {@link #setLayoutDirection}. 1958 */ 1959 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1960 1961 /** 1962 * Horizontal layout direction of this view is from Right to Left. 1963 * Use with {@link #setLayoutDirection}. 1964 */ 1965 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1966 1967 /** 1968 * Horizontal layout direction of this view is inherited from its parent. 1969 * Use with {@link #setLayoutDirection}. 1970 */ 1971 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1972 1973 /** 1974 * Horizontal layout direction of this view is from deduced from the default language 1975 * script for the locale. Use with {@link #setLayoutDirection}. 1976 */ 1977 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1978 1979 /** 1980 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1981 * @hide 1982 */ 1983 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1984 1985 /** 1986 * Mask for use with private flags indicating bits used for horizontal layout direction. 1987 * @hide 1988 */ 1989 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1990 1991 /** 1992 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1993 * right-to-left direction. 1994 * @hide 1995 */ 1996 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1997 1998 /** 1999 * Indicates whether the view horizontal layout direction has been resolved. 2000 * @hide 2001 */ 2002 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2003 2004 /** 2005 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2006 * @hide 2007 */ 2008 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2009 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2010 2011 /* 2012 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2013 * flag value. 2014 * @hide 2015 */ 2016 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2017 LAYOUT_DIRECTION_LTR, 2018 LAYOUT_DIRECTION_RTL, 2019 LAYOUT_DIRECTION_INHERIT, 2020 LAYOUT_DIRECTION_LOCALE 2021 }; 2022 2023 /** 2024 * Default horizontal layout direction. 2025 */ 2026 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2027 2028 /** 2029 * Default horizontal layout direction. 2030 * @hide 2031 */ 2032 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2033 2034 /** 2035 * Text direction is inherited through {@link ViewGroup} 2036 */ 2037 public static final int TEXT_DIRECTION_INHERIT = 0; 2038 2039 /** 2040 * Text direction is using "first strong algorithm". The first strong directional character 2041 * determines the paragraph direction. If there is no strong directional character, the 2042 * paragraph direction is the view's resolved layout direction. 2043 */ 2044 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2045 2046 /** 2047 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2048 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2049 * If there are neither, the paragraph direction is the view's resolved layout direction. 2050 */ 2051 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2052 2053 /** 2054 * Text direction is forced to LTR. 2055 */ 2056 public static final int TEXT_DIRECTION_LTR = 3; 2057 2058 /** 2059 * Text direction is forced to RTL. 2060 */ 2061 public static final int TEXT_DIRECTION_RTL = 4; 2062 2063 /** 2064 * Text direction is coming from the system Locale. 2065 */ 2066 public static final int TEXT_DIRECTION_LOCALE = 5; 2067 2068 /** 2069 * Text direction is using "first strong algorithm". The first strong directional character 2070 * determines the paragraph direction. If there is no strong directional character, the 2071 * paragraph direction is LTR. 2072 */ 2073 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2074 2075 /** 2076 * Text direction is using "first strong algorithm". The first strong directional character 2077 * determines the paragraph direction. If there is no strong directional character, the 2078 * paragraph direction is RTL. 2079 */ 2080 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2081 2082 /** 2083 * Default text direction is inherited 2084 */ 2085 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2086 2087 /** 2088 * Default resolved text direction 2089 * @hide 2090 */ 2091 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2092 2093 /** 2094 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2095 * @hide 2096 */ 2097 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2098 2099 /** 2100 * Mask for use with private flags indicating bits used for text direction. 2101 * @hide 2102 */ 2103 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2104 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2105 2106 /** 2107 * Array of text direction flags for mapping attribute "textDirection" to correct 2108 * flag value. 2109 * @hide 2110 */ 2111 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2112 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2113 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2114 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2115 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2116 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2117 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2118 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2119 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2120 }; 2121 2122 /** 2123 * Indicates whether the view text direction has been resolved. 2124 * @hide 2125 */ 2126 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2127 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2128 2129 /** 2130 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2131 * @hide 2132 */ 2133 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2134 2135 /** 2136 * Mask for use with private flags indicating bits used for resolved text direction. 2137 * @hide 2138 */ 2139 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2140 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2141 2142 /** 2143 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2144 * @hide 2145 */ 2146 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2147 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2148 2149 /** @hide */ 2150 @IntDef({ 2151 TEXT_ALIGNMENT_INHERIT, 2152 TEXT_ALIGNMENT_GRAVITY, 2153 TEXT_ALIGNMENT_CENTER, 2154 TEXT_ALIGNMENT_TEXT_START, 2155 TEXT_ALIGNMENT_TEXT_END, 2156 TEXT_ALIGNMENT_VIEW_START, 2157 TEXT_ALIGNMENT_VIEW_END 2158 }) 2159 @Retention(RetentionPolicy.SOURCE) 2160 public @interface TextAlignment {} 2161 2162 /** 2163 * Default text alignment. The text alignment of this View is inherited from its parent. 2164 * Use with {@link #setTextAlignment(int)} 2165 */ 2166 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2167 2168 /** 2169 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2170 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2171 * 2172 * Use with {@link #setTextAlignment(int)} 2173 */ 2174 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2175 2176 /** 2177 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2178 * 2179 * Use with {@link #setTextAlignment(int)} 2180 */ 2181 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2182 2183 /** 2184 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2185 * 2186 * Use with {@link #setTextAlignment(int)} 2187 */ 2188 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2189 2190 /** 2191 * Center the paragraph, e.g. ALIGN_CENTER. 2192 * 2193 * Use with {@link #setTextAlignment(int)} 2194 */ 2195 public static final int TEXT_ALIGNMENT_CENTER = 4; 2196 2197 /** 2198 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2199 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2200 * 2201 * Use with {@link #setTextAlignment(int)} 2202 */ 2203 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2204 2205 /** 2206 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2207 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2208 * 2209 * Use with {@link #setTextAlignment(int)} 2210 */ 2211 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2212 2213 /** 2214 * Default text alignment is inherited 2215 */ 2216 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2217 2218 /** 2219 * Default resolved text alignment 2220 * @hide 2221 */ 2222 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2223 2224 /** 2225 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2226 * @hide 2227 */ 2228 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2229 2230 /** 2231 * Mask for use with private flags indicating bits used for text alignment. 2232 * @hide 2233 */ 2234 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2235 2236 /** 2237 * Array of text direction flags for mapping attribute "textAlignment" to correct 2238 * flag value. 2239 * @hide 2240 */ 2241 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2242 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2243 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2244 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2245 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2246 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2247 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2248 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2249 }; 2250 2251 /** 2252 * Indicates whether the view text alignment has been resolved. 2253 * @hide 2254 */ 2255 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2256 2257 /** 2258 * Bit shift to get the resolved text alignment. 2259 * @hide 2260 */ 2261 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2262 2263 /** 2264 * Mask for use with private flags indicating bits used for text alignment. 2265 * @hide 2266 */ 2267 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2268 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2269 2270 /** 2271 * Indicates whether if the view text alignment has been resolved to gravity 2272 */ 2273 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2274 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2275 2276 // Accessiblity constants for mPrivateFlags2 2277 2278 /** 2279 * Shift for the bits in {@link #mPrivateFlags2} related to the 2280 * "importantForAccessibility" attribute. 2281 */ 2282 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2283 2284 /** 2285 * Automatically determine whether a view is important for accessibility. 2286 */ 2287 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2288 2289 /** 2290 * The view is important for accessibility. 2291 */ 2292 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2293 2294 /** 2295 * The view is not important for accessibility. 2296 */ 2297 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2298 2299 /** 2300 * The view is not important for accessibility, nor are any of its 2301 * descendant views. 2302 */ 2303 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2304 2305 /** 2306 * The default whether the view is important for accessibility. 2307 */ 2308 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2309 2310 /** 2311 * Mask for obtainig the bits which specify how to determine 2312 * whether a view is important for accessibility. 2313 */ 2314 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2315 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2316 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2317 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2318 2319 /** 2320 * Shift for the bits in {@link #mPrivateFlags2} related to the 2321 * "accessibilityLiveRegion" attribute. 2322 */ 2323 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2324 2325 /** 2326 * Live region mode specifying that accessibility services should not 2327 * automatically announce changes to this view. This is the default live 2328 * region mode for most views. 2329 * <p> 2330 * Use with {@link #setAccessibilityLiveRegion(int)}. 2331 */ 2332 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2333 2334 /** 2335 * Live region mode specifying that accessibility services should announce 2336 * changes to this view. 2337 * <p> 2338 * Use with {@link #setAccessibilityLiveRegion(int)}. 2339 */ 2340 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2341 2342 /** 2343 * Live region mode specifying that accessibility services should interrupt 2344 * ongoing speech to immediately announce changes to this view. 2345 * <p> 2346 * Use with {@link #setAccessibilityLiveRegion(int)}. 2347 */ 2348 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2349 2350 /** 2351 * The default whether the view is important for accessibility. 2352 */ 2353 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2354 2355 /** 2356 * Mask for obtaining the bits which specify a view's accessibility live 2357 * region mode. 2358 */ 2359 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2360 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2361 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2362 2363 /** 2364 * Flag indicating whether a view has accessibility focus. 2365 */ 2366 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2367 2368 /** 2369 * Flag whether the accessibility state of the subtree rooted at this view changed. 2370 */ 2371 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2372 2373 /** 2374 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2375 * is used to check whether later changes to the view's transform should invalidate the 2376 * view to force the quickReject test to run again. 2377 */ 2378 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2379 2380 /** 2381 * Flag indicating that start/end padding has been resolved into left/right padding 2382 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2383 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2384 * during measurement. In some special cases this is required such as when an adapter-based 2385 * view measures prospective children without attaching them to a window. 2386 */ 2387 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2388 2389 /** 2390 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2391 */ 2392 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2393 2394 /** 2395 * Indicates that the view is tracking some sort of transient state 2396 * that the app should not need to be aware of, but that the framework 2397 * should take special care to preserve. 2398 */ 2399 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2400 2401 /** 2402 * Group of bits indicating that RTL properties resolution is done. 2403 */ 2404 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2405 PFLAG2_TEXT_DIRECTION_RESOLVED | 2406 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2407 PFLAG2_PADDING_RESOLVED | 2408 PFLAG2_DRAWABLE_RESOLVED; 2409 2410 // There are a couple of flags left in mPrivateFlags2 2411 2412 /* End of masks for mPrivateFlags2 */ 2413 2414 /** 2415 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2416 * 2417 * |-------|-------|-------|-------| 2418 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2419 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2420 * 1 PFLAG3_IS_LAID_OUT 2421 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2422 * 1 PFLAG3_CALLED_SUPER 2423 * 1 PFLAG3_APPLYING_INSETS 2424 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2425 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2426 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2427 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2428 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2429 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2430 * 1 PFLAG3_SCROLL_INDICATOR_START 2431 * 1 PFLAG3_SCROLL_INDICATOR_END 2432 * 1 PFLAG3_ASSIST_BLOCKED 2433 * 1111111 PFLAG3_POINTER_ICON_MASK 2434 * |-------|-------|-------|-------| 2435 */ 2436 2437 /** 2438 * Flag indicating that view has a transform animation set on it. This is used to track whether 2439 * an animation is cleared between successive frames, in order to tell the associated 2440 * DisplayList to clear its animation matrix. 2441 */ 2442 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2443 2444 /** 2445 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2446 * animation is cleared between successive frames, in order to tell the associated 2447 * DisplayList to restore its alpha value. 2448 */ 2449 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2450 2451 /** 2452 * Flag indicating that the view has been through at least one layout since it 2453 * was last attached to a window. 2454 */ 2455 static final int PFLAG3_IS_LAID_OUT = 0x4; 2456 2457 /** 2458 * Flag indicating that a call to measure() was skipped and should be done 2459 * instead when layout() is invoked. 2460 */ 2461 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2462 2463 /** 2464 * Flag indicating that an overridden method correctly called down to 2465 * the superclass implementation as required by the API spec. 2466 */ 2467 static final int PFLAG3_CALLED_SUPER = 0x10; 2468 2469 /** 2470 * Flag indicating that we're in the process of applying window insets. 2471 */ 2472 static final int PFLAG3_APPLYING_INSETS = 0x20; 2473 2474 /** 2475 * Flag indicating that we're in the process of fitting system windows using the old method. 2476 */ 2477 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2478 2479 /** 2480 * Flag indicating that nested scrolling is enabled for this view. 2481 * The view will optionally cooperate with views up its parent chain to allow for 2482 * integrated nested scrolling along the same axis. 2483 */ 2484 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2485 2486 /** 2487 * Flag indicating that the bottom scroll indicator should be displayed 2488 * when this view can scroll up. 2489 */ 2490 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2491 2492 /** 2493 * Flag indicating that the bottom scroll indicator should be displayed 2494 * when this view can scroll down. 2495 */ 2496 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2497 2498 /** 2499 * Flag indicating that the left scroll indicator should be displayed 2500 * when this view can scroll left. 2501 */ 2502 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2503 2504 /** 2505 * Flag indicating that the right scroll indicator should be displayed 2506 * when this view can scroll right. 2507 */ 2508 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2509 2510 /** 2511 * Flag indicating that the start scroll indicator should be displayed 2512 * when this view can scroll in the start direction. 2513 */ 2514 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2515 2516 /** 2517 * Flag indicating that the end scroll indicator should be displayed 2518 * when this view can scroll in the end direction. 2519 */ 2520 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2521 2522 /* End of masks for mPrivateFlags3 */ 2523 2524 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2525 2526 static final int SCROLL_INDICATORS_NONE = 0x0000; 2527 2528 /** 2529 * Mask for use with setFlags indicating bits used for indicating which 2530 * scroll indicators are enabled. 2531 */ 2532 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2533 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2534 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2535 | PFLAG3_SCROLL_INDICATOR_END; 2536 2537 /** 2538 * Left-shift required to translate between public scroll indicator flags 2539 * and internal PFLAGS3 flags. When used as a right-shift, translates 2540 * PFLAGS3 flags to public flags. 2541 */ 2542 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2543 2544 /** @hide */ 2545 @Retention(RetentionPolicy.SOURCE) 2546 @IntDef(flag = true, 2547 value = { 2548 SCROLL_INDICATOR_TOP, 2549 SCROLL_INDICATOR_BOTTOM, 2550 SCROLL_INDICATOR_LEFT, 2551 SCROLL_INDICATOR_RIGHT, 2552 SCROLL_INDICATOR_START, 2553 SCROLL_INDICATOR_END, 2554 }) 2555 public @interface ScrollIndicators {} 2556 2557 /** 2558 * Scroll indicator direction for the top edge of the view. 2559 * 2560 * @see #setScrollIndicators(int) 2561 * @see #setScrollIndicators(int, int) 2562 * @see #getScrollIndicators() 2563 */ 2564 public static final int SCROLL_INDICATOR_TOP = 2565 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2566 2567 /** 2568 * Scroll indicator direction for the bottom edge of the view. 2569 * 2570 * @see #setScrollIndicators(int) 2571 * @see #setScrollIndicators(int, int) 2572 * @see #getScrollIndicators() 2573 */ 2574 public static final int SCROLL_INDICATOR_BOTTOM = 2575 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2576 2577 /** 2578 * Scroll indicator direction for the left edge of the view. 2579 * 2580 * @see #setScrollIndicators(int) 2581 * @see #setScrollIndicators(int, int) 2582 * @see #getScrollIndicators() 2583 */ 2584 public static final int SCROLL_INDICATOR_LEFT = 2585 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2586 2587 /** 2588 * Scroll indicator direction for the right edge of the view. 2589 * 2590 * @see #setScrollIndicators(int) 2591 * @see #setScrollIndicators(int, int) 2592 * @see #getScrollIndicators() 2593 */ 2594 public static final int SCROLL_INDICATOR_RIGHT = 2595 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2596 2597 /** 2598 * Scroll indicator direction for the starting edge of the view. 2599 * <p> 2600 * Resolved according to the view's layout direction, see 2601 * {@link #getLayoutDirection()} for more information. 2602 * 2603 * @see #setScrollIndicators(int) 2604 * @see #setScrollIndicators(int, int) 2605 * @see #getScrollIndicators() 2606 */ 2607 public static final int SCROLL_INDICATOR_START = 2608 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2609 2610 /** 2611 * Scroll indicator direction for the ending edge of the view. 2612 * <p> 2613 * Resolved according to the view's layout direction, see 2614 * {@link #getLayoutDirection()} for more information. 2615 * 2616 * @see #setScrollIndicators(int) 2617 * @see #setScrollIndicators(int, int) 2618 * @see #getScrollIndicators() 2619 */ 2620 public static final int SCROLL_INDICATOR_END = 2621 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2622 2623 /** 2624 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2625 * into this view.<p> 2626 */ 2627 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2628 2629 /** 2630 * The mask for use with private flags indicating bits used for pointer icon shapes. 2631 */ 2632 static final int PFLAG3_POINTER_ICON_MASK = 0x7f8000; 2633 2634 /** 2635 * Left-shift used for pointer icon shape values in private flags. 2636 */ 2637 static final int PFLAG3_POINTER_ICON_LSHIFT = 15; 2638 2639 /** 2640 * Value indicating no specific pointer icons. 2641 */ 2642 private static final int PFLAG3_POINTER_ICON_NOT_SPECIFIED = 0 << PFLAG3_POINTER_ICON_LSHIFT; 2643 2644 /** 2645 * Value indicating {@link PointerIcon.STYLE_NULL}. 2646 */ 2647 private static final int PFLAG3_POINTER_ICON_NULL = 1 << PFLAG3_POINTER_ICON_LSHIFT; 2648 2649 /** 2650 * The base value for other pointer icon shapes. 2651 */ 2652 private static final int PFLAG3_POINTER_ICON_VALUE_START = 2 << PFLAG3_POINTER_ICON_LSHIFT; 2653 2654 /** 2655 * Always allow a user to over-scroll this view, provided it is a 2656 * view that can scroll. 2657 * 2658 * @see #getOverScrollMode() 2659 * @see #setOverScrollMode(int) 2660 */ 2661 public static final int OVER_SCROLL_ALWAYS = 0; 2662 2663 /** 2664 * Allow a user to over-scroll this view only if the content is large 2665 * enough to meaningfully scroll, provided it is a view that can scroll. 2666 * 2667 * @see #getOverScrollMode() 2668 * @see #setOverScrollMode(int) 2669 */ 2670 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2671 2672 /** 2673 * Never allow a user to over-scroll this view. 2674 * 2675 * @see #getOverScrollMode() 2676 * @see #setOverScrollMode(int) 2677 */ 2678 public static final int OVER_SCROLL_NEVER = 2; 2679 2680 /** 2681 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2682 * requested the system UI (status bar) to be visible (the default). 2683 * 2684 * @see #setSystemUiVisibility(int) 2685 */ 2686 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2687 2688 /** 2689 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2690 * system UI to enter an unobtrusive "low profile" mode. 2691 * 2692 * <p>This is for use in games, book readers, video players, or any other 2693 * "immersive" application where the usual system chrome is deemed too distracting. 2694 * 2695 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2696 * 2697 * @see #setSystemUiVisibility(int) 2698 */ 2699 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2700 2701 /** 2702 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2703 * system navigation be temporarily hidden. 2704 * 2705 * <p>This is an even less obtrusive state than that called for by 2706 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2707 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2708 * those to disappear. This is useful (in conjunction with the 2709 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2710 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2711 * window flags) for displaying content using every last pixel on the display. 2712 * 2713 * <p>There is a limitation: because navigation controls are so important, the least user 2714 * interaction will cause them to reappear immediately. When this happens, both 2715 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2716 * so that both elements reappear at the same time. 2717 * 2718 * @see #setSystemUiVisibility(int) 2719 */ 2720 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2721 2722 /** 2723 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2724 * into the normal fullscreen mode so that its content can take over the screen 2725 * while still allowing the user to interact with the application. 2726 * 2727 * <p>This has the same visual effect as 2728 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2729 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2730 * meaning that non-critical screen decorations (such as the status bar) will be 2731 * hidden while the user is in the View's window, focusing the experience on 2732 * that content. Unlike the window flag, if you are using ActionBar in 2733 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2734 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2735 * hide the action bar. 2736 * 2737 * <p>This approach to going fullscreen is best used over the window flag when 2738 * it is a transient state -- that is, the application does this at certain 2739 * points in its user interaction where it wants to allow the user to focus 2740 * on content, but not as a continuous state. For situations where the application 2741 * would like to simply stay full screen the entire time (such as a game that 2742 * wants to take over the screen), the 2743 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2744 * is usually a better approach. The state set here will be removed by the system 2745 * in various situations (such as the user moving to another application) like 2746 * the other system UI states. 2747 * 2748 * <p>When using this flag, the application should provide some easy facility 2749 * for the user to go out of it. A common example would be in an e-book 2750 * reader, where tapping on the screen brings back whatever screen and UI 2751 * decorations that had been hidden while the user was immersed in reading 2752 * the book. 2753 * 2754 * @see #setSystemUiVisibility(int) 2755 */ 2756 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2757 2758 /** 2759 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2760 * flags, we would like a stable view of the content insets given to 2761 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2762 * will always represent the worst case that the application can expect 2763 * as a continuous state. In the stock Android UI this is the space for 2764 * the system bar, nav bar, and status bar, but not more transient elements 2765 * such as an input method. 2766 * 2767 * The stable layout your UI sees is based on the system UI modes you can 2768 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2769 * then you will get a stable layout for changes of the 2770 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2771 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2772 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2773 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2774 * with a stable layout. (Note that you should avoid using 2775 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2776 * 2777 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2778 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2779 * then a hidden status bar will be considered a "stable" state for purposes 2780 * here. This allows your UI to continually hide the status bar, while still 2781 * using the system UI flags to hide the action bar while still retaining 2782 * a stable layout. Note that changing the window fullscreen flag will never 2783 * provide a stable layout for a clean transition. 2784 * 2785 * <p>If you are using ActionBar in 2786 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2787 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2788 * insets it adds to those given to the application. 2789 */ 2790 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2791 2792 /** 2793 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2794 * to be laid out as if it has requested 2795 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2796 * allows it to avoid artifacts when switching in and out of that mode, at 2797 * the expense that some of its user interface may be covered by screen 2798 * decorations when they are shown. You can perform layout of your inner 2799 * UI elements to account for the navigation system UI through the 2800 * {@link #fitSystemWindows(Rect)} method. 2801 */ 2802 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2803 2804 /** 2805 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2806 * to be laid out as if it has requested 2807 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2808 * allows it to avoid artifacts when switching in and out of that mode, at 2809 * the expense that some of its user interface may be covered by screen 2810 * decorations when they are shown. You can perform layout of your inner 2811 * UI elements to account for non-fullscreen system UI through the 2812 * {@link #fitSystemWindows(Rect)} method. 2813 */ 2814 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2815 2816 /** 2817 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2818 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2819 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2820 * user interaction. 2821 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2822 * has an effect when used in combination with that flag.</p> 2823 */ 2824 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2825 2826 /** 2827 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2828 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2829 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2830 * experience while also hiding the system bars. If this flag is not set, 2831 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2832 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2833 * if the user swipes from the top of the screen. 2834 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2835 * system gestures, such as swiping from the top of the screen. These transient system bars 2836 * will overlay app’s content, may have some degree of transparency, and will automatically 2837 * hide after a short timeout. 2838 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2839 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2840 * with one or both of those flags.</p> 2841 */ 2842 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2843 2844 /** 2845 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 2846 * is compatible with light status bar backgrounds. 2847 * 2848 * <p>For this to take effect, the window must request 2849 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 2850 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 2851 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 2852 * FLAG_TRANSLUCENT_STATUS}. 2853 * 2854 * @see android.R.attr#windowLightStatusBar 2855 */ 2856 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 2857 2858 /** 2859 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2860 */ 2861 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2862 2863 /** 2864 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2865 */ 2866 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2867 2868 /** 2869 * @hide 2870 * 2871 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2872 * out of the public fields to keep the undefined bits out of the developer's way. 2873 * 2874 * Flag to make the status bar not expandable. Unless you also 2875 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2876 */ 2877 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2878 2879 /** 2880 * @hide 2881 * 2882 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2883 * out of the public fields to keep the undefined bits out of the developer's way. 2884 * 2885 * Flag to hide notification icons and scrolling ticker text. 2886 */ 2887 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2888 2889 /** 2890 * @hide 2891 * 2892 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2893 * out of the public fields to keep the undefined bits out of the developer's way. 2894 * 2895 * Flag to disable incoming notification alerts. This will not block 2896 * icons, but it will block sound, vibrating and other visual or aural notifications. 2897 */ 2898 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2899 2900 /** 2901 * @hide 2902 * 2903 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2904 * out of the public fields to keep the undefined bits out of the developer's way. 2905 * 2906 * Flag to hide only the scrolling ticker. Note that 2907 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2908 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2909 */ 2910 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2911 2912 /** 2913 * @hide 2914 * 2915 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2916 * out of the public fields to keep the undefined bits out of the developer's way. 2917 * 2918 * Flag to hide the center system info area. 2919 */ 2920 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2921 2922 /** 2923 * @hide 2924 * 2925 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2926 * out of the public fields to keep the undefined bits out of the developer's way. 2927 * 2928 * Flag to hide only the home button. Don't use this 2929 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2930 */ 2931 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2932 2933 /** 2934 * @hide 2935 * 2936 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2937 * out of the public fields to keep the undefined bits out of the developer's way. 2938 * 2939 * Flag to hide only the back button. Don't use this 2940 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2941 */ 2942 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2943 2944 /** 2945 * @hide 2946 * 2947 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2948 * out of the public fields to keep the undefined bits out of the developer's way. 2949 * 2950 * Flag to hide only the clock. You might use this if your activity has 2951 * its own clock making the status bar's clock redundant. 2952 */ 2953 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2954 2955 /** 2956 * @hide 2957 * 2958 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2959 * out of the public fields to keep the undefined bits out of the developer's way. 2960 * 2961 * Flag to hide only the recent apps button. Don't use this 2962 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2963 */ 2964 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2965 2966 /** 2967 * @hide 2968 * 2969 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2970 * out of the public fields to keep the undefined bits out of the developer's way. 2971 * 2972 * Flag to disable the global search gesture. Don't use this 2973 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2974 */ 2975 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2976 2977 /** 2978 * @hide 2979 * 2980 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2981 * out of the public fields to keep the undefined bits out of the developer's way. 2982 * 2983 * Flag to specify that the status bar is displayed in transient mode. 2984 */ 2985 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2986 2987 /** 2988 * @hide 2989 * 2990 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2991 * out of the public fields to keep the undefined bits out of the developer's way. 2992 * 2993 * Flag to specify that the navigation bar is displayed in transient mode. 2994 */ 2995 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2996 2997 /** 2998 * @hide 2999 * 3000 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3001 * out of the public fields to keep the undefined bits out of the developer's way. 3002 * 3003 * Flag to specify that the hidden status bar would like to be shown. 3004 */ 3005 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3006 3007 /** 3008 * @hide 3009 * 3010 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3011 * out of the public fields to keep the undefined bits out of the developer's way. 3012 * 3013 * Flag to specify that the hidden navigation bar would like to be shown. 3014 */ 3015 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3016 3017 /** 3018 * @hide 3019 * 3020 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3021 * out of the public fields to keep the undefined bits out of the developer's way. 3022 * 3023 * Flag to specify that the status bar is displayed in translucent mode. 3024 */ 3025 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3026 3027 /** 3028 * @hide 3029 * 3030 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3031 * out of the public fields to keep the undefined bits out of the developer's way. 3032 * 3033 * Flag to specify that the navigation bar is displayed in translucent mode. 3034 */ 3035 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3036 3037 /** 3038 * @hide 3039 * 3040 * Whether Recents is visible or not. 3041 */ 3042 public static final int RECENT_APPS_VISIBLE = 0x00004000; 3043 3044 /** 3045 * @hide 3046 * 3047 * Makes navigation bar transparent (but not the status bar). 3048 */ 3049 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3050 3051 /** 3052 * @hide 3053 * 3054 * Makes status bar transparent (but not the navigation bar). 3055 */ 3056 public static final int STATUS_BAR_TRANSPARENT = 0x0000008; 3057 3058 /** 3059 * @hide 3060 * 3061 * Makes both status bar and navigation bar transparent. 3062 */ 3063 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3064 | STATUS_BAR_TRANSPARENT; 3065 3066 /** 3067 * @hide 3068 */ 3069 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3070 3071 /** 3072 * These are the system UI flags that can be cleared by events outside 3073 * of an application. Currently this is just the ability to tap on the 3074 * screen while hiding the navigation bar to have it return. 3075 * @hide 3076 */ 3077 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3078 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3079 | SYSTEM_UI_FLAG_FULLSCREEN; 3080 3081 /** 3082 * Flags that can impact the layout in relation to system UI. 3083 */ 3084 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3085 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3086 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3087 3088 /** @hide */ 3089 @IntDef(flag = true, 3090 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3091 @Retention(RetentionPolicy.SOURCE) 3092 public @interface FindViewFlags {} 3093 3094 /** 3095 * Find views that render the specified text. 3096 * 3097 * @see #findViewsWithText(ArrayList, CharSequence, int) 3098 */ 3099 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3100 3101 /** 3102 * Find find views that contain the specified content description. 3103 * 3104 * @see #findViewsWithText(ArrayList, CharSequence, int) 3105 */ 3106 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3107 3108 /** 3109 * Find views that contain {@link AccessibilityNodeProvider}. Such 3110 * a View is a root of virtual view hierarchy and may contain the searched 3111 * text. If this flag is set Views with providers are automatically 3112 * added and it is a responsibility of the client to call the APIs of 3113 * the provider to determine whether the virtual tree rooted at this View 3114 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3115 * representing the virtual views with this text. 3116 * 3117 * @see #findViewsWithText(ArrayList, CharSequence, int) 3118 * 3119 * @hide 3120 */ 3121 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3122 3123 /** 3124 * The undefined cursor position. 3125 * 3126 * @hide 3127 */ 3128 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3129 3130 /** 3131 * Indicates that the screen has changed state and is now off. 3132 * 3133 * @see #onScreenStateChanged(int) 3134 */ 3135 public static final int SCREEN_STATE_OFF = 0x0; 3136 3137 /** 3138 * Indicates that the screen has changed state and is now on. 3139 * 3140 * @see #onScreenStateChanged(int) 3141 */ 3142 public static final int SCREEN_STATE_ON = 0x1; 3143 3144 /** 3145 * Indicates no axis of view scrolling. 3146 */ 3147 public static final int SCROLL_AXIS_NONE = 0; 3148 3149 /** 3150 * Indicates scrolling along the horizontal axis. 3151 */ 3152 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3153 3154 /** 3155 * Indicates scrolling along the vertical axis. 3156 */ 3157 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3158 3159 /** 3160 * Controls the over-scroll mode for this view. 3161 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3162 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3163 * and {@link #OVER_SCROLL_NEVER}. 3164 */ 3165 private int mOverScrollMode; 3166 3167 /** 3168 * The parent this view is attached to. 3169 * {@hide} 3170 * 3171 * @see #getParent() 3172 */ 3173 protected ViewParent mParent; 3174 3175 /** 3176 * {@hide} 3177 */ 3178 AttachInfo mAttachInfo; 3179 3180 /** 3181 * {@hide} 3182 */ 3183 @ViewDebug.ExportedProperty(flagMapping = { 3184 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3185 name = "FORCE_LAYOUT"), 3186 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3187 name = "LAYOUT_REQUIRED"), 3188 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3189 name = "DRAWING_CACHE_INVALID", outputIf = false), 3190 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3191 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3192 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3193 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3194 }, formatToHexString = true) 3195 int mPrivateFlags; 3196 int mPrivateFlags2; 3197 int mPrivateFlags3; 3198 3199 /** 3200 * This view's request for the visibility of the status bar. 3201 * @hide 3202 */ 3203 @ViewDebug.ExportedProperty(flagMapping = { 3204 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3205 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3206 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3207 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3208 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3209 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3210 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3211 equals = SYSTEM_UI_FLAG_VISIBLE, 3212 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3213 }, formatToHexString = true) 3214 int mSystemUiVisibility; 3215 3216 /** 3217 * Reference count for transient state. 3218 * @see #setHasTransientState(boolean) 3219 */ 3220 int mTransientStateCount = 0; 3221 3222 /** 3223 * Count of how many windows this view has been attached to. 3224 */ 3225 int mWindowAttachCount; 3226 3227 /** 3228 * The layout parameters associated with this view and used by the parent 3229 * {@link android.view.ViewGroup} to determine how this view should be 3230 * laid out. 3231 * {@hide} 3232 */ 3233 protected ViewGroup.LayoutParams mLayoutParams; 3234 3235 /** 3236 * The view flags hold various views states. 3237 * {@hide} 3238 */ 3239 @ViewDebug.ExportedProperty(formatToHexString = true) 3240 int mViewFlags; 3241 3242 static class TransformationInfo { 3243 /** 3244 * The transform matrix for the View. This transform is calculated internally 3245 * based on the translation, rotation, and scale properties. 3246 * 3247 * Do *not* use this variable directly; instead call getMatrix(), which will 3248 * load the value from the View's RenderNode. 3249 */ 3250 private final Matrix mMatrix = new Matrix(); 3251 3252 /** 3253 * The inverse transform matrix for the View. This transform is calculated 3254 * internally based on the translation, rotation, and scale properties. 3255 * 3256 * Do *not* use this variable directly; instead call getInverseMatrix(), 3257 * which will load the value from the View's RenderNode. 3258 */ 3259 private Matrix mInverseMatrix; 3260 3261 /** 3262 * The opacity of the View. This is a value from 0 to 1, where 0 means 3263 * completely transparent and 1 means completely opaque. 3264 */ 3265 @ViewDebug.ExportedProperty 3266 float mAlpha = 1f; 3267 3268 /** 3269 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3270 * property only used by transitions, which is composited with the other alpha 3271 * values to calculate the final visual alpha value. 3272 */ 3273 float mTransitionAlpha = 1f; 3274 } 3275 3276 TransformationInfo mTransformationInfo; 3277 3278 /** 3279 * Current clip bounds. to which all drawing of this view are constrained. 3280 */ 3281 Rect mClipBounds = null; 3282 3283 private boolean mLastIsOpaque; 3284 3285 /** 3286 * The distance in pixels from the left edge of this view's parent 3287 * to the left edge of this view. 3288 * {@hide} 3289 */ 3290 @ViewDebug.ExportedProperty(category = "layout") 3291 protected int mLeft; 3292 /** 3293 * The distance in pixels from the left edge of this view's parent 3294 * to the right edge of this view. 3295 * {@hide} 3296 */ 3297 @ViewDebug.ExportedProperty(category = "layout") 3298 protected int mRight; 3299 /** 3300 * The distance in pixels from the top edge of this view's parent 3301 * to the top edge of this view. 3302 * {@hide} 3303 */ 3304 @ViewDebug.ExportedProperty(category = "layout") 3305 protected int mTop; 3306 /** 3307 * The distance in pixels from the top edge of this view's parent 3308 * to the bottom edge of this view. 3309 * {@hide} 3310 */ 3311 @ViewDebug.ExportedProperty(category = "layout") 3312 protected int mBottom; 3313 3314 /** 3315 * The offset, in pixels, by which the content of this view is scrolled 3316 * horizontally. 3317 * {@hide} 3318 */ 3319 @ViewDebug.ExportedProperty(category = "scrolling") 3320 protected int mScrollX; 3321 /** 3322 * The offset, in pixels, by which the content of this view is scrolled 3323 * vertically. 3324 * {@hide} 3325 */ 3326 @ViewDebug.ExportedProperty(category = "scrolling") 3327 protected int mScrollY; 3328 3329 /** 3330 * The left padding in pixels, that is the distance in pixels between the 3331 * left edge of this view and the left edge of its content. 3332 * {@hide} 3333 */ 3334 @ViewDebug.ExportedProperty(category = "padding") 3335 protected int mPaddingLeft = 0; 3336 /** 3337 * The right padding in pixels, that is the distance in pixels between the 3338 * right edge of this view and the right edge of its content. 3339 * {@hide} 3340 */ 3341 @ViewDebug.ExportedProperty(category = "padding") 3342 protected int mPaddingRight = 0; 3343 /** 3344 * The top padding in pixels, that is the distance in pixels between the 3345 * top edge of this view and the top edge of its content. 3346 * {@hide} 3347 */ 3348 @ViewDebug.ExportedProperty(category = "padding") 3349 protected int mPaddingTop; 3350 /** 3351 * The bottom padding in pixels, that is the distance in pixels between the 3352 * bottom edge of this view and the bottom edge of its content. 3353 * {@hide} 3354 */ 3355 @ViewDebug.ExportedProperty(category = "padding") 3356 protected int mPaddingBottom; 3357 3358 /** 3359 * The layout insets in pixels, that is the distance in pixels between the 3360 * visible edges of this view its bounds. 3361 */ 3362 private Insets mLayoutInsets; 3363 3364 /** 3365 * Briefly describes the view and is primarily used for accessibility support. 3366 */ 3367 private CharSequence mContentDescription; 3368 3369 /** 3370 * Specifies the id of a view for which this view serves as a label for 3371 * accessibility purposes. 3372 */ 3373 private int mLabelForId = View.NO_ID; 3374 3375 /** 3376 * Predicate for matching labeled view id with its label for 3377 * accessibility purposes. 3378 */ 3379 private MatchLabelForPredicate mMatchLabelForPredicate; 3380 3381 /** 3382 * Specifies a view before which this one is visited in accessibility traversal. 3383 */ 3384 private int mAccessibilityTraversalBeforeId = NO_ID; 3385 3386 /** 3387 * Specifies a view after which this one is visited in accessibility traversal. 3388 */ 3389 private int mAccessibilityTraversalAfterId = NO_ID; 3390 3391 /** 3392 * Predicate for matching a view by its id. 3393 */ 3394 private MatchIdPredicate mMatchIdPredicate; 3395 3396 /** 3397 * Cache the paddingRight set by the user to append to the scrollbar's size. 3398 * 3399 * @hide 3400 */ 3401 @ViewDebug.ExportedProperty(category = "padding") 3402 protected int mUserPaddingRight; 3403 3404 /** 3405 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3406 * 3407 * @hide 3408 */ 3409 @ViewDebug.ExportedProperty(category = "padding") 3410 protected int mUserPaddingBottom; 3411 3412 /** 3413 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3414 * 3415 * @hide 3416 */ 3417 @ViewDebug.ExportedProperty(category = "padding") 3418 protected int mUserPaddingLeft; 3419 3420 /** 3421 * Cache the paddingStart set by the user to append to the scrollbar's size. 3422 * 3423 */ 3424 @ViewDebug.ExportedProperty(category = "padding") 3425 int mUserPaddingStart; 3426 3427 /** 3428 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3429 * 3430 */ 3431 @ViewDebug.ExportedProperty(category = "padding") 3432 int mUserPaddingEnd; 3433 3434 /** 3435 * Cache initial left padding. 3436 * 3437 * @hide 3438 */ 3439 int mUserPaddingLeftInitial; 3440 3441 /** 3442 * Cache initial right padding. 3443 * 3444 * @hide 3445 */ 3446 int mUserPaddingRightInitial; 3447 3448 /** 3449 * Default undefined padding 3450 */ 3451 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3452 3453 /** 3454 * Cache if a left padding has been defined 3455 */ 3456 private boolean mLeftPaddingDefined = false; 3457 3458 /** 3459 * Cache if a right padding has been defined 3460 */ 3461 private boolean mRightPaddingDefined = false; 3462 3463 /** 3464 * @hide 3465 */ 3466 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3467 /** 3468 * @hide 3469 */ 3470 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3471 3472 private LongSparseLongArray mMeasureCache; 3473 3474 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3475 private Drawable mBackground; 3476 private TintInfo mBackgroundTint; 3477 3478 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3479 private ForegroundInfo mForegroundInfo; 3480 3481 private Drawable mScrollIndicatorDrawable; 3482 3483 /** 3484 * RenderNode used for backgrounds. 3485 * <p> 3486 * When non-null and valid, this is expected to contain an up-to-date copy 3487 * of the background drawable. It is cleared on temporary detach, and reset 3488 * on cleanup. 3489 */ 3490 private RenderNode mBackgroundRenderNode; 3491 3492 private int mBackgroundResource; 3493 private boolean mBackgroundSizeChanged; 3494 3495 private String mTransitionName; 3496 3497 static class TintInfo { 3498 ColorStateList mTintList; 3499 PorterDuff.Mode mTintMode; 3500 boolean mHasTintMode; 3501 boolean mHasTintList; 3502 } 3503 3504 private static class ForegroundInfo { 3505 private Drawable mDrawable; 3506 private TintInfo mTintInfo; 3507 private int mGravity = Gravity.FILL; 3508 private boolean mInsidePadding = true; 3509 private boolean mBoundsChanged = true; 3510 private final Rect mSelfBounds = new Rect(); 3511 private final Rect mOverlayBounds = new Rect(); 3512 } 3513 3514 static class ListenerInfo { 3515 /** 3516 * Listener used to dispatch focus change events. 3517 * This field should be made private, so it is hidden from the SDK. 3518 * {@hide} 3519 */ 3520 protected OnFocusChangeListener mOnFocusChangeListener; 3521 3522 /** 3523 * Listeners for layout change events. 3524 */ 3525 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3526 3527 protected OnScrollChangeListener mOnScrollChangeListener; 3528 3529 /** 3530 * Listeners for attach events. 3531 */ 3532 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3533 3534 /** 3535 * Listener used to dispatch click events. 3536 * This field should be made private, so it is hidden from the SDK. 3537 * {@hide} 3538 */ 3539 public OnClickListener mOnClickListener; 3540 3541 /** 3542 * Listener used to dispatch long click events. 3543 * This field should be made private, so it is hidden from the SDK. 3544 * {@hide} 3545 */ 3546 protected OnLongClickListener mOnLongClickListener; 3547 3548 /** 3549 * Listener used to dispatch context click events. This field should be made private, so it 3550 * is hidden from the SDK. 3551 * {@hide} 3552 */ 3553 protected OnContextClickListener mOnContextClickListener; 3554 3555 /** 3556 * Listener used to build the context menu. 3557 * This field should be made private, so it is hidden from the SDK. 3558 * {@hide} 3559 */ 3560 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3561 3562 private OnKeyListener mOnKeyListener; 3563 3564 private OnTouchListener mOnTouchListener; 3565 3566 private OnHoverListener mOnHoverListener; 3567 3568 private OnGenericMotionListener mOnGenericMotionListener; 3569 3570 private OnDragListener mOnDragListener; 3571 3572 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3573 3574 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3575 } 3576 3577 ListenerInfo mListenerInfo; 3578 3579 // Temporary values used to hold (x,y) coordinates when delegating from the 3580 // two-arg performLongClick() method to the legacy no-arg version. 3581 private float mLongClickX = Float.NaN; 3582 private float mLongClickY = Float.NaN; 3583 3584 /** 3585 * The application environment this view lives in. 3586 * This field should be made private, so it is hidden from the SDK. 3587 * {@hide} 3588 */ 3589 @ViewDebug.ExportedProperty(deepExport = true) 3590 protected Context mContext; 3591 3592 private final Resources mResources; 3593 3594 private ScrollabilityCache mScrollCache; 3595 3596 private int[] mDrawableState = null; 3597 3598 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3599 3600 /** 3601 * Animator that automatically runs based on state changes. 3602 */ 3603 private StateListAnimator mStateListAnimator; 3604 3605 /** 3606 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3607 * the user may specify which view to go to next. 3608 */ 3609 private int mNextFocusLeftId = View.NO_ID; 3610 3611 /** 3612 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3613 * the user may specify which view to go to next. 3614 */ 3615 private int mNextFocusRightId = View.NO_ID; 3616 3617 /** 3618 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3619 * the user may specify which view to go to next. 3620 */ 3621 private int mNextFocusUpId = View.NO_ID; 3622 3623 /** 3624 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3625 * the user may specify which view to go to next. 3626 */ 3627 private int mNextFocusDownId = View.NO_ID; 3628 3629 /** 3630 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3631 * the user may specify which view to go to next. 3632 */ 3633 int mNextFocusForwardId = View.NO_ID; 3634 3635 private CheckForLongPress mPendingCheckForLongPress; 3636 private CheckForTap mPendingCheckForTap = null; 3637 private PerformClick mPerformClick; 3638 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3639 3640 private UnsetPressedState mUnsetPressedState; 3641 3642 /** 3643 * Whether the long press's action has been invoked. The tap's action is invoked on the 3644 * up event while a long press is invoked as soon as the long press duration is reached, so 3645 * a long press could be performed before the tap is checked, in which case the tap's action 3646 * should not be invoked. 3647 */ 3648 private boolean mHasPerformedLongPress; 3649 3650 /** 3651 * Whether a context click button is currently pressed down. This is true when the stylus is 3652 * touching the screen and the primary button has been pressed, or if a mouse's right button is 3653 * pressed. This is false once the button is released or if the stylus has been lifted. 3654 */ 3655 private boolean mInContextButtonPress; 3656 3657 /** 3658 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 3659 * true after a stylus button press has occured, when the next up event should not be recognized 3660 * as a tap. 3661 */ 3662 private boolean mIgnoreNextUpEvent; 3663 3664 /** 3665 * The minimum height of the view. We'll try our best to have the height 3666 * of this view to at least this amount. 3667 */ 3668 @ViewDebug.ExportedProperty(category = "measurement") 3669 private int mMinHeight; 3670 3671 /** 3672 * The minimum width of the view. We'll try our best to have the width 3673 * of this view to at least this amount. 3674 */ 3675 @ViewDebug.ExportedProperty(category = "measurement") 3676 private int mMinWidth; 3677 3678 /** 3679 * The delegate to handle touch events that are physically in this view 3680 * but should be handled by another view. 3681 */ 3682 private TouchDelegate mTouchDelegate = null; 3683 3684 /** 3685 * Solid color to use as a background when creating the drawing cache. Enables 3686 * the cache to use 16 bit bitmaps instead of 32 bit. 3687 */ 3688 private int mDrawingCacheBackgroundColor = 0; 3689 3690 /** 3691 * Special tree observer used when mAttachInfo is null. 3692 */ 3693 private ViewTreeObserver mFloatingTreeObserver; 3694 3695 /** 3696 * Cache the touch slop from the context that created the view. 3697 */ 3698 private int mTouchSlop; 3699 3700 /** 3701 * Object that handles automatic animation of view properties. 3702 */ 3703 private ViewPropertyAnimator mAnimator = null; 3704 3705 /** 3706 * List of registered FrameMetricsObservers. 3707 */ 3708 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 3709 3710 /** 3711 * Flag indicating that a drag can cross window boundaries. When 3712 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3713 * with this flag set, all visible applications will be able to participate 3714 * in the drag operation and receive the dragged content. 3715 * 3716 * If this is the only flag set, then the drag recipient will only have access to text data 3717 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 3718 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags. 3719 */ 3720 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 3721 3722 /** 3723 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3724 * request read access to the content URI(s) contained in the {@link ClipData} object. 3725 * @see android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION 3726 */ 3727 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 3728 3729 /** 3730 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 3731 * request write access to the content URI(s) contained in the {@link ClipData} object. 3732 * @see android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION 3733 */ 3734 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 3735 3736 /** 3737 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3738 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 3739 * reboots until explicitly revoked with 3740 * {@link android.content.Context#revokeUriPermission(Uri,int) Context.revokeUriPermission}. 3741 * @see android.content.Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 3742 */ 3743 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 3744 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 3745 3746 /** 3747 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 3748 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 3749 * match against the original granted URI. 3750 * @see android.content.Intent.FLAG_GRANT_PREFIX_URI_PERMISSION 3751 */ 3752 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 3753 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 3754 3755 /** 3756 * Flag indicating that the drag shadow will be opaque. When 3757 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 3758 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 3759 */ 3760 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 3761 3762 /** 3763 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3764 */ 3765 private float mVerticalScrollFactor; 3766 3767 /** 3768 * Position of the vertical scroll bar. 3769 */ 3770 private int mVerticalScrollbarPosition; 3771 3772 /** 3773 * Position the scroll bar at the default position as determined by the system. 3774 */ 3775 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3776 3777 /** 3778 * Position the scroll bar along the left edge. 3779 */ 3780 public static final int SCROLLBAR_POSITION_LEFT = 1; 3781 3782 /** 3783 * Position the scroll bar along the right edge. 3784 */ 3785 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3786 3787 /** 3788 * Indicates that the view does not have a layer. 3789 * 3790 * @see #getLayerType() 3791 * @see #setLayerType(int, android.graphics.Paint) 3792 * @see #LAYER_TYPE_SOFTWARE 3793 * @see #LAYER_TYPE_HARDWARE 3794 */ 3795 public static final int LAYER_TYPE_NONE = 0; 3796 3797 /** 3798 * <p>Indicates that the view has a software layer. A software layer is backed 3799 * by a bitmap and causes the view to be rendered using Android's software 3800 * rendering pipeline, even if hardware acceleration is enabled.</p> 3801 * 3802 * <p>Software layers have various usages:</p> 3803 * <p>When the application is not using hardware acceleration, a software layer 3804 * is useful to apply a specific color filter and/or blending mode and/or 3805 * translucency to a view and all its children.</p> 3806 * <p>When the application is using hardware acceleration, a software layer 3807 * is useful to render drawing primitives not supported by the hardware 3808 * accelerated pipeline. It can also be used to cache a complex view tree 3809 * into a texture and reduce the complexity of drawing operations. For instance, 3810 * when animating a complex view tree with a translation, a software layer can 3811 * be used to render the view tree only once.</p> 3812 * <p>Software layers should be avoided when the affected view tree updates 3813 * often. Every update will require to re-render the software layer, which can 3814 * potentially be slow (particularly when hardware acceleration is turned on 3815 * since the layer will have to be uploaded into a hardware texture after every 3816 * update.)</p> 3817 * 3818 * @see #getLayerType() 3819 * @see #setLayerType(int, android.graphics.Paint) 3820 * @see #LAYER_TYPE_NONE 3821 * @see #LAYER_TYPE_HARDWARE 3822 */ 3823 public static final int LAYER_TYPE_SOFTWARE = 1; 3824 3825 /** 3826 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3827 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3828 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3829 * rendering pipeline, but only if hardware acceleration is turned on for the 3830 * view hierarchy. When hardware acceleration is turned off, hardware layers 3831 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3832 * 3833 * <p>A hardware layer is useful to apply a specific color filter and/or 3834 * blending mode and/or translucency to a view and all its children.</p> 3835 * <p>A hardware layer can be used to cache a complex view tree into a 3836 * texture and reduce the complexity of drawing operations. For instance, 3837 * when animating a complex view tree with a translation, a hardware layer can 3838 * be used to render the view tree only once.</p> 3839 * <p>A hardware layer can also be used to increase the rendering quality when 3840 * rotation transformations are applied on a view. It can also be used to 3841 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3842 * 3843 * @see #getLayerType() 3844 * @see #setLayerType(int, android.graphics.Paint) 3845 * @see #LAYER_TYPE_NONE 3846 * @see #LAYER_TYPE_SOFTWARE 3847 */ 3848 public static final int LAYER_TYPE_HARDWARE = 2; 3849 3850 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3851 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3852 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3853 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3854 }) 3855 int mLayerType = LAYER_TYPE_NONE; 3856 Paint mLayerPaint; 3857 3858 /** 3859 * Set to true when drawing cache is enabled and cannot be created. 3860 * 3861 * @hide 3862 */ 3863 public boolean mCachingFailed; 3864 private Bitmap mDrawingCache; 3865 private Bitmap mUnscaledDrawingCache; 3866 3867 /** 3868 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3869 * <p> 3870 * When non-null and valid, this is expected to contain an up-to-date copy 3871 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3872 * cleanup. 3873 */ 3874 final RenderNode mRenderNode; 3875 3876 /** 3877 * Set to true when the view is sending hover accessibility events because it 3878 * is the innermost hovered view. 3879 */ 3880 private boolean mSendingHoverAccessibilityEvents; 3881 3882 /** 3883 * Delegate for injecting accessibility functionality. 3884 */ 3885 AccessibilityDelegate mAccessibilityDelegate; 3886 3887 /** 3888 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3889 * and add/remove objects to/from the overlay directly through the Overlay methods. 3890 */ 3891 ViewOverlay mOverlay; 3892 3893 /** 3894 * The currently active parent view for receiving delegated nested scrolling events. 3895 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3896 * by {@link #stopNestedScroll()} at the same point where we clear 3897 * requestDisallowInterceptTouchEvent. 3898 */ 3899 private ViewParent mNestedScrollingParent; 3900 3901 /** 3902 * Consistency verifier for debugging purposes. 3903 * @hide 3904 */ 3905 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3906 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3907 new InputEventConsistencyVerifier(this, 0) : null; 3908 3909 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3910 3911 private int[] mTempNestedScrollConsumed; 3912 3913 /** 3914 * An overlay is going to draw this View instead of being drawn as part of this 3915 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3916 * when this view is invalidated. 3917 */ 3918 GhostView mGhostView; 3919 3920 /** 3921 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3922 * @hide 3923 */ 3924 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3925 public String[] mAttributes; 3926 3927 /** 3928 * Maps a Resource id to its name. 3929 */ 3930 private static SparseArray<String> mAttributeMap; 3931 3932 /** 3933 * Queue of pending runnables. Used to postpone calls to post() until this 3934 * view is attached and has a handler. 3935 */ 3936 private HandlerActionQueue mRunQueue; 3937 3938 /** 3939 * The pointer icon when the mouse hovers on this view. The default is null. 3940 */ 3941 private PointerIcon mPointerIcon; 3942 3943 /** 3944 * @hide 3945 */ 3946 String mStartActivityRequestWho; 3947 3948 /** 3949 * Simple constructor to use when creating a view from code. 3950 * 3951 * @param context The Context the view is running in, through which it can 3952 * access the current theme, resources, etc. 3953 */ 3954 public View(Context context) { 3955 mContext = context; 3956 mResources = context != null ? context.getResources() : null; 3957 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3958 // Set some flags defaults 3959 mPrivateFlags2 = 3960 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3961 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3962 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3963 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3964 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3965 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3966 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3967 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3968 mUserPaddingStart = UNDEFINED_PADDING; 3969 mUserPaddingEnd = UNDEFINED_PADDING; 3970 mRenderNode = RenderNode.create(getClass().getName(), this); 3971 3972 if (!sCompatibilityDone && context != null) { 3973 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3974 3975 // Older apps may need this compatibility hack for measurement. 3976 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3977 3978 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3979 // of whether a layout was requested on that View. 3980 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3981 3982 Canvas.sCompatibilityRestore = targetSdkVersion < M; 3983 3984 // In M and newer, our widgets can pass a "hint" value in the size 3985 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 3986 // know what the expected parent size is going to be, so e.g. list items can size 3987 // themselves at 1/3 the size of their container. It breaks older apps though, 3988 // specifically apps that use some popular open source libraries. 3989 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M; 3990 3991 // Old versions of the platform would give different results from 3992 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 3993 // modes, so we always need to run an additional EXACTLY pass. 3994 sAlwaysRemeasureExactly = targetSdkVersion <= M; 3995 3996 // Prior to N, layout params could change without requiring a 3997 // subsequent call to setLayoutParams() and they would usually 3998 // work. Partial layout breaks this assumption. 3999 sLayoutParamsAlwaysChanged = targetSdkVersion <= M; 4000 4001 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4002 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4003 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= M; 4004 4005 sCompatibilityDone = true; 4006 } 4007 } 4008 4009 /** 4010 * Constructor that is called when inflating a view from XML. This is called 4011 * when a view is being constructed from an XML file, supplying attributes 4012 * that were specified in the XML file. This version uses a default style of 4013 * 0, so the only attribute values applied are those in the Context's Theme 4014 * and the given AttributeSet. 4015 * 4016 * <p> 4017 * The method onFinishInflate() will be called after all children have been 4018 * added. 4019 * 4020 * @param context The Context the view is running in, through which it can 4021 * access the current theme, resources, etc. 4022 * @param attrs The attributes of the XML tag that is inflating the view. 4023 * @see #View(Context, AttributeSet, int) 4024 */ 4025 public View(Context context, @Nullable AttributeSet attrs) { 4026 this(context, attrs, 0); 4027 } 4028 4029 /** 4030 * Perform inflation from XML and apply a class-specific base style from a 4031 * theme attribute. This constructor of View allows subclasses to use their 4032 * own base style when they are inflating. For example, a Button class's 4033 * constructor would call this version of the super class constructor and 4034 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4035 * allows the theme's button style to modify all of the base view attributes 4036 * (in particular its background) as well as the Button class's attributes. 4037 * 4038 * @param context The Context the view is running in, through which it can 4039 * access the current theme, resources, etc. 4040 * @param attrs The attributes of the XML tag that is inflating the view. 4041 * @param defStyleAttr An attribute in the current theme that contains a 4042 * reference to a style resource that supplies default values for 4043 * the view. Can be 0 to not look for defaults. 4044 * @see #View(Context, AttributeSet) 4045 */ 4046 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4047 this(context, attrs, defStyleAttr, 0); 4048 } 4049 4050 /** 4051 * Perform inflation from XML and apply a class-specific base style from a 4052 * theme attribute or style resource. This constructor of View allows 4053 * subclasses to use their own base style when they are inflating. 4054 * <p> 4055 * When determining the final value of a particular attribute, there are 4056 * four inputs that come into play: 4057 * <ol> 4058 * <li>Any attribute values in the given AttributeSet. 4059 * <li>The style resource specified in the AttributeSet (named "style"). 4060 * <li>The default style specified by <var>defStyleAttr</var>. 4061 * <li>The default style specified by <var>defStyleRes</var>. 4062 * <li>The base values in this theme. 4063 * </ol> 4064 * <p> 4065 * Each of these inputs is considered in-order, with the first listed taking 4066 * precedence over the following ones. In other words, if in the 4067 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4068 * , then the button's text will <em>always</em> be black, regardless of 4069 * what is specified in any of the styles. 4070 * 4071 * @param context The Context the view is running in, through which it can 4072 * access the current theme, resources, etc. 4073 * @param attrs The attributes of the XML tag that is inflating the view. 4074 * @param defStyleAttr An attribute in the current theme that contains a 4075 * reference to a style resource that supplies default values for 4076 * the view. Can be 0 to not look for defaults. 4077 * @param defStyleRes A resource identifier of a style resource that 4078 * supplies default values for the view, used only if 4079 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4080 * to not look for defaults. 4081 * @see #View(Context, AttributeSet, int) 4082 */ 4083 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4084 this(context); 4085 4086 final TypedArray a = context.obtainStyledAttributes( 4087 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4088 4089 if (mDebugViewAttributes) { 4090 saveAttributeData(attrs, a); 4091 } 4092 4093 Drawable background = null; 4094 4095 int leftPadding = -1; 4096 int topPadding = -1; 4097 int rightPadding = -1; 4098 int bottomPadding = -1; 4099 int startPadding = UNDEFINED_PADDING; 4100 int endPadding = UNDEFINED_PADDING; 4101 4102 int padding = -1; 4103 4104 int viewFlagValues = 0; 4105 int viewFlagMasks = 0; 4106 4107 boolean setScrollContainer = false; 4108 4109 int x = 0; 4110 int y = 0; 4111 4112 float tx = 0; 4113 float ty = 0; 4114 float tz = 0; 4115 float elevation = 0; 4116 float rotation = 0; 4117 float rotationX = 0; 4118 float rotationY = 0; 4119 float sx = 1f; 4120 float sy = 1f; 4121 boolean transformSet = false; 4122 4123 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4124 int overScrollMode = mOverScrollMode; 4125 boolean initializeScrollbars = false; 4126 boolean initializeScrollIndicators = false; 4127 4128 boolean startPaddingDefined = false; 4129 boolean endPaddingDefined = false; 4130 boolean leftPaddingDefined = false; 4131 boolean rightPaddingDefined = false; 4132 4133 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4134 4135 final int N = a.getIndexCount(); 4136 for (int i = 0; i < N; i++) { 4137 int attr = a.getIndex(i); 4138 switch (attr) { 4139 case com.android.internal.R.styleable.View_background: 4140 background = a.getDrawable(attr); 4141 break; 4142 case com.android.internal.R.styleable.View_padding: 4143 padding = a.getDimensionPixelSize(attr, -1); 4144 mUserPaddingLeftInitial = padding; 4145 mUserPaddingRightInitial = padding; 4146 leftPaddingDefined = true; 4147 rightPaddingDefined = true; 4148 break; 4149 case com.android.internal.R.styleable.View_paddingLeft: 4150 leftPadding = a.getDimensionPixelSize(attr, -1); 4151 mUserPaddingLeftInitial = leftPadding; 4152 leftPaddingDefined = true; 4153 break; 4154 case com.android.internal.R.styleable.View_paddingTop: 4155 topPadding = a.getDimensionPixelSize(attr, -1); 4156 break; 4157 case com.android.internal.R.styleable.View_paddingRight: 4158 rightPadding = a.getDimensionPixelSize(attr, -1); 4159 mUserPaddingRightInitial = rightPadding; 4160 rightPaddingDefined = true; 4161 break; 4162 case com.android.internal.R.styleable.View_paddingBottom: 4163 bottomPadding = a.getDimensionPixelSize(attr, -1); 4164 break; 4165 case com.android.internal.R.styleable.View_paddingStart: 4166 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4167 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4168 break; 4169 case com.android.internal.R.styleable.View_paddingEnd: 4170 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4171 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4172 break; 4173 case com.android.internal.R.styleable.View_scrollX: 4174 x = a.getDimensionPixelOffset(attr, 0); 4175 break; 4176 case com.android.internal.R.styleable.View_scrollY: 4177 y = a.getDimensionPixelOffset(attr, 0); 4178 break; 4179 case com.android.internal.R.styleable.View_alpha: 4180 setAlpha(a.getFloat(attr, 1f)); 4181 break; 4182 case com.android.internal.R.styleable.View_transformPivotX: 4183 setPivotX(a.getDimensionPixelOffset(attr, 0)); 4184 break; 4185 case com.android.internal.R.styleable.View_transformPivotY: 4186 setPivotY(a.getDimensionPixelOffset(attr, 0)); 4187 break; 4188 case com.android.internal.R.styleable.View_translationX: 4189 tx = a.getDimensionPixelOffset(attr, 0); 4190 transformSet = true; 4191 break; 4192 case com.android.internal.R.styleable.View_translationY: 4193 ty = a.getDimensionPixelOffset(attr, 0); 4194 transformSet = true; 4195 break; 4196 case com.android.internal.R.styleable.View_translationZ: 4197 tz = a.getDimensionPixelOffset(attr, 0); 4198 transformSet = true; 4199 break; 4200 case com.android.internal.R.styleable.View_elevation: 4201 elevation = a.getDimensionPixelOffset(attr, 0); 4202 transformSet = true; 4203 break; 4204 case com.android.internal.R.styleable.View_rotation: 4205 rotation = a.getFloat(attr, 0); 4206 transformSet = true; 4207 break; 4208 case com.android.internal.R.styleable.View_rotationX: 4209 rotationX = a.getFloat(attr, 0); 4210 transformSet = true; 4211 break; 4212 case com.android.internal.R.styleable.View_rotationY: 4213 rotationY = a.getFloat(attr, 0); 4214 transformSet = true; 4215 break; 4216 case com.android.internal.R.styleable.View_scaleX: 4217 sx = a.getFloat(attr, 1f); 4218 transformSet = true; 4219 break; 4220 case com.android.internal.R.styleable.View_scaleY: 4221 sy = a.getFloat(attr, 1f); 4222 transformSet = true; 4223 break; 4224 case com.android.internal.R.styleable.View_id: 4225 mID = a.getResourceId(attr, NO_ID); 4226 break; 4227 case com.android.internal.R.styleable.View_tag: 4228 mTag = a.getText(attr); 4229 break; 4230 case com.android.internal.R.styleable.View_fitsSystemWindows: 4231 if (a.getBoolean(attr, false)) { 4232 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4233 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4234 } 4235 break; 4236 case com.android.internal.R.styleable.View_focusable: 4237 if (a.getBoolean(attr, false)) { 4238 viewFlagValues |= FOCUSABLE; 4239 viewFlagMasks |= FOCUSABLE_MASK; 4240 } 4241 break; 4242 case com.android.internal.R.styleable.View_focusableInTouchMode: 4243 if (a.getBoolean(attr, false)) { 4244 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4245 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4246 } 4247 break; 4248 case com.android.internal.R.styleable.View_clickable: 4249 if (a.getBoolean(attr, false)) { 4250 viewFlagValues |= CLICKABLE; 4251 viewFlagMasks |= CLICKABLE; 4252 } 4253 break; 4254 case com.android.internal.R.styleable.View_longClickable: 4255 if (a.getBoolean(attr, false)) { 4256 viewFlagValues |= LONG_CLICKABLE; 4257 viewFlagMasks |= LONG_CLICKABLE; 4258 } 4259 break; 4260 case com.android.internal.R.styleable.View_contextClickable: 4261 if (a.getBoolean(attr, false)) { 4262 viewFlagValues |= CONTEXT_CLICKABLE; 4263 viewFlagMasks |= CONTEXT_CLICKABLE; 4264 } 4265 break; 4266 case com.android.internal.R.styleable.View_saveEnabled: 4267 if (!a.getBoolean(attr, true)) { 4268 viewFlagValues |= SAVE_DISABLED; 4269 viewFlagMasks |= SAVE_DISABLED_MASK; 4270 } 4271 break; 4272 case com.android.internal.R.styleable.View_duplicateParentState: 4273 if (a.getBoolean(attr, false)) { 4274 viewFlagValues |= DUPLICATE_PARENT_STATE; 4275 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4276 } 4277 break; 4278 case com.android.internal.R.styleable.View_visibility: 4279 final int visibility = a.getInt(attr, 0); 4280 if (visibility != 0) { 4281 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4282 viewFlagMasks |= VISIBILITY_MASK; 4283 } 4284 break; 4285 case com.android.internal.R.styleable.View_layoutDirection: 4286 // Clear any layout direction flags (included resolved bits) already set 4287 mPrivateFlags2 &= 4288 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4289 // Set the layout direction flags depending on the value of the attribute 4290 final int layoutDirection = a.getInt(attr, -1); 4291 final int value = (layoutDirection != -1) ? 4292 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4293 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4294 break; 4295 case com.android.internal.R.styleable.View_drawingCacheQuality: 4296 final int cacheQuality = a.getInt(attr, 0); 4297 if (cacheQuality != 0) { 4298 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4299 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4300 } 4301 break; 4302 case com.android.internal.R.styleable.View_contentDescription: 4303 setContentDescription(a.getString(attr)); 4304 break; 4305 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4306 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4307 break; 4308 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4309 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4310 break; 4311 case com.android.internal.R.styleable.View_labelFor: 4312 setLabelFor(a.getResourceId(attr, NO_ID)); 4313 break; 4314 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4315 if (!a.getBoolean(attr, true)) { 4316 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4317 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4318 } 4319 break; 4320 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4321 if (!a.getBoolean(attr, true)) { 4322 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4323 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4324 } 4325 break; 4326 case R.styleable.View_scrollbars: 4327 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4328 if (scrollbars != SCROLLBARS_NONE) { 4329 viewFlagValues |= scrollbars; 4330 viewFlagMasks |= SCROLLBARS_MASK; 4331 initializeScrollbars = true; 4332 } 4333 break; 4334 //noinspection deprecation 4335 case R.styleable.View_fadingEdge: 4336 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 4337 // Ignore the attribute starting with ICS 4338 break; 4339 } 4340 // With builds < ICS, fall through and apply fading edges 4341 case R.styleable.View_requiresFadingEdge: 4342 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4343 if (fadingEdge != FADING_EDGE_NONE) { 4344 viewFlagValues |= fadingEdge; 4345 viewFlagMasks |= FADING_EDGE_MASK; 4346 initializeFadingEdgeInternal(a); 4347 } 4348 break; 4349 case R.styleable.View_scrollbarStyle: 4350 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4351 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4352 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4353 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4354 } 4355 break; 4356 case R.styleable.View_isScrollContainer: 4357 setScrollContainer = true; 4358 if (a.getBoolean(attr, false)) { 4359 setScrollContainer(true); 4360 } 4361 break; 4362 case com.android.internal.R.styleable.View_keepScreenOn: 4363 if (a.getBoolean(attr, false)) { 4364 viewFlagValues |= KEEP_SCREEN_ON; 4365 viewFlagMasks |= KEEP_SCREEN_ON; 4366 } 4367 break; 4368 case R.styleable.View_filterTouchesWhenObscured: 4369 if (a.getBoolean(attr, false)) { 4370 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4371 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4372 } 4373 break; 4374 case R.styleable.View_nextFocusLeft: 4375 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4376 break; 4377 case R.styleable.View_nextFocusRight: 4378 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4379 break; 4380 case R.styleable.View_nextFocusUp: 4381 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4382 break; 4383 case R.styleable.View_nextFocusDown: 4384 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4385 break; 4386 case R.styleable.View_nextFocusForward: 4387 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4388 break; 4389 case R.styleable.View_minWidth: 4390 mMinWidth = a.getDimensionPixelSize(attr, 0); 4391 break; 4392 case R.styleable.View_minHeight: 4393 mMinHeight = a.getDimensionPixelSize(attr, 0); 4394 break; 4395 case R.styleable.View_onClick: 4396 if (context.isRestricted()) { 4397 throw new IllegalStateException("The android:onClick attribute cannot " 4398 + "be used within a restricted context"); 4399 } 4400 4401 final String handlerName = a.getString(attr); 4402 if (handlerName != null) { 4403 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4404 } 4405 break; 4406 case R.styleable.View_overScrollMode: 4407 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4408 break; 4409 case R.styleable.View_verticalScrollbarPosition: 4410 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4411 break; 4412 case R.styleable.View_layerType: 4413 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4414 break; 4415 case R.styleable.View_textDirection: 4416 // Clear any text direction flag already set 4417 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4418 // Set the text direction flags depending on the value of the attribute 4419 final int textDirection = a.getInt(attr, -1); 4420 if (textDirection != -1) { 4421 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4422 } 4423 break; 4424 case R.styleable.View_textAlignment: 4425 // Clear any text alignment flag already set 4426 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4427 // Set the text alignment flag depending on the value of the attribute 4428 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4429 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4430 break; 4431 case R.styleable.View_importantForAccessibility: 4432 setImportantForAccessibility(a.getInt(attr, 4433 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4434 break; 4435 case R.styleable.View_accessibilityLiveRegion: 4436 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4437 break; 4438 case R.styleable.View_transitionName: 4439 setTransitionName(a.getString(attr)); 4440 break; 4441 case R.styleable.View_nestedScrollingEnabled: 4442 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4443 break; 4444 case R.styleable.View_stateListAnimator: 4445 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4446 a.getResourceId(attr, 0))); 4447 break; 4448 case R.styleable.View_backgroundTint: 4449 // This will get applied later during setBackground(). 4450 if (mBackgroundTint == null) { 4451 mBackgroundTint = new TintInfo(); 4452 } 4453 mBackgroundTint.mTintList = a.getColorStateList( 4454 R.styleable.View_backgroundTint); 4455 mBackgroundTint.mHasTintList = true; 4456 break; 4457 case R.styleable.View_backgroundTintMode: 4458 // This will get applied later during setBackground(). 4459 if (mBackgroundTint == null) { 4460 mBackgroundTint = new TintInfo(); 4461 } 4462 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4463 R.styleable.View_backgroundTintMode, -1), null); 4464 mBackgroundTint.mHasTintMode = true; 4465 break; 4466 case R.styleable.View_outlineProvider: 4467 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4468 PROVIDER_BACKGROUND)); 4469 break; 4470 case R.styleable.View_foreground: 4471 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4472 setForeground(a.getDrawable(attr)); 4473 } 4474 break; 4475 case R.styleable.View_foregroundGravity: 4476 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4477 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4478 } 4479 break; 4480 case R.styleable.View_foregroundTintMode: 4481 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4482 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4483 } 4484 break; 4485 case R.styleable.View_foregroundTint: 4486 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4487 setForegroundTintList(a.getColorStateList(attr)); 4488 } 4489 break; 4490 case R.styleable.View_foregroundInsidePadding: 4491 if (targetSdkVersion >= VERSION_CODES.M || this instanceof FrameLayout) { 4492 if (mForegroundInfo == null) { 4493 mForegroundInfo = new ForegroundInfo(); 4494 } 4495 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4496 mForegroundInfo.mInsidePadding); 4497 } 4498 break; 4499 case R.styleable.View_scrollIndicators: 4500 final int scrollIndicators = 4501 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 4502 & SCROLL_INDICATORS_PFLAG3_MASK; 4503 if (scrollIndicators != 0) { 4504 mPrivateFlags3 |= scrollIndicators; 4505 initializeScrollIndicators = true; 4506 } 4507 break; 4508 case R.styleable.View_pointerShape: 4509 final int resourceId = a.getResourceId(attr, 0); 4510 if (resourceId != 0) { 4511 setPointerIcon(PointerIcon.loadCustomIcon( 4512 context.getResources(), resourceId)); 4513 } else { 4514 final int pointerShape = a.getInt(attr, PointerIcon.STYLE_NOT_SPECIFIED); 4515 if (pointerShape != PointerIcon.STYLE_NOT_SPECIFIED) { 4516 setPointerIcon(PointerIcon.getSystemIcon(context, pointerShape)); 4517 } 4518 } 4519 break; 4520 } 4521 } 4522 4523 setOverScrollMode(overScrollMode); 4524 4525 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4526 // the resolved layout direction). Those cached values will be used later during padding 4527 // resolution. 4528 mUserPaddingStart = startPadding; 4529 mUserPaddingEnd = endPadding; 4530 4531 if (background != null) { 4532 setBackground(background); 4533 } 4534 4535 // setBackground above will record that padding is currently provided by the background. 4536 // If we have padding specified via xml, record that here instead and use it. 4537 mLeftPaddingDefined = leftPaddingDefined; 4538 mRightPaddingDefined = rightPaddingDefined; 4539 4540 if (padding >= 0) { 4541 leftPadding = padding; 4542 topPadding = padding; 4543 rightPadding = padding; 4544 bottomPadding = padding; 4545 mUserPaddingLeftInitial = padding; 4546 mUserPaddingRightInitial = padding; 4547 } 4548 4549 if (isRtlCompatibilityMode()) { 4550 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4551 // left / right padding are used if defined (meaning here nothing to do). If they are not 4552 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4553 // start / end and resolve them as left / right (layout direction is not taken into account). 4554 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4555 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4556 // defined. 4557 if (!mLeftPaddingDefined && startPaddingDefined) { 4558 leftPadding = startPadding; 4559 } 4560 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4561 if (!mRightPaddingDefined && endPaddingDefined) { 4562 rightPadding = endPadding; 4563 } 4564 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4565 } else { 4566 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4567 // values defined. Otherwise, left /right values are used. 4568 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4569 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4570 // defined. 4571 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4572 4573 if (mLeftPaddingDefined && !hasRelativePadding) { 4574 mUserPaddingLeftInitial = leftPadding; 4575 } 4576 if (mRightPaddingDefined && !hasRelativePadding) { 4577 mUserPaddingRightInitial = rightPadding; 4578 } 4579 } 4580 4581 internalSetPadding( 4582 mUserPaddingLeftInitial, 4583 topPadding >= 0 ? topPadding : mPaddingTop, 4584 mUserPaddingRightInitial, 4585 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4586 4587 if (viewFlagMasks != 0) { 4588 setFlags(viewFlagValues, viewFlagMasks); 4589 } 4590 4591 if (initializeScrollbars) { 4592 initializeScrollbarsInternal(a); 4593 } 4594 4595 if (initializeScrollIndicators) { 4596 initializeScrollIndicatorsInternal(); 4597 } 4598 4599 a.recycle(); 4600 4601 // Needs to be called after mViewFlags is set 4602 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4603 recomputePadding(); 4604 } 4605 4606 if (x != 0 || y != 0) { 4607 scrollTo(x, y); 4608 } 4609 4610 if (transformSet) { 4611 setTranslationX(tx); 4612 setTranslationY(ty); 4613 setTranslationZ(tz); 4614 setElevation(elevation); 4615 setRotation(rotation); 4616 setRotationX(rotationX); 4617 setRotationY(rotationY); 4618 setScaleX(sx); 4619 setScaleY(sy); 4620 } 4621 4622 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4623 setScrollContainer(true); 4624 } 4625 4626 computeOpaqueFlags(); 4627 } 4628 4629 /** 4630 * An implementation of OnClickListener that attempts to lazily load a 4631 * named click handling method from a parent or ancestor context. 4632 */ 4633 private static class DeclaredOnClickListener implements OnClickListener { 4634 private final View mHostView; 4635 private final String mMethodName; 4636 4637 private Method mResolvedMethod; 4638 private Context mResolvedContext; 4639 4640 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 4641 mHostView = hostView; 4642 mMethodName = methodName; 4643 } 4644 4645 @Override 4646 public void onClick(@NonNull View v) { 4647 if (mResolvedMethod == null) { 4648 resolveMethod(mHostView.getContext(), mMethodName); 4649 } 4650 4651 try { 4652 mResolvedMethod.invoke(mResolvedContext, v); 4653 } catch (IllegalAccessException e) { 4654 throw new IllegalStateException( 4655 "Could not execute non-public method for android:onClick", e); 4656 } catch (InvocationTargetException e) { 4657 throw new IllegalStateException( 4658 "Could not execute method for android:onClick", e); 4659 } 4660 } 4661 4662 @NonNull 4663 private void resolveMethod(@Nullable Context context, @NonNull String name) { 4664 while (context != null) { 4665 try { 4666 if (!context.isRestricted()) { 4667 final Method method = context.getClass().getMethod(mMethodName, View.class); 4668 if (method != null) { 4669 mResolvedMethod = method; 4670 mResolvedContext = context; 4671 return; 4672 } 4673 } 4674 } catch (NoSuchMethodException e) { 4675 // Failed to find method, keep searching up the hierarchy. 4676 } 4677 4678 if (context instanceof ContextWrapper) { 4679 context = ((ContextWrapper) context).getBaseContext(); 4680 } else { 4681 // Can't search up the hierarchy, null out and fail. 4682 context = null; 4683 } 4684 } 4685 4686 final int id = mHostView.getId(); 4687 final String idText = id == NO_ID ? "" : " with id '" 4688 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 4689 throw new IllegalStateException("Could not find method " + mMethodName 4690 + "(View) in a parent or ancestor Context for android:onClick " 4691 + "attribute defined on view " + mHostView.getClass() + idText); 4692 } 4693 } 4694 4695 /** 4696 * Non-public constructor for use in testing 4697 */ 4698 View() { 4699 mResources = null; 4700 mRenderNode = RenderNode.create(getClass().getName(), this); 4701 } 4702 4703 private static SparseArray<String> getAttributeMap() { 4704 if (mAttributeMap == null) { 4705 mAttributeMap = new SparseArray<>(); 4706 } 4707 return mAttributeMap; 4708 } 4709 4710 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 4711 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 4712 final int indexCount = t.getIndexCount(); 4713 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 4714 4715 int i = 0; 4716 4717 // Store raw XML attributes. 4718 for (int j = 0; j < attrsCount; ++j) { 4719 attributes[i] = attrs.getAttributeName(j); 4720 attributes[i + 1] = attrs.getAttributeValue(j); 4721 i += 2; 4722 } 4723 4724 // Store resolved styleable attributes. 4725 final Resources res = t.getResources(); 4726 final SparseArray<String> attributeMap = getAttributeMap(); 4727 for (int j = 0; j < indexCount; ++j) { 4728 final int index = t.getIndex(j); 4729 if (!t.hasValueOrEmpty(index)) { 4730 // Value is undefined. Skip it. 4731 continue; 4732 } 4733 4734 final int resourceId = t.getResourceId(index, 0); 4735 if (resourceId == 0) { 4736 // Value is not a reference. Skip it. 4737 continue; 4738 } 4739 4740 String resourceName = attributeMap.get(resourceId); 4741 if (resourceName == null) { 4742 try { 4743 resourceName = res.getResourceName(resourceId); 4744 } catch (Resources.NotFoundException e) { 4745 resourceName = "0x" + Integer.toHexString(resourceId); 4746 } 4747 attributeMap.put(resourceId, resourceName); 4748 } 4749 4750 attributes[i] = resourceName; 4751 attributes[i + 1] = t.getString(index); 4752 i += 2; 4753 } 4754 4755 // Trim to fit contents. 4756 final String[] trimmed = new String[i]; 4757 System.arraycopy(attributes, 0, trimmed, 0, i); 4758 mAttributes = trimmed; 4759 } 4760 4761 public String toString() { 4762 StringBuilder out = new StringBuilder(128); 4763 out.append(getClass().getName()); 4764 out.append('{'); 4765 out.append(Integer.toHexString(System.identityHashCode(this))); 4766 out.append(' '); 4767 switch (mViewFlags&VISIBILITY_MASK) { 4768 case VISIBLE: out.append('V'); break; 4769 case INVISIBLE: out.append('I'); break; 4770 case GONE: out.append('G'); break; 4771 default: out.append('.'); break; 4772 } 4773 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4774 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4775 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4776 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4777 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4778 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4779 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4780 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 4781 out.append(' '); 4782 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4783 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4784 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4785 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4786 out.append('p'); 4787 } else { 4788 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4789 } 4790 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4791 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4792 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4793 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4794 out.append(' '); 4795 out.append(mLeft); 4796 out.append(','); 4797 out.append(mTop); 4798 out.append('-'); 4799 out.append(mRight); 4800 out.append(','); 4801 out.append(mBottom); 4802 final int id = getId(); 4803 if (id != NO_ID) { 4804 out.append(" #"); 4805 out.append(Integer.toHexString(id)); 4806 final Resources r = mResources; 4807 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 4808 try { 4809 String pkgname; 4810 switch (id&0xff000000) { 4811 case 0x7f000000: 4812 pkgname="app"; 4813 break; 4814 case 0x01000000: 4815 pkgname="android"; 4816 break; 4817 default: 4818 pkgname = r.getResourcePackageName(id); 4819 break; 4820 } 4821 String typename = r.getResourceTypeName(id); 4822 String entryname = r.getResourceEntryName(id); 4823 out.append(" "); 4824 out.append(pkgname); 4825 out.append(":"); 4826 out.append(typename); 4827 out.append("/"); 4828 out.append(entryname); 4829 } catch (Resources.NotFoundException e) { 4830 } 4831 } 4832 } 4833 out.append("}"); 4834 return out.toString(); 4835 } 4836 4837 /** 4838 * <p> 4839 * Initializes the fading edges from a given set of styled attributes. This 4840 * method should be called by subclasses that need fading edges and when an 4841 * instance of these subclasses is created programmatically rather than 4842 * being inflated from XML. This method is automatically called when the XML 4843 * is inflated. 4844 * </p> 4845 * 4846 * @param a the styled attributes set to initialize the fading edges from 4847 * 4848 * @removed 4849 */ 4850 protected void initializeFadingEdge(TypedArray a) { 4851 // This method probably shouldn't have been included in the SDK to begin with. 4852 // It relies on 'a' having been initialized using an attribute filter array that is 4853 // not publicly available to the SDK. The old method has been renamed 4854 // to initializeFadingEdgeInternal and hidden for framework use only; 4855 // this one initializes using defaults to make it safe to call for apps. 4856 4857 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4858 4859 initializeFadingEdgeInternal(arr); 4860 4861 arr.recycle(); 4862 } 4863 4864 /** 4865 * <p> 4866 * Initializes the fading edges from a given set of styled attributes. This 4867 * method should be called by subclasses that need fading edges and when an 4868 * instance of these subclasses is created programmatically rather than 4869 * being inflated from XML. This method is automatically called when the XML 4870 * is inflated. 4871 * </p> 4872 * 4873 * @param a the styled attributes set to initialize the fading edges from 4874 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4875 */ 4876 protected void initializeFadingEdgeInternal(TypedArray a) { 4877 initScrollCache(); 4878 4879 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4880 R.styleable.View_fadingEdgeLength, 4881 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4882 } 4883 4884 /** 4885 * Returns the size of the vertical faded edges used to indicate that more 4886 * content in this view is visible. 4887 * 4888 * @return The size in pixels of the vertical faded edge or 0 if vertical 4889 * faded edges are not enabled for this view. 4890 * @attr ref android.R.styleable#View_fadingEdgeLength 4891 */ 4892 public int getVerticalFadingEdgeLength() { 4893 if (isVerticalFadingEdgeEnabled()) { 4894 ScrollabilityCache cache = mScrollCache; 4895 if (cache != null) { 4896 return cache.fadingEdgeLength; 4897 } 4898 } 4899 return 0; 4900 } 4901 4902 /** 4903 * Set the size of the faded edge used to indicate that more content in this 4904 * view is available. Will not change whether the fading edge is enabled; use 4905 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4906 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4907 * for the vertical or horizontal fading edges. 4908 * 4909 * @param length The size in pixels of the faded edge used to indicate that more 4910 * content in this view is visible. 4911 */ 4912 public void setFadingEdgeLength(int length) { 4913 initScrollCache(); 4914 mScrollCache.fadingEdgeLength = length; 4915 } 4916 4917 /** 4918 * Returns the size of the horizontal faded edges used to indicate that more 4919 * content in this view is visible. 4920 * 4921 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4922 * faded edges are not enabled for this view. 4923 * @attr ref android.R.styleable#View_fadingEdgeLength 4924 */ 4925 public int getHorizontalFadingEdgeLength() { 4926 if (isHorizontalFadingEdgeEnabled()) { 4927 ScrollabilityCache cache = mScrollCache; 4928 if (cache != null) { 4929 return cache.fadingEdgeLength; 4930 } 4931 } 4932 return 0; 4933 } 4934 4935 /** 4936 * Returns the width of the vertical scrollbar. 4937 * 4938 * @return The width in pixels of the vertical scrollbar or 0 if there 4939 * is no vertical scrollbar. 4940 */ 4941 public int getVerticalScrollbarWidth() { 4942 ScrollabilityCache cache = mScrollCache; 4943 if (cache != null) { 4944 ScrollBarDrawable scrollBar = cache.scrollBar; 4945 if (scrollBar != null) { 4946 int size = scrollBar.getSize(true); 4947 if (size <= 0) { 4948 size = cache.scrollBarSize; 4949 } 4950 return size; 4951 } 4952 return 0; 4953 } 4954 return 0; 4955 } 4956 4957 /** 4958 * Returns the height of the horizontal scrollbar. 4959 * 4960 * @return The height in pixels of the horizontal scrollbar or 0 if 4961 * there is no horizontal scrollbar. 4962 */ 4963 protected int getHorizontalScrollbarHeight() { 4964 ScrollabilityCache cache = mScrollCache; 4965 if (cache != null) { 4966 ScrollBarDrawable scrollBar = cache.scrollBar; 4967 if (scrollBar != null) { 4968 int size = scrollBar.getSize(false); 4969 if (size <= 0) { 4970 size = cache.scrollBarSize; 4971 } 4972 return size; 4973 } 4974 return 0; 4975 } 4976 return 0; 4977 } 4978 4979 /** 4980 * <p> 4981 * Initializes the scrollbars from a given set of styled attributes. This 4982 * method should be called by subclasses that need scrollbars and when an 4983 * instance of these subclasses is created programmatically rather than 4984 * being inflated from XML. This method is automatically called when the XML 4985 * is inflated. 4986 * </p> 4987 * 4988 * @param a the styled attributes set to initialize the scrollbars from 4989 * 4990 * @removed 4991 */ 4992 protected void initializeScrollbars(TypedArray a) { 4993 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4994 // using the View filter array which is not available to the SDK. As such, internal 4995 // framework usage now uses initializeScrollbarsInternal and we grab a default 4996 // TypedArray with the right filter instead here. 4997 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4998 4999 initializeScrollbarsInternal(arr); 5000 5001 // We ignored the method parameter. Recycle the one we actually did use. 5002 arr.recycle(); 5003 } 5004 5005 /** 5006 * <p> 5007 * Initializes the scrollbars from a given set of styled attributes. This 5008 * method should be called by subclasses that need scrollbars and when an 5009 * instance of these subclasses is created programmatically rather than 5010 * being inflated from XML. This method is automatically called when the XML 5011 * is inflated. 5012 * </p> 5013 * 5014 * @param a the styled attributes set to initialize the scrollbars from 5015 * @hide 5016 */ 5017 protected void initializeScrollbarsInternal(TypedArray a) { 5018 initScrollCache(); 5019 5020 final ScrollabilityCache scrollabilityCache = mScrollCache; 5021 5022 if (scrollabilityCache.scrollBar == null) { 5023 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5024 scrollabilityCache.scrollBar.setCallback(this); 5025 scrollabilityCache.scrollBar.setState(getDrawableState()); 5026 } 5027 5028 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5029 5030 if (!fadeScrollbars) { 5031 scrollabilityCache.state = ScrollabilityCache.ON; 5032 } 5033 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5034 5035 5036 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5037 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5038 .getScrollBarFadeDuration()); 5039 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5040 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5041 ViewConfiguration.getScrollDefaultDelay()); 5042 5043 5044 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5045 com.android.internal.R.styleable.View_scrollbarSize, 5046 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5047 5048 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5049 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5050 5051 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5052 if (thumb != null) { 5053 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5054 } 5055 5056 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5057 false); 5058 if (alwaysDraw) { 5059 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5060 } 5061 5062 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5063 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5064 5065 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5066 if (thumb != null) { 5067 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5068 } 5069 5070 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5071 false); 5072 if (alwaysDraw) { 5073 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5074 } 5075 5076 // Apply layout direction to the new Drawables if needed 5077 final int layoutDirection = getLayoutDirection(); 5078 if (track != null) { 5079 track.setLayoutDirection(layoutDirection); 5080 } 5081 if (thumb != null) { 5082 thumb.setLayoutDirection(layoutDirection); 5083 } 5084 5085 // Re-apply user/background padding so that scrollbar(s) get added 5086 resolvePadding(); 5087 } 5088 5089 private void initializeScrollIndicatorsInternal() { 5090 // Some day maybe we'll break this into top/left/start/etc. and let the 5091 // client control it. Until then, you can have any scroll indicator you 5092 // want as long as it's a 1dp foreground-colored rectangle. 5093 if (mScrollIndicatorDrawable == null) { 5094 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5095 } 5096 } 5097 5098 /** 5099 * <p> 5100 * Initalizes the scrollability cache if necessary. 5101 * </p> 5102 */ 5103 private void initScrollCache() { 5104 if (mScrollCache == null) { 5105 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5106 } 5107 } 5108 5109 private ScrollabilityCache getScrollCache() { 5110 initScrollCache(); 5111 return mScrollCache; 5112 } 5113 5114 /** 5115 * Set the position of the vertical scroll bar. Should be one of 5116 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5117 * {@link #SCROLLBAR_POSITION_RIGHT}. 5118 * 5119 * @param position Where the vertical scroll bar should be positioned. 5120 */ 5121 public void setVerticalScrollbarPosition(int position) { 5122 if (mVerticalScrollbarPosition != position) { 5123 mVerticalScrollbarPosition = position; 5124 computeOpaqueFlags(); 5125 resolvePadding(); 5126 } 5127 } 5128 5129 /** 5130 * @return The position where the vertical scroll bar will show, if applicable. 5131 * @see #setVerticalScrollbarPosition(int) 5132 */ 5133 public int getVerticalScrollbarPosition() { 5134 return mVerticalScrollbarPosition; 5135 } 5136 5137 boolean isOnScrollbar(float x, float y) { 5138 if (mScrollCache == null) { 5139 return false; 5140 } 5141 x += getScrollX(); 5142 y += getScrollY(); 5143 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5144 final Rect bounds = mScrollCache.mScrollBarBounds; 5145 getVerticalScrollBarBounds(bounds); 5146 if (bounds.contains((int)x, (int)y)) { 5147 return true; 5148 } 5149 } 5150 if (isHorizontalScrollBarEnabled()) { 5151 final Rect bounds = mScrollCache.mScrollBarBounds; 5152 getHorizontalScrollBarBounds(bounds); 5153 if (bounds.contains((int)x, (int)y)) { 5154 return true; 5155 } 5156 } 5157 return false; 5158 } 5159 5160 boolean isOnScrollbarThumb(float x, float y) { 5161 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5162 } 5163 5164 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5165 if (mScrollCache == null) { 5166 return false; 5167 } 5168 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5169 x += getScrollX(); 5170 y += getScrollY(); 5171 final Rect bounds = mScrollCache.mScrollBarBounds; 5172 getVerticalScrollBarBounds(bounds); 5173 final int range = computeVerticalScrollRange(); 5174 final int offset = computeVerticalScrollOffset(); 5175 final int extent = computeVerticalScrollExtent(); 5176 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5177 extent, range); 5178 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5179 extent, range, offset); 5180 final int thumbTop = bounds.top + thumbOffset; 5181 if (x >= bounds.left && x <= bounds.right && y >= thumbTop 5182 && y <= thumbTop + thumbLength) { 5183 return true; 5184 } 5185 } 5186 return false; 5187 } 5188 5189 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5190 if (mScrollCache == null) { 5191 return false; 5192 } 5193 if (isHorizontalScrollBarEnabled()) { 5194 x += getScrollX(); 5195 y += getScrollY(); 5196 final Rect bounds = mScrollCache.mScrollBarBounds; 5197 getHorizontalScrollBarBounds(bounds); 5198 final int range = computeHorizontalScrollRange(); 5199 final int offset = computeHorizontalScrollOffset(); 5200 final int extent = computeHorizontalScrollExtent(); 5201 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5202 extent, range); 5203 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5204 extent, range, offset); 5205 final int thumbLeft = bounds.left + thumbOffset; 5206 if (x >= thumbLeft && x <= thumbLeft + thumbLength && y >= bounds.top 5207 && y <= bounds.bottom) { 5208 return true; 5209 } 5210 } 5211 return false; 5212 } 5213 5214 boolean isDraggingScrollBar() { 5215 return mScrollCache != null 5216 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5217 } 5218 5219 /** 5220 * Sets the state of all scroll indicators. 5221 * <p> 5222 * See {@link #setScrollIndicators(int, int)} for usage information. 5223 * 5224 * @param indicators a bitmask of indicators that should be enabled, or 5225 * {@code 0} to disable all indicators 5226 * @see #setScrollIndicators(int, int) 5227 * @see #getScrollIndicators() 5228 * @attr ref android.R.styleable#View_scrollIndicators 5229 */ 5230 public void setScrollIndicators(@ScrollIndicators int indicators) { 5231 setScrollIndicators(indicators, 5232 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5233 } 5234 5235 /** 5236 * Sets the state of the scroll indicators specified by the mask. To change 5237 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5238 * <p> 5239 * When a scroll indicator is enabled, it will be displayed if the view 5240 * can scroll in the direction of the indicator. 5241 * <p> 5242 * Multiple indicator types may be enabled or disabled by passing the 5243 * logical OR of the desired types. If multiple types are specified, they 5244 * will all be set to the same enabled state. 5245 * <p> 5246 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5247 * 5248 * @param indicators the indicator direction, or the logical OR of multiple 5249 * indicator directions. One or more of: 5250 * <ul> 5251 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5252 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5253 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5254 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5255 * <li>{@link #SCROLL_INDICATOR_START}</li> 5256 * <li>{@link #SCROLL_INDICATOR_END}</li> 5257 * </ul> 5258 * @see #setScrollIndicators(int) 5259 * @see #getScrollIndicators() 5260 * @attr ref android.R.styleable#View_scrollIndicators 5261 */ 5262 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5263 // Shift and sanitize mask. 5264 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5265 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5266 5267 // Shift and mask indicators. 5268 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5269 indicators &= mask; 5270 5271 // Merge with non-masked flags. 5272 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5273 5274 if (mPrivateFlags3 != updatedFlags) { 5275 mPrivateFlags3 = updatedFlags; 5276 5277 if (indicators != 0) { 5278 initializeScrollIndicatorsInternal(); 5279 } 5280 invalidate(); 5281 } 5282 } 5283 5284 /** 5285 * Returns a bitmask representing the enabled scroll indicators. 5286 * <p> 5287 * For example, if the top and left scroll indicators are enabled and all 5288 * other indicators are disabled, the return value will be 5289 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5290 * <p> 5291 * To check whether the bottom scroll indicator is enabled, use the value 5292 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5293 * 5294 * @return a bitmask representing the enabled scroll indicators 5295 */ 5296 @ScrollIndicators 5297 public int getScrollIndicators() { 5298 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5299 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5300 } 5301 5302 ListenerInfo getListenerInfo() { 5303 if (mListenerInfo != null) { 5304 return mListenerInfo; 5305 } 5306 mListenerInfo = new ListenerInfo(); 5307 return mListenerInfo; 5308 } 5309 5310 /** 5311 * Register a callback to be invoked when the scroll X or Y positions of 5312 * this view change. 5313 * <p> 5314 * <b>Note:</b> Some views handle scrolling independently from View and may 5315 * have their own separate listeners for scroll-type events. For example, 5316 * {@link android.widget.ListView ListView} allows clients to register an 5317 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5318 * to listen for changes in list scroll position. 5319 * 5320 * @param l The listener to notify when the scroll X or Y position changes. 5321 * @see android.view.View#getScrollX() 5322 * @see android.view.View#getScrollY() 5323 */ 5324 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5325 getListenerInfo().mOnScrollChangeListener = l; 5326 } 5327 5328 /** 5329 * Register a callback to be invoked when focus of this view changed. 5330 * 5331 * @param l The callback that will run. 5332 */ 5333 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5334 getListenerInfo().mOnFocusChangeListener = l; 5335 } 5336 5337 /** 5338 * Add a listener that will be called when the bounds of the view change due to 5339 * layout processing. 5340 * 5341 * @param listener The listener that will be called when layout bounds change. 5342 */ 5343 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5344 ListenerInfo li = getListenerInfo(); 5345 if (li.mOnLayoutChangeListeners == null) { 5346 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5347 } 5348 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5349 li.mOnLayoutChangeListeners.add(listener); 5350 } 5351 } 5352 5353 /** 5354 * Remove a listener for layout changes. 5355 * 5356 * @param listener The listener for layout bounds change. 5357 */ 5358 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5359 ListenerInfo li = mListenerInfo; 5360 if (li == null || li.mOnLayoutChangeListeners == null) { 5361 return; 5362 } 5363 li.mOnLayoutChangeListeners.remove(listener); 5364 } 5365 5366 /** 5367 * Add a listener for attach state changes. 5368 * 5369 * This listener will be called whenever this view is attached or detached 5370 * from a window. Remove the listener using 5371 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5372 * 5373 * @param listener Listener to attach 5374 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5375 */ 5376 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5377 ListenerInfo li = getListenerInfo(); 5378 if (li.mOnAttachStateChangeListeners == null) { 5379 li.mOnAttachStateChangeListeners 5380 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5381 } 5382 li.mOnAttachStateChangeListeners.add(listener); 5383 } 5384 5385 /** 5386 * Remove a listener for attach state changes. The listener will receive no further 5387 * notification of window attach/detach events. 5388 * 5389 * @param listener Listener to remove 5390 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5391 */ 5392 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5393 ListenerInfo li = mListenerInfo; 5394 if (li == null || li.mOnAttachStateChangeListeners == null) { 5395 return; 5396 } 5397 li.mOnAttachStateChangeListeners.remove(listener); 5398 } 5399 5400 /** 5401 * Returns the focus-change callback registered for this view. 5402 * 5403 * @return The callback, or null if one is not registered. 5404 */ 5405 public OnFocusChangeListener getOnFocusChangeListener() { 5406 ListenerInfo li = mListenerInfo; 5407 return li != null ? li.mOnFocusChangeListener : null; 5408 } 5409 5410 /** 5411 * Register a callback to be invoked when this view is clicked. If this view is not 5412 * clickable, it becomes clickable. 5413 * 5414 * @param l The callback that will run 5415 * 5416 * @see #setClickable(boolean) 5417 */ 5418 public void setOnClickListener(@Nullable OnClickListener l) { 5419 if (!isClickable()) { 5420 setClickable(true); 5421 } 5422 getListenerInfo().mOnClickListener = l; 5423 } 5424 5425 /** 5426 * Return whether this view has an attached OnClickListener. Returns 5427 * true if there is a listener, false if there is none. 5428 */ 5429 public boolean hasOnClickListeners() { 5430 ListenerInfo li = mListenerInfo; 5431 return (li != null && li.mOnClickListener != null); 5432 } 5433 5434 /** 5435 * Register a callback to be invoked when this view is clicked and held. If this view is not 5436 * long clickable, it becomes long clickable. 5437 * 5438 * @param l The callback that will run 5439 * 5440 * @see #setLongClickable(boolean) 5441 */ 5442 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 5443 if (!isLongClickable()) { 5444 setLongClickable(true); 5445 } 5446 getListenerInfo().mOnLongClickListener = l; 5447 } 5448 5449 /** 5450 * Register a callback to be invoked when this view is context clicked. If the view is not 5451 * context clickable, it becomes context clickable. 5452 * 5453 * @param l The callback that will run 5454 * @see #setContextClickable(boolean) 5455 */ 5456 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 5457 if (!isContextClickable()) { 5458 setContextClickable(true); 5459 } 5460 getListenerInfo().mOnContextClickListener = l; 5461 } 5462 5463 /** 5464 * Register a callback to be invoked when the context menu for this view is 5465 * being built. If this view is not long clickable, it becomes long clickable. 5466 * 5467 * @param l The callback that will run 5468 * 5469 */ 5470 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 5471 if (!isLongClickable()) { 5472 setLongClickable(true); 5473 } 5474 getListenerInfo().mOnCreateContextMenuListener = l; 5475 } 5476 5477 /** 5478 * Set an observer to collect stats for each frame rendered for this view. 5479 * 5480 * @hide 5481 */ 5482 public void addFrameMetricsListener(Window window, Window.FrameMetricsListener listener, 5483 Handler handler) { 5484 if (mAttachInfo != null) { 5485 if (mAttachInfo.mHardwareRenderer != null) { 5486 if (mFrameMetricsObservers == null) { 5487 mFrameMetricsObservers = new ArrayList<>(); 5488 } 5489 5490 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5491 handler.getLooper(), listener); 5492 mFrameMetricsObservers.add(fmo); 5493 mAttachInfo.mHardwareRenderer.addFrameMetricsObserver(fmo); 5494 } else { 5495 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5496 } 5497 } else { 5498 if (mFrameMetricsObservers == null) { 5499 mFrameMetricsObservers = new ArrayList<>(); 5500 } 5501 5502 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 5503 handler.getLooper(), listener); 5504 mFrameMetricsObservers.add(fmo); 5505 } 5506 } 5507 5508 /** 5509 * Remove observer configured to collect frame stats for this view. 5510 * 5511 * @hide 5512 */ 5513 public void removeFrameMetricsListener(Window.FrameMetricsListener listener) { 5514 ThreadedRenderer renderer = getHardwareRenderer(); 5515 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 5516 if (fmo == null) { 5517 throw new IllegalArgumentException("attempt to remove FrameMetricsListener that was never added"); 5518 } 5519 5520 if (mFrameMetricsObservers != null) { 5521 mFrameMetricsObservers.remove(fmo); 5522 if (renderer != null) { 5523 renderer.removeFrameMetricsObserver(fmo); 5524 } 5525 } 5526 } 5527 5528 private void registerPendingFrameMetricsObservers() { 5529 if (mFrameMetricsObservers != null) { 5530 ThreadedRenderer renderer = getHardwareRenderer(); 5531 if (renderer != null) { 5532 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 5533 renderer.addFrameMetricsObserver(fmo); 5534 } 5535 } else { 5536 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 5537 } 5538 } 5539 } 5540 5541 private FrameMetricsObserver findFrameMetricsObserver(Window.FrameMetricsListener listener) { 5542 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 5543 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 5544 if (observer.mListener == listener) { 5545 return observer; 5546 } 5547 } 5548 5549 return null; 5550 } 5551 5552 /** 5553 * Call this view's OnClickListener, if it is defined. Performs all normal 5554 * actions associated with clicking: reporting accessibility event, playing 5555 * a sound, etc. 5556 * 5557 * @return True there was an assigned OnClickListener that was called, false 5558 * otherwise is returned. 5559 */ 5560 public boolean performClick() { 5561 final boolean result; 5562 final ListenerInfo li = mListenerInfo; 5563 if (li != null && li.mOnClickListener != null) { 5564 playSoundEffect(SoundEffectConstants.CLICK); 5565 li.mOnClickListener.onClick(this); 5566 result = true; 5567 } else { 5568 result = false; 5569 } 5570 5571 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 5572 return result; 5573 } 5574 5575 /** 5576 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 5577 * this only calls the listener, and does not do any associated clicking 5578 * actions like reporting an accessibility event. 5579 * 5580 * @return True there was an assigned OnClickListener that was called, false 5581 * otherwise is returned. 5582 */ 5583 public boolean callOnClick() { 5584 ListenerInfo li = mListenerInfo; 5585 if (li != null && li.mOnClickListener != null) { 5586 li.mOnClickListener.onClick(this); 5587 return true; 5588 } 5589 return false; 5590 } 5591 5592 /** 5593 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5594 * context menu if the OnLongClickListener did not consume the event. 5595 * 5596 * @return {@code true} if one of the above receivers consumed the event, 5597 * {@code false} otherwise 5598 */ 5599 public boolean performLongClick() { 5600 return performLongClickInternal(mLongClickX, mLongClickY); 5601 } 5602 5603 /** 5604 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5605 * context menu if the OnLongClickListener did not consume the event, 5606 * anchoring it to an (x,y) coordinate. 5607 * 5608 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5609 * to disable anchoring 5610 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5611 * to disable anchoring 5612 * @return {@code true} if one of the above receivers consumed the event, 5613 * {@code false} otherwise 5614 */ 5615 public boolean performLongClick(float x, float y) { 5616 mLongClickX = x; 5617 mLongClickY = y; 5618 final boolean handled = performLongClick(); 5619 mLongClickX = Float.NaN; 5620 mLongClickY = Float.NaN; 5621 return handled; 5622 } 5623 5624 /** 5625 * Calls this view's OnLongClickListener, if it is defined. Invokes the 5626 * context menu if the OnLongClickListener did not consume the event, 5627 * optionally anchoring it to an (x,y) coordinate. 5628 * 5629 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 5630 * to disable anchoring 5631 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 5632 * to disable anchoring 5633 * @return {@code true} if one of the above receivers consumed the event, 5634 * {@code false} otherwise 5635 */ 5636 private boolean performLongClickInternal(float x, float y) { 5637 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 5638 5639 boolean handled = false; 5640 final ListenerInfo li = mListenerInfo; 5641 if (li != null && li.mOnLongClickListener != null) { 5642 handled = li.mOnLongClickListener.onLongClick(View.this); 5643 } 5644 if (!handled) { 5645 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 5646 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 5647 } 5648 if (handled) { 5649 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 5650 } 5651 return handled; 5652 } 5653 5654 /** 5655 * Call this view's OnContextClickListener, if it is defined. 5656 * 5657 * @return True if there was an assigned OnContextClickListener that consumed the event, false 5658 * otherwise. 5659 */ 5660 public boolean performContextClick() { 5661 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 5662 5663 boolean handled = false; 5664 ListenerInfo li = mListenerInfo; 5665 if (li != null && li.mOnContextClickListener != null) { 5666 handled = li.mOnContextClickListener.onContextClick(View.this); 5667 } 5668 if (handled) { 5669 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 5670 } 5671 return handled; 5672 } 5673 5674 /** 5675 * Performs button-related actions during a touch down event. 5676 * 5677 * @param event The event. 5678 * @return True if the down was consumed. 5679 * 5680 * @hide 5681 */ 5682 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 5683 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 5684 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 5685 showContextMenu(event.getX(), event.getY()); 5686 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 5687 return true; 5688 } 5689 return false; 5690 } 5691 5692 /** 5693 * Shows the context menu for this view. 5694 * 5695 * @return {@code true} if the context menu was shown, {@code false} 5696 * otherwise 5697 * @see #showContextMenu(float, float) 5698 */ 5699 public boolean showContextMenu() { 5700 return getParent().showContextMenuForChild(this); 5701 } 5702 5703 /** 5704 * Shows the context menu for this view anchored to the specified 5705 * view-relative coordinate. 5706 * 5707 * @param x the X coordinate in pixels relative to the view to which the 5708 * menu should be anchored 5709 * @param y the Y coordinate in pixels relative to the view to which the 5710 * menu should be anchored 5711 * @return {@code true} if the context menu was shown, {@code false} 5712 * otherwise 5713 */ 5714 public boolean showContextMenu(float x, float y) { 5715 return getParent().showContextMenuForChild(this, x, y); 5716 } 5717 5718 /** 5719 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 5720 * 5721 * @param callback Callback that will control the lifecycle of the action mode 5722 * @return The new action mode if it is started, null otherwise 5723 * 5724 * @see ActionMode 5725 * @see #startActionMode(android.view.ActionMode.Callback, int) 5726 */ 5727 public ActionMode startActionMode(ActionMode.Callback callback) { 5728 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 5729 } 5730 5731 /** 5732 * Start an action mode with the given type. 5733 * 5734 * @param callback Callback that will control the lifecycle of the action mode 5735 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 5736 * @return The new action mode if it is started, null otherwise 5737 * 5738 * @see ActionMode 5739 */ 5740 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 5741 ViewParent parent = getParent(); 5742 if (parent == null) return null; 5743 try { 5744 return parent.startActionModeForChild(this, callback, type); 5745 } catch (AbstractMethodError ame) { 5746 // Older implementations of custom views might not implement this. 5747 return parent.startActionModeForChild(this, callback); 5748 } 5749 } 5750 5751 /** 5752 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 5753 * Context, creating a unique View identifier to retrieve the result. 5754 * 5755 * @param intent The Intent to be started. 5756 * @param requestCode The request code to use. 5757 * @hide 5758 */ 5759 public void startActivityForResult(Intent intent, int requestCode) { 5760 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 5761 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 5762 } 5763 5764 /** 5765 * If this View corresponds to the calling who, dispatches the activity result. 5766 * @param who The identifier for the targeted View to receive the result. 5767 * @param requestCode The integer request code originally supplied to 5768 * startActivityForResult(), allowing you to identify who this 5769 * result came from. 5770 * @param resultCode The integer result code returned by the child activity 5771 * through its setResult(). 5772 * @param data An Intent, which can return result data to the caller 5773 * (various data can be attached to Intent "extras"). 5774 * @return {@code true} if the activity result was dispatched. 5775 * @hide 5776 */ 5777 public boolean dispatchActivityResult( 5778 String who, int requestCode, int resultCode, Intent data) { 5779 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 5780 onActivityResult(requestCode, resultCode, data); 5781 mStartActivityRequestWho = null; 5782 return true; 5783 } 5784 return false; 5785 } 5786 5787 /** 5788 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 5789 * 5790 * @param requestCode The integer request code originally supplied to 5791 * startActivityForResult(), allowing you to identify who this 5792 * result came from. 5793 * @param resultCode The integer result code returned by the child activity 5794 * through its setResult(). 5795 * @param data An Intent, which can return result data to the caller 5796 * (various data can be attached to Intent "extras"). 5797 * @hide 5798 */ 5799 public void onActivityResult(int requestCode, int resultCode, Intent data) { 5800 // Do nothing. 5801 } 5802 5803 /** 5804 * Register a callback to be invoked when a hardware key is pressed in this view. 5805 * Key presses in software input methods will generally not trigger the methods of 5806 * this listener. 5807 * @param l the key listener to attach to this view 5808 */ 5809 public void setOnKeyListener(OnKeyListener l) { 5810 getListenerInfo().mOnKeyListener = l; 5811 } 5812 5813 /** 5814 * Register a callback to be invoked when a touch event is sent to this view. 5815 * @param l the touch listener to attach to this view 5816 */ 5817 public void setOnTouchListener(OnTouchListener l) { 5818 getListenerInfo().mOnTouchListener = l; 5819 } 5820 5821 /** 5822 * Register a callback to be invoked when a generic motion event is sent to this view. 5823 * @param l the generic motion listener to attach to this view 5824 */ 5825 public void setOnGenericMotionListener(OnGenericMotionListener l) { 5826 getListenerInfo().mOnGenericMotionListener = l; 5827 } 5828 5829 /** 5830 * Register a callback to be invoked when a hover event is sent to this view. 5831 * @param l the hover listener to attach to this view 5832 */ 5833 public void setOnHoverListener(OnHoverListener l) { 5834 getListenerInfo().mOnHoverListener = l; 5835 } 5836 5837 /** 5838 * Register a drag event listener callback object for this View. The parameter is 5839 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 5840 * View, the system calls the 5841 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 5842 * @param l An implementation of {@link android.view.View.OnDragListener}. 5843 */ 5844 public void setOnDragListener(OnDragListener l) { 5845 getListenerInfo().mOnDragListener = l; 5846 } 5847 5848 /** 5849 * Give this view focus. This will cause 5850 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 5851 * 5852 * Note: this does not check whether this {@link View} should get focus, it just 5853 * gives it focus no matter what. It should only be called internally by framework 5854 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 5855 * 5856 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5857 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 5858 * focus moved when requestFocus() is called. It may not always 5859 * apply, in which case use the default View.FOCUS_DOWN. 5860 * @param previouslyFocusedRect The rectangle of the view that had focus 5861 * prior in this View's coordinate system. 5862 */ 5863 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 5864 if (DBG) { 5865 System.out.println(this + " requestFocus()"); 5866 } 5867 5868 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 5869 mPrivateFlags |= PFLAG_FOCUSED; 5870 5871 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 5872 5873 if (mParent != null) { 5874 mParent.requestChildFocus(this, this); 5875 } 5876 5877 if (mAttachInfo != null) { 5878 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 5879 } 5880 5881 onFocusChanged(true, direction, previouslyFocusedRect); 5882 refreshDrawableState(); 5883 } 5884 } 5885 5886 /** 5887 * Populates <code>outRect</code> with the hotspot bounds. By default, 5888 * the hotspot bounds are identical to the screen bounds. 5889 * 5890 * @param outRect rect to populate with hotspot bounds 5891 * @hide Only for internal use by views and widgets. 5892 */ 5893 public void getHotspotBounds(Rect outRect) { 5894 final Drawable background = getBackground(); 5895 if (background != null) { 5896 background.getHotspotBounds(outRect); 5897 } else { 5898 getBoundsOnScreen(outRect); 5899 } 5900 } 5901 5902 /** 5903 * Request that a rectangle of this view be visible on the screen, 5904 * scrolling if necessary just enough. 5905 * 5906 * <p>A View should call this if it maintains some notion of which part 5907 * of its content is interesting. For example, a text editing view 5908 * should call this when its cursor moves. 5909 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5910 * It should not be affected by which part of the View is currently visible or its scroll 5911 * position. 5912 * 5913 * @param rectangle The rectangle in the View's content coordinate space 5914 * @return Whether any parent scrolled. 5915 */ 5916 public boolean requestRectangleOnScreen(Rect rectangle) { 5917 return requestRectangleOnScreen(rectangle, false); 5918 } 5919 5920 /** 5921 * Request that a rectangle of this view be visible on the screen, 5922 * scrolling if necessary just enough. 5923 * 5924 * <p>A View should call this if it maintains some notion of which part 5925 * of its content is interesting. For example, a text editing view 5926 * should call this when its cursor moves. 5927 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 5928 * It should not be affected by which part of the View is currently visible or its scroll 5929 * position. 5930 * <p>When <code>immediate</code> is set to true, scrolling will not be 5931 * animated. 5932 * 5933 * @param rectangle The rectangle in the View's content coordinate space 5934 * @param immediate True to forbid animated scrolling, false otherwise 5935 * @return Whether any parent scrolled. 5936 */ 5937 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 5938 if (mParent == null) { 5939 return false; 5940 } 5941 5942 View child = this; 5943 5944 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 5945 position.set(rectangle); 5946 5947 ViewParent parent = mParent; 5948 boolean scrolled = false; 5949 while (parent != null) { 5950 rectangle.set((int) position.left, (int) position.top, 5951 (int) position.right, (int) position.bottom); 5952 5953 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 5954 5955 if (!(parent instanceof View)) { 5956 break; 5957 } 5958 5959 // move it from child's content coordinate space to parent's content coordinate space 5960 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 5961 5962 child = (View) parent; 5963 parent = child.getParent(); 5964 } 5965 5966 return scrolled; 5967 } 5968 5969 /** 5970 * Called when this view wants to give up focus. If focus is cleared 5971 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5972 * <p> 5973 * <strong>Note:</strong> When a View clears focus the framework is trying 5974 * to give focus to the first focusable View from the top. Hence, if this 5975 * View is the first from the top that can take focus, then all callbacks 5976 * related to clearing focus will be invoked after which the framework will 5977 * give focus to this view. 5978 * </p> 5979 */ 5980 public void clearFocus() { 5981 if (DBG) { 5982 System.out.println(this + " clearFocus()"); 5983 } 5984 5985 clearFocusInternal(null, true, true); 5986 } 5987 5988 /** 5989 * Clears focus from the view, optionally propagating the change up through 5990 * the parent hierarchy and requesting that the root view place new focus. 5991 * 5992 * @param propagate whether to propagate the change up through the parent 5993 * hierarchy 5994 * @param refocus when propagate is true, specifies whether to request the 5995 * root view place new focus 5996 */ 5997 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5998 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5999 mPrivateFlags &= ~PFLAG_FOCUSED; 6000 6001 if (propagate && mParent != null) { 6002 mParent.clearChildFocus(this); 6003 } 6004 6005 onFocusChanged(false, 0, null); 6006 refreshDrawableState(); 6007 6008 if (propagate && (!refocus || !rootViewRequestFocus())) { 6009 notifyGlobalFocusCleared(this); 6010 } 6011 } 6012 } 6013 6014 void notifyGlobalFocusCleared(View oldFocus) { 6015 if (oldFocus != null && mAttachInfo != null) { 6016 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6017 } 6018 } 6019 6020 boolean rootViewRequestFocus() { 6021 final View root = getRootView(); 6022 return root != null && root.requestFocus(); 6023 } 6024 6025 /** 6026 * Called internally by the view system when a new view is getting focus. 6027 * This is what clears the old focus. 6028 * <p> 6029 * <b>NOTE:</b> The parent view's focused child must be updated manually 6030 * after calling this method. Otherwise, the view hierarchy may be left in 6031 * an inconstent state. 6032 */ 6033 void unFocus(View focused) { 6034 if (DBG) { 6035 System.out.println(this + " unFocus()"); 6036 } 6037 6038 clearFocusInternal(focused, false, false); 6039 } 6040 6041 /** 6042 * Returns true if this view has focus itself, or is the ancestor of the 6043 * view that has focus. 6044 * 6045 * @return True if this view has or contains focus, false otherwise. 6046 */ 6047 @ViewDebug.ExportedProperty(category = "focus") 6048 public boolean hasFocus() { 6049 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6050 } 6051 6052 /** 6053 * Returns true if this view is focusable or if it contains a reachable View 6054 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 6055 * is a View whose parents do not block descendants focus. 6056 * 6057 * Only {@link #VISIBLE} views are considered focusable. 6058 * 6059 * @return True if the view is focusable or if the view contains a focusable 6060 * View, false otherwise. 6061 * 6062 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6063 * @see ViewGroup#getTouchscreenBlocksFocus() 6064 */ 6065 public boolean hasFocusable() { 6066 if (!isFocusableInTouchMode()) { 6067 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6068 final ViewGroup g = (ViewGroup) p; 6069 if (g.shouldBlockFocusForTouchscreen()) { 6070 return false; 6071 } 6072 } 6073 } 6074 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 6075 } 6076 6077 /** 6078 * Called by the view system when the focus state of this view changes. 6079 * When the focus change event is caused by directional navigation, direction 6080 * and previouslyFocusedRect provide insight into where the focus is coming from. 6081 * When overriding, be sure to call up through to the super class so that 6082 * the standard focus handling will occur. 6083 * 6084 * @param gainFocus True if the View has focus; false otherwise. 6085 * @param direction The direction focus has moved when requestFocus() 6086 * is called to give this view focus. Values are 6087 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6088 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6089 * It may not always apply, in which case use the default. 6090 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6091 * system, of the previously focused view. If applicable, this will be 6092 * passed in as finer grained information about where the focus is coming 6093 * from (in addition to direction). Will be <code>null</code> otherwise. 6094 */ 6095 @CallSuper 6096 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6097 @Nullable Rect previouslyFocusedRect) { 6098 if (gainFocus) { 6099 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6100 } else { 6101 notifyViewAccessibilityStateChangedIfNeeded( 6102 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6103 } 6104 6105 InputMethodManager imm = InputMethodManager.peekInstance(); 6106 if (!gainFocus) { 6107 if (isPressed()) { 6108 setPressed(false); 6109 } 6110 if (imm != null && mAttachInfo != null 6111 && mAttachInfo.mHasWindowFocus) { 6112 imm.focusOut(this); 6113 } 6114 onFocusLost(); 6115 } else if (imm != null && mAttachInfo != null 6116 && mAttachInfo.mHasWindowFocus) { 6117 imm.focusIn(this); 6118 } 6119 6120 invalidate(true); 6121 ListenerInfo li = mListenerInfo; 6122 if (li != null && li.mOnFocusChangeListener != null) { 6123 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6124 } 6125 6126 if (mAttachInfo != null) { 6127 mAttachInfo.mKeyDispatchState.reset(this); 6128 } 6129 } 6130 6131 /** 6132 * Sends an accessibility event of the given type. If accessibility is 6133 * not enabled this method has no effect. The default implementation calls 6134 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6135 * to populate information about the event source (this View), then calls 6136 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6137 * populate the text content of the event source including its descendants, 6138 * and last calls 6139 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6140 * on its parent to request sending of the event to interested parties. 6141 * <p> 6142 * If an {@link AccessibilityDelegate} has been specified via calling 6143 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6144 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6145 * responsible for handling this call. 6146 * </p> 6147 * 6148 * @param eventType The type of the event to send, as defined by several types from 6149 * {@link android.view.accessibility.AccessibilityEvent}, such as 6150 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6151 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6152 * 6153 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6154 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6155 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6156 * @see AccessibilityDelegate 6157 */ 6158 public void sendAccessibilityEvent(int eventType) { 6159 if (mAccessibilityDelegate != null) { 6160 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6161 } else { 6162 sendAccessibilityEventInternal(eventType); 6163 } 6164 } 6165 6166 /** 6167 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6168 * {@link AccessibilityEvent} to make an announcement which is related to some 6169 * sort of a context change for which none of the events representing UI transitions 6170 * is a good fit. For example, announcing a new page in a book. If accessibility 6171 * is not enabled this method does nothing. 6172 * 6173 * @param text The announcement text. 6174 */ 6175 public void announceForAccessibility(CharSequence text) { 6176 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6177 AccessibilityEvent event = AccessibilityEvent.obtain( 6178 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6179 onInitializeAccessibilityEvent(event); 6180 event.getText().add(text); 6181 event.setContentDescription(null); 6182 mParent.requestSendAccessibilityEvent(this, event); 6183 } 6184 } 6185 6186 /** 6187 * @see #sendAccessibilityEvent(int) 6188 * 6189 * Note: Called from the default {@link AccessibilityDelegate}. 6190 * 6191 * @hide 6192 */ 6193 public void sendAccessibilityEventInternal(int eventType) { 6194 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6195 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6196 } 6197 } 6198 6199 /** 6200 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6201 * takes as an argument an empty {@link AccessibilityEvent} and does not 6202 * perform a check whether accessibility is enabled. 6203 * <p> 6204 * If an {@link AccessibilityDelegate} has been specified via calling 6205 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6206 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6207 * is responsible for handling this call. 6208 * </p> 6209 * 6210 * @param event The event to send. 6211 * 6212 * @see #sendAccessibilityEvent(int) 6213 */ 6214 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6215 if (mAccessibilityDelegate != null) { 6216 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6217 } else { 6218 sendAccessibilityEventUncheckedInternal(event); 6219 } 6220 } 6221 6222 /** 6223 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6224 * 6225 * Note: Called from the default {@link AccessibilityDelegate}. 6226 * 6227 * @hide 6228 */ 6229 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6230 if (!isShown()) { 6231 return; 6232 } 6233 onInitializeAccessibilityEvent(event); 6234 // Only a subset of accessibility events populates text content. 6235 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6236 dispatchPopulateAccessibilityEvent(event); 6237 } 6238 // In the beginning we called #isShown(), so we know that getParent() is not null. 6239 getParent().requestSendAccessibilityEvent(this, event); 6240 } 6241 6242 /** 6243 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6244 * to its children for adding their text content to the event. Note that the 6245 * event text is populated in a separate dispatch path since we add to the 6246 * event not only the text of the source but also the text of all its descendants. 6247 * A typical implementation will call 6248 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6249 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6250 * on each child. Override this method if custom population of the event text 6251 * content is required. 6252 * <p> 6253 * If an {@link AccessibilityDelegate} has been specified via calling 6254 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6255 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6256 * is responsible for handling this call. 6257 * </p> 6258 * <p> 6259 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6260 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6261 * </p> 6262 * 6263 * @param event The event. 6264 * 6265 * @return True if the event population was completed. 6266 */ 6267 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6268 if (mAccessibilityDelegate != null) { 6269 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6270 } else { 6271 return dispatchPopulateAccessibilityEventInternal(event); 6272 } 6273 } 6274 6275 /** 6276 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6277 * 6278 * Note: Called from the default {@link AccessibilityDelegate}. 6279 * 6280 * @hide 6281 */ 6282 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6283 onPopulateAccessibilityEvent(event); 6284 return false; 6285 } 6286 6287 /** 6288 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6289 * giving a chance to this View to populate the accessibility event with its 6290 * text content. While this method is free to modify event 6291 * attributes other than text content, doing so should normally be performed in 6292 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 6293 * <p> 6294 * Example: Adding formatted date string to an accessibility event in addition 6295 * to the text added by the super implementation: 6296 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6297 * super.onPopulateAccessibilityEvent(event); 6298 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 6299 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 6300 * mCurrentDate.getTimeInMillis(), flags); 6301 * event.getText().add(selectedDateUtterance); 6302 * }</pre> 6303 * <p> 6304 * If an {@link AccessibilityDelegate} has been specified via calling 6305 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6306 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 6307 * is responsible for handling this call. 6308 * </p> 6309 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6310 * information to the event, in case the default implementation has basic information to add. 6311 * </p> 6312 * 6313 * @param event The accessibility event which to populate. 6314 * 6315 * @see #sendAccessibilityEvent(int) 6316 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6317 */ 6318 @CallSuper 6319 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 6320 if (mAccessibilityDelegate != null) { 6321 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 6322 } else { 6323 onPopulateAccessibilityEventInternal(event); 6324 } 6325 } 6326 6327 /** 6328 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 6329 * 6330 * Note: Called from the default {@link AccessibilityDelegate}. 6331 * 6332 * @hide 6333 */ 6334 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 6335 } 6336 6337 /** 6338 * Initializes an {@link AccessibilityEvent} with information about 6339 * this View which is the event source. In other words, the source of 6340 * an accessibility event is the view whose state change triggered firing 6341 * the event. 6342 * <p> 6343 * Example: Setting the password property of an event in addition 6344 * to properties set by the super implementation: 6345 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6346 * super.onInitializeAccessibilityEvent(event); 6347 * event.setPassword(true); 6348 * }</pre> 6349 * <p> 6350 * If an {@link AccessibilityDelegate} has been specified via calling 6351 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6352 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 6353 * is responsible for handling this call. 6354 * </p> 6355 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 6356 * information to the event, in case the default implementation has basic information to add. 6357 * </p> 6358 * @param event The event to initialize. 6359 * 6360 * @see #sendAccessibilityEvent(int) 6361 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6362 */ 6363 @CallSuper 6364 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 6365 if (mAccessibilityDelegate != null) { 6366 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 6367 } else { 6368 onInitializeAccessibilityEventInternal(event); 6369 } 6370 } 6371 6372 /** 6373 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6374 * 6375 * Note: Called from the default {@link AccessibilityDelegate}. 6376 * 6377 * @hide 6378 */ 6379 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 6380 event.setSource(this); 6381 event.setClassName(getAccessibilityClassName()); 6382 event.setPackageName(getContext().getPackageName()); 6383 event.setEnabled(isEnabled()); 6384 event.setContentDescription(mContentDescription); 6385 6386 switch (event.getEventType()) { 6387 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 6388 ArrayList<View> focusablesTempList = (mAttachInfo != null) 6389 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 6390 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 6391 event.setItemCount(focusablesTempList.size()); 6392 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 6393 if (mAttachInfo != null) { 6394 focusablesTempList.clear(); 6395 } 6396 } break; 6397 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 6398 CharSequence text = getIterableTextForAccessibility(); 6399 if (text != null && text.length() > 0) { 6400 event.setFromIndex(getAccessibilitySelectionStart()); 6401 event.setToIndex(getAccessibilitySelectionEnd()); 6402 event.setItemCount(text.length()); 6403 } 6404 } break; 6405 } 6406 } 6407 6408 /** 6409 * Returns an {@link AccessibilityNodeInfo} representing this view from the 6410 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 6411 * This method is responsible for obtaining an accessibility node info from a 6412 * pool of reusable instances and calling 6413 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 6414 * initialize the former. 6415 * <p> 6416 * Note: The client is responsible for recycling the obtained instance by calling 6417 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 6418 * </p> 6419 * 6420 * @return A populated {@link AccessibilityNodeInfo}. 6421 * 6422 * @see AccessibilityNodeInfo 6423 */ 6424 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 6425 if (mAccessibilityDelegate != null) { 6426 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 6427 } else { 6428 return createAccessibilityNodeInfoInternal(); 6429 } 6430 } 6431 6432 /** 6433 * @see #createAccessibilityNodeInfo() 6434 * 6435 * @hide 6436 */ 6437 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 6438 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6439 if (provider != null) { 6440 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 6441 } else { 6442 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 6443 onInitializeAccessibilityNodeInfo(info); 6444 return info; 6445 } 6446 } 6447 6448 /** 6449 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 6450 * The base implementation sets: 6451 * <ul> 6452 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 6453 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 6454 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 6455 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 6456 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 6457 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 6458 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 6459 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 6460 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 6461 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 6462 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 6463 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 6464 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 6465 * </ul> 6466 * <p> 6467 * Subclasses should override this method, call the super implementation, 6468 * and set additional attributes. 6469 * </p> 6470 * <p> 6471 * If an {@link AccessibilityDelegate} has been specified via calling 6472 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6473 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 6474 * is responsible for handling this call. 6475 * </p> 6476 * 6477 * @param info The instance to initialize. 6478 */ 6479 @CallSuper 6480 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 6481 if (mAccessibilityDelegate != null) { 6482 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 6483 } else { 6484 onInitializeAccessibilityNodeInfoInternal(info); 6485 } 6486 } 6487 6488 /** 6489 * Gets the location of this view in screen coordinates. 6490 * 6491 * @param outRect The output location 6492 * @hide 6493 */ 6494 public void getBoundsOnScreen(Rect outRect) { 6495 getBoundsOnScreen(outRect, false); 6496 } 6497 6498 /** 6499 * Gets the location of this view in screen coordinates. 6500 * 6501 * @param outRect The output location 6502 * @param clipToParent Whether to clip child bounds to the parent ones. 6503 * @hide 6504 */ 6505 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 6506 if (mAttachInfo == null) { 6507 return; 6508 } 6509 6510 RectF position = mAttachInfo.mTmpTransformRect; 6511 position.set(0, 0, mRight - mLeft, mBottom - mTop); 6512 6513 if (!hasIdentityMatrix()) { 6514 getMatrix().mapRect(position); 6515 } 6516 6517 position.offset(mLeft, mTop); 6518 6519 ViewParent parent = mParent; 6520 while (parent instanceof View) { 6521 View parentView = (View) parent; 6522 6523 position.offset(-parentView.mScrollX, -parentView.mScrollY); 6524 6525 if (clipToParent) { 6526 position.left = Math.max(position.left, 0); 6527 position.top = Math.max(position.top, 0); 6528 position.right = Math.min(position.right, parentView.getWidth()); 6529 position.bottom = Math.min(position.bottom, parentView.getHeight()); 6530 } 6531 6532 if (!parentView.hasIdentityMatrix()) { 6533 parentView.getMatrix().mapRect(position); 6534 } 6535 6536 position.offset(parentView.mLeft, parentView.mTop); 6537 6538 parent = parentView.mParent; 6539 } 6540 6541 if (parent instanceof ViewRootImpl) { 6542 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 6543 position.offset(0, -viewRootImpl.mCurScrollY); 6544 } 6545 6546 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 6547 6548 outRect.set(Math.round(position.left), Math.round(position.top), 6549 Math.round(position.right), Math.round(position.bottom)); 6550 } 6551 6552 /** 6553 * Return the class name of this object to be used for accessibility purposes. 6554 * Subclasses should only override this if they are implementing something that 6555 * should be seen as a completely new class of view when used by accessibility, 6556 * unrelated to the class it is deriving from. This is used to fill in 6557 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 6558 */ 6559 public CharSequence getAccessibilityClassName() { 6560 return View.class.getName(); 6561 } 6562 6563 /** 6564 * Called when assist structure is being retrieved from a view as part of 6565 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 6566 * @param structure Fill in with structured view data. The default implementation 6567 * fills in all data that can be inferred from the view itself. 6568 */ 6569 public void onProvideStructure(ViewStructure structure) { 6570 final int id = mID; 6571 if (id > 0 && (id&0xff000000) != 0 && (id&0x00ff0000) != 0 6572 && (id&0x0000ffff) != 0) { 6573 String pkg, type, entry; 6574 try { 6575 final Resources res = getResources(); 6576 entry = res.getResourceEntryName(id); 6577 type = res.getResourceTypeName(id); 6578 pkg = res.getResourcePackageName(id); 6579 } catch (Resources.NotFoundException e) { 6580 entry = type = pkg = null; 6581 } 6582 structure.setId(id, pkg, type, entry); 6583 } else { 6584 structure.setId(id, null, null, null); 6585 } 6586 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 6587 if (!hasIdentityMatrix()) { 6588 structure.setTransformation(getMatrix()); 6589 } 6590 structure.setElevation(getZ()); 6591 structure.setVisibility(getVisibility()); 6592 structure.setEnabled(isEnabled()); 6593 if (isClickable()) { 6594 structure.setClickable(true); 6595 } 6596 if (isFocusable()) { 6597 structure.setFocusable(true); 6598 } 6599 if (isFocused()) { 6600 structure.setFocused(true); 6601 } 6602 if (isAccessibilityFocused()) { 6603 structure.setAccessibilityFocused(true); 6604 } 6605 if (isSelected()) { 6606 structure.setSelected(true); 6607 } 6608 if (isActivated()) { 6609 structure.setActivated(true); 6610 } 6611 if (isLongClickable()) { 6612 structure.setLongClickable(true); 6613 } 6614 if (this instanceof Checkable) { 6615 structure.setCheckable(true); 6616 if (((Checkable)this).isChecked()) { 6617 structure.setChecked(true); 6618 } 6619 } 6620 if (isContextClickable()) { 6621 structure.setContextClickable(true); 6622 } 6623 structure.setClassName(getAccessibilityClassName().toString()); 6624 structure.setContentDescription(getContentDescription()); 6625 } 6626 6627 /** 6628 * Called when assist structure is being retrieved from a view as part of 6629 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 6630 * generate additional virtual structure under this view. The defaullt implementation 6631 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 6632 * view's virtual accessibility nodes, if any. You can override this for a more 6633 * optimal implementation providing this data. 6634 */ 6635 public void onProvideVirtualStructure(ViewStructure structure) { 6636 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 6637 if (provider != null) { 6638 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 6639 structure.setChildCount(1); 6640 ViewStructure root = structure.newChild(0); 6641 populateVirtualStructure(root, provider, info); 6642 info.recycle(); 6643 } 6644 } 6645 6646 private void populateVirtualStructure(ViewStructure structure, 6647 AccessibilityNodeProvider provider, AccessibilityNodeInfo info) { 6648 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 6649 null, null, null); 6650 Rect rect = structure.getTempRect(); 6651 info.getBoundsInParent(rect); 6652 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 6653 structure.setVisibility(VISIBLE); 6654 structure.setEnabled(info.isEnabled()); 6655 if (info.isClickable()) { 6656 structure.setClickable(true); 6657 } 6658 if (info.isFocusable()) { 6659 structure.setFocusable(true); 6660 } 6661 if (info.isFocused()) { 6662 structure.setFocused(true); 6663 } 6664 if (info.isAccessibilityFocused()) { 6665 structure.setAccessibilityFocused(true); 6666 } 6667 if (info.isSelected()) { 6668 structure.setSelected(true); 6669 } 6670 if (info.isLongClickable()) { 6671 structure.setLongClickable(true); 6672 } 6673 if (info.isCheckable()) { 6674 structure.setCheckable(true); 6675 if (info.isChecked()) { 6676 structure.setChecked(true); 6677 } 6678 } 6679 if (info.isContextClickable()) { 6680 structure.setContextClickable(true); 6681 } 6682 CharSequence cname = info.getClassName(); 6683 structure.setClassName(cname != null ? cname.toString() : null); 6684 structure.setContentDescription(info.getContentDescription()); 6685 if (info.getText() != null || info.getError() != null) { 6686 structure.setText(info.getText(), info.getTextSelectionStart(), 6687 info.getTextSelectionEnd()); 6688 } 6689 final int NCHILDREN = info.getChildCount(); 6690 if (NCHILDREN > 0) { 6691 structure.setChildCount(NCHILDREN); 6692 for (int i=0; i<NCHILDREN; i++) { 6693 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 6694 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 6695 ViewStructure child = structure.newChild(i); 6696 populateVirtualStructure(child, provider, cinfo); 6697 cinfo.recycle(); 6698 } 6699 } 6700 } 6701 6702 /** 6703 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 6704 * implementation calls {@link #onProvideStructure} and 6705 * {@link #onProvideVirtualStructure}. 6706 */ 6707 public void dispatchProvideStructure(ViewStructure structure) { 6708 if (!isAssistBlocked()) { 6709 onProvideStructure(structure); 6710 onProvideVirtualStructure(structure); 6711 } else { 6712 structure.setClassName(getAccessibilityClassName().toString()); 6713 structure.setAssistBlocked(true); 6714 } 6715 } 6716 6717 /** 6718 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 6719 * 6720 * Note: Called from the default {@link AccessibilityDelegate}. 6721 * 6722 * @hide 6723 */ 6724 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 6725 if (mAttachInfo == null) { 6726 return; 6727 } 6728 6729 Rect bounds = mAttachInfo.mTmpInvalRect; 6730 6731 getDrawingRect(bounds); 6732 info.setBoundsInParent(bounds); 6733 6734 getBoundsOnScreen(bounds, true); 6735 info.setBoundsInScreen(bounds); 6736 6737 ViewParent parent = getParentForAccessibility(); 6738 if (parent instanceof View) { 6739 info.setParent((View) parent); 6740 } 6741 6742 if (mID != View.NO_ID) { 6743 View rootView = getRootView(); 6744 if (rootView == null) { 6745 rootView = this; 6746 } 6747 6748 View label = rootView.findLabelForView(this, mID); 6749 if (label != null) { 6750 info.setLabeledBy(label); 6751 } 6752 6753 if ((mAttachInfo.mAccessibilityFetchFlags 6754 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 6755 && Resources.resourceHasPackage(mID)) { 6756 try { 6757 String viewId = getResources().getResourceName(mID); 6758 info.setViewIdResourceName(viewId); 6759 } catch (Resources.NotFoundException nfe) { 6760 /* ignore */ 6761 } 6762 } 6763 } 6764 6765 if (mLabelForId != View.NO_ID) { 6766 View rootView = getRootView(); 6767 if (rootView == null) { 6768 rootView = this; 6769 } 6770 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 6771 if (labeled != null) { 6772 info.setLabelFor(labeled); 6773 } 6774 } 6775 6776 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 6777 View rootView = getRootView(); 6778 if (rootView == null) { 6779 rootView = this; 6780 } 6781 View next = rootView.findViewInsideOutShouldExist(this, 6782 mAccessibilityTraversalBeforeId); 6783 if (next != null && next.includeForAccessibility()) { 6784 info.setTraversalBefore(next); 6785 } 6786 } 6787 6788 if (mAccessibilityTraversalAfterId != View.NO_ID) { 6789 View rootView = getRootView(); 6790 if (rootView == null) { 6791 rootView = this; 6792 } 6793 View next = rootView.findViewInsideOutShouldExist(this, 6794 mAccessibilityTraversalAfterId); 6795 if (next != null && next.includeForAccessibility()) { 6796 info.setTraversalAfter(next); 6797 } 6798 } 6799 6800 info.setVisibleToUser(isVisibleToUser()); 6801 6802 if ((mAttachInfo != null) && ((mAttachInfo.mAccessibilityFetchFlags 6803 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0)) { 6804 info.setImportantForAccessibility(isImportantForAccessibility()); 6805 } else { 6806 info.setImportantForAccessibility(true); 6807 } 6808 6809 info.setPackageName(mContext.getPackageName()); 6810 info.setClassName(getAccessibilityClassName()); 6811 info.setContentDescription(getContentDescription()); 6812 6813 info.setEnabled(isEnabled()); 6814 info.setClickable(isClickable()); 6815 info.setFocusable(isFocusable()); 6816 info.setFocused(isFocused()); 6817 info.setAccessibilityFocused(isAccessibilityFocused()); 6818 info.setSelected(isSelected()); 6819 info.setLongClickable(isLongClickable()); 6820 info.setContextClickable(isContextClickable()); 6821 info.setLiveRegion(getAccessibilityLiveRegion()); 6822 6823 // TODO: These make sense only if we are in an AdapterView but all 6824 // views can be selected. Maybe from accessibility perspective 6825 // we should report as selectable view in an AdapterView. 6826 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 6827 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 6828 6829 if (isFocusable()) { 6830 if (isFocused()) { 6831 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 6832 } else { 6833 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 6834 } 6835 } 6836 6837 if (!isAccessibilityFocused()) { 6838 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 6839 } else { 6840 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 6841 } 6842 6843 if (isClickable() && isEnabled()) { 6844 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 6845 } 6846 6847 if (isLongClickable() && isEnabled()) { 6848 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 6849 } 6850 6851 if (isContextClickable() && isEnabled()) { 6852 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 6853 } 6854 6855 CharSequence text = getIterableTextForAccessibility(); 6856 if (text != null && text.length() > 0) { 6857 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 6858 6859 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 6860 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 6861 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 6862 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 6863 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 6864 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 6865 } 6866 6867 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 6868 populateAccessibilityNodeInfoDrawingOrderInParent(info); 6869 } 6870 6871 /** 6872 * Determine the order in which this view will be drawn relative to its siblings for a11y 6873 * 6874 * @param info The info whose drawing order should be populated 6875 */ 6876 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 6877 int drawingOrderInParent = 1; 6878 // Iterate up the hierarchy if parents are not important for a11y 6879 View viewAtDrawingLevel = this; 6880 final ViewParent parent = getParentForAccessibility(); 6881 while (viewAtDrawingLevel != parent) { 6882 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 6883 if (!(currentParent instanceof ViewGroup)) { 6884 // Should only happen for the Decor 6885 drawingOrderInParent = 0; 6886 break; 6887 } else { 6888 final ViewGroup parentGroup = (ViewGroup) currentParent; 6889 final int childCount = parentGroup.getChildCount(); 6890 if (childCount > 1) { 6891 List<View> preorderedList = parentGroup.buildOrderedChildList(); 6892 if (preorderedList != null) { 6893 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 6894 for (int i = 0; i < childDrawIndex; i++) { 6895 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 6896 } 6897 } else { 6898 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 6899 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 6900 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 6901 .getChildDrawingOrder(childCount, childIndex) : childIndex; 6902 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 6903 if (childDrawIndex != 0) { 6904 for (int i = 0; i < numChildrenToIterate; i++) { 6905 final int otherDrawIndex = (customOrder ? 6906 parentGroup.getChildDrawingOrder(childCount, i) : i); 6907 if (otherDrawIndex < childDrawIndex) { 6908 drawingOrderInParent += 6909 numViewsForAccessibility(parentGroup.getChildAt(i)); 6910 } 6911 } 6912 } 6913 } 6914 } 6915 } 6916 viewAtDrawingLevel = (View) currentParent; 6917 } 6918 info.setDrawingOrder(drawingOrderInParent); 6919 } 6920 6921 private static int numViewsForAccessibility(View view) { 6922 if (view != null) { 6923 if (view.includeForAccessibility()) { 6924 return 1; 6925 } else if (view instanceof ViewGroup) { 6926 return ((ViewGroup) view).getNumChildrenForAccessibility(); 6927 } 6928 } 6929 return 0; 6930 } 6931 6932 private View findLabelForView(View view, int labeledId) { 6933 if (mMatchLabelForPredicate == null) { 6934 mMatchLabelForPredicate = new MatchLabelForPredicate(); 6935 } 6936 mMatchLabelForPredicate.mLabeledId = labeledId; 6937 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 6938 } 6939 6940 /** 6941 * Computes whether this view is visible to the user. Such a view is 6942 * attached, visible, all its predecessors are visible, it is not clipped 6943 * entirely by its predecessors, and has an alpha greater than zero. 6944 * 6945 * @return Whether the view is visible on the screen. 6946 * 6947 * @hide 6948 */ 6949 protected boolean isVisibleToUser() { 6950 return isVisibleToUser(null); 6951 } 6952 6953 /** 6954 * Computes whether the given portion of this view is visible to the user. 6955 * Such a view is attached, visible, all its predecessors are visible, 6956 * has an alpha greater than zero, and the specified portion is not 6957 * clipped entirely by its predecessors. 6958 * 6959 * @param boundInView the portion of the view to test; coordinates should be relative; may be 6960 * <code>null</code>, and the entire view will be tested in this case. 6961 * When <code>true</code> is returned by the function, the actual visible 6962 * region will be stored in this parameter; that is, if boundInView is fully 6963 * contained within the view, no modification will be made, otherwise regions 6964 * outside of the visible area of the view will be clipped. 6965 * 6966 * @return Whether the specified portion of the view is visible on the screen. 6967 * 6968 * @hide 6969 */ 6970 protected boolean isVisibleToUser(Rect boundInView) { 6971 if (mAttachInfo != null) { 6972 // Attached to invisible window means this view is not visible. 6973 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 6974 return false; 6975 } 6976 // An invisible predecessor or one with alpha zero means 6977 // that this view is not visible to the user. 6978 Object current = this; 6979 while (current instanceof View) { 6980 View view = (View) current; 6981 // We have attach info so this view is attached and there is no 6982 // need to check whether we reach to ViewRootImpl on the way up. 6983 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 6984 view.getVisibility() != VISIBLE) { 6985 return false; 6986 } 6987 current = view.mParent; 6988 } 6989 // Check if the view is entirely covered by its predecessors. 6990 Rect visibleRect = mAttachInfo.mTmpInvalRect; 6991 Point offset = mAttachInfo.mPoint; 6992 if (!getGlobalVisibleRect(visibleRect, offset)) { 6993 return false; 6994 } 6995 // Check if the visible portion intersects the rectangle of interest. 6996 if (boundInView != null) { 6997 visibleRect.offset(-offset.x, -offset.y); 6998 return boundInView.intersect(visibleRect); 6999 } 7000 return true; 7001 } 7002 return false; 7003 } 7004 7005 /** 7006 * Returns the delegate for implementing accessibility support via 7007 * composition. For more details see {@link AccessibilityDelegate}. 7008 * 7009 * @return The delegate, or null if none set. 7010 * 7011 * @hide 7012 */ 7013 public AccessibilityDelegate getAccessibilityDelegate() { 7014 return mAccessibilityDelegate; 7015 } 7016 7017 /** 7018 * Sets a delegate for implementing accessibility support via composition 7019 * (as opposed to inheritance). For more details, see 7020 * {@link AccessibilityDelegate}. 7021 * <p> 7022 * <strong>Note:</strong> On platform versions prior to 7023 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7024 * views in the {@code android.widget.*} package are called <i>before</i> 7025 * host methods. This prevents certain properties such as class name from 7026 * being modified by overriding 7027 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7028 * as any changes will be overwritten by the host class. 7029 * <p> 7030 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7031 * methods are called <i>after</i> host methods, which all properties to be 7032 * modified without being overwritten by the host class. 7033 * 7034 * @param delegate the object to which accessibility method calls should be 7035 * delegated 7036 * @see AccessibilityDelegate 7037 */ 7038 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7039 mAccessibilityDelegate = delegate; 7040 } 7041 7042 /** 7043 * Gets the provider for managing a virtual view hierarchy rooted at this View 7044 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7045 * that explore the window content. 7046 * <p> 7047 * If this method returns an instance, this instance is responsible for managing 7048 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7049 * View including the one representing the View itself. Similarly the returned 7050 * instance is responsible for performing accessibility actions on any virtual 7051 * view or the root view itself. 7052 * </p> 7053 * <p> 7054 * If an {@link AccessibilityDelegate} has been specified via calling 7055 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7056 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7057 * is responsible for handling this call. 7058 * </p> 7059 * 7060 * @return The provider. 7061 * 7062 * @see AccessibilityNodeProvider 7063 */ 7064 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7065 if (mAccessibilityDelegate != null) { 7066 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7067 } else { 7068 return null; 7069 } 7070 } 7071 7072 /** 7073 * Gets the unique identifier of this view on the screen for accessibility purposes. 7074 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 7075 * 7076 * @return The view accessibility id. 7077 * 7078 * @hide 7079 */ 7080 public int getAccessibilityViewId() { 7081 if (mAccessibilityViewId == NO_ID) { 7082 mAccessibilityViewId = sNextAccessibilityViewId++; 7083 } 7084 return mAccessibilityViewId; 7085 } 7086 7087 /** 7088 * Gets the unique identifier of the window in which this View reseides. 7089 * 7090 * @return The window accessibility id. 7091 * 7092 * @hide 7093 */ 7094 public int getAccessibilityWindowId() { 7095 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7096 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7097 } 7098 7099 /** 7100 * Returns the {@link View}'s content description. 7101 * <p> 7102 * <strong>Note:</strong> Do not override this method, as it will have no 7103 * effect on the content description presented to accessibility services. 7104 * You must call {@link #setContentDescription(CharSequence)} to modify the 7105 * content description. 7106 * 7107 * @return the content description 7108 * @see #setContentDescription(CharSequence) 7109 * @attr ref android.R.styleable#View_contentDescription 7110 */ 7111 @ViewDebug.ExportedProperty(category = "accessibility") 7112 public CharSequence getContentDescription() { 7113 return mContentDescription; 7114 } 7115 7116 /** 7117 * Sets the {@link View}'s content description. 7118 * <p> 7119 * A content description briefly describes the view and is primarily used 7120 * for accessibility support to determine how a view should be presented to 7121 * the user. In the case of a view with no textual representation, such as 7122 * {@link android.widget.ImageButton}, a useful content description 7123 * explains what the view does. For example, an image button with a phone 7124 * icon that is used to place a call may use "Call" as its content 7125 * description. An image of a floppy disk that is used to save a file may 7126 * use "Save". 7127 * 7128 * @param contentDescription The content description. 7129 * @see #getContentDescription() 7130 * @attr ref android.R.styleable#View_contentDescription 7131 */ 7132 @RemotableViewMethod 7133 public void setContentDescription(CharSequence contentDescription) { 7134 if (mContentDescription == null) { 7135 if (contentDescription == null) { 7136 return; 7137 } 7138 } else if (mContentDescription.equals(contentDescription)) { 7139 return; 7140 } 7141 mContentDescription = contentDescription; 7142 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7143 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7144 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7145 notifySubtreeAccessibilityStateChangedIfNeeded(); 7146 } else { 7147 notifyViewAccessibilityStateChangedIfNeeded( 7148 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7149 } 7150 } 7151 7152 /** 7153 * Sets the id of a view before which this one is visited in accessibility traversal. 7154 * A screen-reader must visit the content of this view before the content of the one 7155 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7156 * will traverse the entire content of B before traversing the entire content of A, 7157 * regardles of what traversal strategy it is using. 7158 * <p> 7159 * Views that do not have specified before/after relationships are traversed in order 7160 * determined by the screen-reader. 7161 * </p> 7162 * <p> 7163 * Setting that this view is before a view that is not important for accessibility 7164 * or if this view is not important for accessibility will have no effect as the 7165 * screen-reader is not aware of unimportant views. 7166 * </p> 7167 * 7168 * @param beforeId The id of a view this one precedes in accessibility traversal. 7169 * 7170 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7171 * 7172 * @see #setImportantForAccessibility(int) 7173 */ 7174 @RemotableViewMethod 7175 public void setAccessibilityTraversalBefore(int beforeId) { 7176 if (mAccessibilityTraversalBeforeId == beforeId) { 7177 return; 7178 } 7179 mAccessibilityTraversalBeforeId = beforeId; 7180 notifyViewAccessibilityStateChangedIfNeeded( 7181 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7182 } 7183 7184 /** 7185 * Gets the id of a view before which this one is visited in accessibility traversal. 7186 * 7187 * @return The id of a view this one precedes in accessibility traversal if 7188 * specified, otherwise {@link #NO_ID}. 7189 * 7190 * @see #setAccessibilityTraversalBefore(int) 7191 */ 7192 public int getAccessibilityTraversalBefore() { 7193 return mAccessibilityTraversalBeforeId; 7194 } 7195 7196 /** 7197 * Sets the id of a view after which this one is visited in accessibility traversal. 7198 * A screen-reader must visit the content of the other view before the content of this 7199 * one. For example, if view B is set to be after view A, then a screen-reader 7200 * will traverse the entire content of A before traversing the entire content of B, 7201 * regardles of what traversal strategy it is using. 7202 * <p> 7203 * Views that do not have specified before/after relationships are traversed in order 7204 * determined by the screen-reader. 7205 * </p> 7206 * <p> 7207 * Setting that this view is after a view that is not important for accessibility 7208 * or if this view is not important for accessibility will have no effect as the 7209 * screen-reader is not aware of unimportant views. 7210 * </p> 7211 * 7212 * @param afterId The id of a view this one succedees in accessibility traversal. 7213 * 7214 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7215 * 7216 * @see #setImportantForAccessibility(int) 7217 */ 7218 @RemotableViewMethod 7219 public void setAccessibilityTraversalAfter(int afterId) { 7220 if (mAccessibilityTraversalAfterId == afterId) { 7221 return; 7222 } 7223 mAccessibilityTraversalAfterId = afterId; 7224 notifyViewAccessibilityStateChangedIfNeeded( 7225 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7226 } 7227 7228 /** 7229 * Gets the id of a view after which this one is visited in accessibility traversal. 7230 * 7231 * @return The id of a view this one succeedes in accessibility traversal if 7232 * specified, otherwise {@link #NO_ID}. 7233 * 7234 * @see #setAccessibilityTraversalAfter(int) 7235 */ 7236 public int getAccessibilityTraversalAfter() { 7237 return mAccessibilityTraversalAfterId; 7238 } 7239 7240 /** 7241 * Gets the id of a view for which this view serves as a label for 7242 * accessibility purposes. 7243 * 7244 * @return The labeled view id. 7245 */ 7246 @ViewDebug.ExportedProperty(category = "accessibility") 7247 public int getLabelFor() { 7248 return mLabelForId; 7249 } 7250 7251 /** 7252 * Sets the id of a view for which this view serves as a label for 7253 * accessibility purposes. 7254 * 7255 * @param id The labeled view id. 7256 */ 7257 @RemotableViewMethod 7258 public void setLabelFor(@IdRes int id) { 7259 if (mLabelForId == id) { 7260 return; 7261 } 7262 mLabelForId = id; 7263 if (mLabelForId != View.NO_ID 7264 && mID == View.NO_ID) { 7265 mID = generateViewId(); 7266 } 7267 notifyViewAccessibilityStateChangedIfNeeded( 7268 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7269 } 7270 7271 /** 7272 * Invoked whenever this view loses focus, either by losing window focus or by losing 7273 * focus within its window. This method can be used to clear any state tied to the 7274 * focus. For instance, if a button is held pressed with the trackball and the window 7275 * loses focus, this method can be used to cancel the press. 7276 * 7277 * Subclasses of View overriding this method should always call super.onFocusLost(). 7278 * 7279 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7280 * @see #onWindowFocusChanged(boolean) 7281 * 7282 * @hide pending API council approval 7283 */ 7284 @CallSuper 7285 protected void onFocusLost() { 7286 resetPressedState(); 7287 } 7288 7289 private void resetPressedState() { 7290 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7291 return; 7292 } 7293 7294 if (isPressed()) { 7295 setPressed(false); 7296 7297 if (!mHasPerformedLongPress) { 7298 removeLongPressCallback(); 7299 } 7300 } 7301 } 7302 7303 /** 7304 * Returns true if this view has focus 7305 * 7306 * @return True if this view has focus, false otherwise. 7307 */ 7308 @ViewDebug.ExportedProperty(category = "focus") 7309 public boolean isFocused() { 7310 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7311 } 7312 7313 /** 7314 * Find the view in the hierarchy rooted at this view that currently has 7315 * focus. 7316 * 7317 * @return The view that currently has focus, or null if no focused view can 7318 * be found. 7319 */ 7320 public View findFocus() { 7321 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7322 } 7323 7324 /** 7325 * Indicates whether this view is one of the set of scrollable containers in 7326 * its window. 7327 * 7328 * @return whether this view is one of the set of scrollable containers in 7329 * its window 7330 * 7331 * @attr ref android.R.styleable#View_isScrollContainer 7332 */ 7333 public boolean isScrollContainer() { 7334 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7335 } 7336 7337 /** 7338 * Change whether this view is one of the set of scrollable containers in 7339 * its window. This will be used to determine whether the window can 7340 * resize or must pan when a soft input area is open -- scrollable 7341 * containers allow the window to use resize mode since the container 7342 * will appropriately shrink. 7343 * 7344 * @attr ref android.R.styleable#View_isScrollContainer 7345 */ 7346 public void setScrollContainer(boolean isScrollContainer) { 7347 if (isScrollContainer) { 7348 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7349 mAttachInfo.mScrollContainers.add(this); 7350 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7351 } 7352 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7353 } else { 7354 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7355 mAttachInfo.mScrollContainers.remove(this); 7356 } 7357 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7358 } 7359 } 7360 7361 /** 7362 * Returns the quality of the drawing cache. 7363 * 7364 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7365 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7366 * 7367 * @see #setDrawingCacheQuality(int) 7368 * @see #setDrawingCacheEnabled(boolean) 7369 * @see #isDrawingCacheEnabled() 7370 * 7371 * @attr ref android.R.styleable#View_drawingCacheQuality 7372 */ 7373 @DrawingCacheQuality 7374 public int getDrawingCacheQuality() { 7375 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7376 } 7377 7378 /** 7379 * Set the drawing cache quality of this view. This value is used only when the 7380 * drawing cache is enabled 7381 * 7382 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7383 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7384 * 7385 * @see #getDrawingCacheQuality() 7386 * @see #setDrawingCacheEnabled(boolean) 7387 * @see #isDrawingCacheEnabled() 7388 * 7389 * @attr ref android.R.styleable#View_drawingCacheQuality 7390 */ 7391 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7392 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7393 } 7394 7395 /** 7396 * Returns whether the screen should remain on, corresponding to the current 7397 * value of {@link #KEEP_SCREEN_ON}. 7398 * 7399 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7400 * 7401 * @see #setKeepScreenOn(boolean) 7402 * 7403 * @attr ref android.R.styleable#View_keepScreenOn 7404 */ 7405 public boolean getKeepScreenOn() { 7406 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7407 } 7408 7409 /** 7410 * Controls whether the screen should remain on, modifying the 7411 * value of {@link #KEEP_SCREEN_ON}. 7412 * 7413 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7414 * 7415 * @see #getKeepScreenOn() 7416 * 7417 * @attr ref android.R.styleable#View_keepScreenOn 7418 */ 7419 public void setKeepScreenOn(boolean keepScreenOn) { 7420 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7421 } 7422 7423 /** 7424 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7425 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7426 * 7427 * @attr ref android.R.styleable#View_nextFocusLeft 7428 */ 7429 public int getNextFocusLeftId() { 7430 return mNextFocusLeftId; 7431 } 7432 7433 /** 7434 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7435 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7436 * decide automatically. 7437 * 7438 * @attr ref android.R.styleable#View_nextFocusLeft 7439 */ 7440 public void setNextFocusLeftId(int nextFocusLeftId) { 7441 mNextFocusLeftId = nextFocusLeftId; 7442 } 7443 7444 /** 7445 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7446 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7447 * 7448 * @attr ref android.R.styleable#View_nextFocusRight 7449 */ 7450 public int getNextFocusRightId() { 7451 return mNextFocusRightId; 7452 } 7453 7454 /** 7455 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7456 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7457 * decide automatically. 7458 * 7459 * @attr ref android.R.styleable#View_nextFocusRight 7460 */ 7461 public void setNextFocusRightId(int nextFocusRightId) { 7462 mNextFocusRightId = nextFocusRightId; 7463 } 7464 7465 /** 7466 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7467 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7468 * 7469 * @attr ref android.R.styleable#View_nextFocusUp 7470 */ 7471 public int getNextFocusUpId() { 7472 return mNextFocusUpId; 7473 } 7474 7475 /** 7476 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7477 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7478 * decide automatically. 7479 * 7480 * @attr ref android.R.styleable#View_nextFocusUp 7481 */ 7482 public void setNextFocusUpId(int nextFocusUpId) { 7483 mNextFocusUpId = nextFocusUpId; 7484 } 7485 7486 /** 7487 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7488 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7489 * 7490 * @attr ref android.R.styleable#View_nextFocusDown 7491 */ 7492 public int getNextFocusDownId() { 7493 return mNextFocusDownId; 7494 } 7495 7496 /** 7497 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7498 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7499 * decide automatically. 7500 * 7501 * @attr ref android.R.styleable#View_nextFocusDown 7502 */ 7503 public void setNextFocusDownId(int nextFocusDownId) { 7504 mNextFocusDownId = nextFocusDownId; 7505 } 7506 7507 /** 7508 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7509 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7510 * 7511 * @attr ref android.R.styleable#View_nextFocusForward 7512 */ 7513 public int getNextFocusForwardId() { 7514 return mNextFocusForwardId; 7515 } 7516 7517 /** 7518 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7519 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7520 * decide automatically. 7521 * 7522 * @attr ref android.R.styleable#View_nextFocusForward 7523 */ 7524 public void setNextFocusForwardId(int nextFocusForwardId) { 7525 mNextFocusForwardId = nextFocusForwardId; 7526 } 7527 7528 /** 7529 * Returns the visibility of this view and all of its ancestors 7530 * 7531 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7532 */ 7533 public boolean isShown() { 7534 View current = this; 7535 //noinspection ConstantConditions 7536 do { 7537 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7538 return false; 7539 } 7540 ViewParent parent = current.mParent; 7541 if (parent == null) { 7542 return false; // We are not attached to the view root 7543 } 7544 if (!(parent instanceof View)) { 7545 return true; 7546 } 7547 current = (View) parent; 7548 } while (current != null); 7549 7550 return false; 7551 } 7552 7553 /** 7554 * Called by the view hierarchy when the content insets for a window have 7555 * changed, to allow it to adjust its content to fit within those windows. 7556 * The content insets tell you the space that the status bar, input method, 7557 * and other system windows infringe on the application's window. 7558 * 7559 * <p>You do not normally need to deal with this function, since the default 7560 * window decoration given to applications takes care of applying it to the 7561 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7562 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7563 * and your content can be placed under those system elements. You can then 7564 * use this method within your view hierarchy if you have parts of your UI 7565 * which you would like to ensure are not being covered. 7566 * 7567 * <p>The default implementation of this method simply applies the content 7568 * insets to the view's padding, consuming that content (modifying the 7569 * insets to be 0), and returning true. This behavior is off by default, but can 7570 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7571 * 7572 * <p>This function's traversal down the hierarchy is depth-first. The same content 7573 * insets object is propagated down the hierarchy, so any changes made to it will 7574 * be seen by all following views (including potentially ones above in 7575 * the hierarchy since this is a depth-first traversal). The first view 7576 * that returns true will abort the entire traversal. 7577 * 7578 * <p>The default implementation works well for a situation where it is 7579 * used with a container that covers the entire window, allowing it to 7580 * apply the appropriate insets to its content on all edges. If you need 7581 * a more complicated layout (such as two different views fitting system 7582 * windows, one on the top of the window, and one on the bottom), 7583 * you can override the method and handle the insets however you would like. 7584 * Note that the insets provided by the framework are always relative to the 7585 * far edges of the window, not accounting for the location of the called view 7586 * within that window. (In fact when this method is called you do not yet know 7587 * where the layout will place the view, as it is done before layout happens.) 7588 * 7589 * <p>Note: unlike many View methods, there is no dispatch phase to this 7590 * call. If you are overriding it in a ViewGroup and want to allow the 7591 * call to continue to your children, you must be sure to call the super 7592 * implementation. 7593 * 7594 * <p>Here is a sample layout that makes use of fitting system windows 7595 * to have controls for a video view placed inside of the window decorations 7596 * that it hides and shows. This can be used with code like the second 7597 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7598 * 7599 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7600 * 7601 * @param insets Current content insets of the window. Prior to 7602 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7603 * the insets or else you and Android will be unhappy. 7604 * 7605 * @return {@code true} if this view applied the insets and it should not 7606 * continue propagating further down the hierarchy, {@code false} otherwise. 7607 * @see #getFitsSystemWindows() 7608 * @see #setFitsSystemWindows(boolean) 7609 * @see #setSystemUiVisibility(int) 7610 * 7611 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7612 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7613 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7614 * to implement handling their own insets. 7615 */ 7616 protected boolean fitSystemWindows(Rect insets) { 7617 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7618 if (insets == null) { 7619 // Null insets by definition have already been consumed. 7620 // This call cannot apply insets since there are none to apply, 7621 // so return false. 7622 return false; 7623 } 7624 // If we're not in the process of dispatching the newer apply insets call, 7625 // that means we're not in the compatibility path. Dispatch into the newer 7626 // apply insets path and take things from there. 7627 try { 7628 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7629 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7630 } finally { 7631 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7632 } 7633 } else { 7634 // We're being called from the newer apply insets path. 7635 // Perform the standard fallback behavior. 7636 return fitSystemWindowsInt(insets); 7637 } 7638 } 7639 7640 private boolean fitSystemWindowsInt(Rect insets) { 7641 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7642 mUserPaddingStart = UNDEFINED_PADDING; 7643 mUserPaddingEnd = UNDEFINED_PADDING; 7644 Rect localInsets = sThreadLocal.get(); 7645 if (localInsets == null) { 7646 localInsets = new Rect(); 7647 sThreadLocal.set(localInsets); 7648 } 7649 boolean res = computeFitSystemWindows(insets, localInsets); 7650 mUserPaddingLeftInitial = localInsets.left; 7651 mUserPaddingRightInitial = localInsets.right; 7652 internalSetPadding(localInsets.left, localInsets.top, 7653 localInsets.right, localInsets.bottom); 7654 return res; 7655 } 7656 return false; 7657 } 7658 7659 /** 7660 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7661 * 7662 * <p>This method should be overridden by views that wish to apply a policy different from or 7663 * in addition to the default behavior. Clients that wish to force a view subtree 7664 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7665 * 7666 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7667 * it will be called during dispatch instead of this method. The listener may optionally 7668 * call this method from its own implementation if it wishes to apply the view's default 7669 * insets policy in addition to its own.</p> 7670 * 7671 * <p>Implementations of this method should either return the insets parameter unchanged 7672 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7673 * that this view applied itself. This allows new inset types added in future platform 7674 * versions to pass through existing implementations unchanged without being erroneously 7675 * consumed.</p> 7676 * 7677 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7678 * property is set then the view will consume the system window insets and apply them 7679 * as padding for the view.</p> 7680 * 7681 * @param insets Insets to apply 7682 * @return The supplied insets with any applied insets consumed 7683 */ 7684 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7685 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7686 // We weren't called from within a direct call to fitSystemWindows, 7687 // call into it as a fallback in case we're in a class that overrides it 7688 // and has logic to perform. 7689 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7690 return insets.consumeSystemWindowInsets(); 7691 } 7692 } else { 7693 // We were called from within a direct call to fitSystemWindows. 7694 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7695 return insets.consumeSystemWindowInsets(); 7696 } 7697 } 7698 return insets; 7699 } 7700 7701 /** 7702 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7703 * window insets to this view. The listener's 7704 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7705 * method will be called instead of the view's 7706 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7707 * 7708 * @param listener Listener to set 7709 * 7710 * @see #onApplyWindowInsets(WindowInsets) 7711 */ 7712 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7713 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7714 } 7715 7716 /** 7717 * Request to apply the given window insets to this view or another view in its subtree. 7718 * 7719 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7720 * obscured by window decorations or overlays. This can include the status and navigation bars, 7721 * action bars, input methods and more. New inset categories may be added in the future. 7722 * The method returns the insets provided minus any that were applied by this view or its 7723 * children.</p> 7724 * 7725 * <p>Clients wishing to provide custom behavior should override the 7726 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7727 * {@link OnApplyWindowInsetsListener} via the 7728 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7729 * method.</p> 7730 * 7731 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7732 * </p> 7733 * 7734 * @param insets Insets to apply 7735 * @return The provided insets minus the insets that were consumed 7736 */ 7737 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7738 try { 7739 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7740 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7741 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7742 } else { 7743 return onApplyWindowInsets(insets); 7744 } 7745 } finally { 7746 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7747 } 7748 } 7749 7750 /** 7751 * Compute the view's coordinate within the surface. 7752 * 7753 * <p>Computes the coordinates of this view in its surface. The argument 7754 * must be an array of two integers. After the method returns, the array 7755 * contains the x and y location in that order.</p> 7756 * @hide 7757 * @param location an array of two integers in which to hold the coordinates 7758 */ 7759 public void getLocationInSurface(@Size(2) int[] location) { 7760 getLocationInWindow(location); 7761 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7762 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7763 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7764 } 7765 } 7766 7767 /** 7768 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7769 * only available if the view is attached. 7770 * 7771 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7772 */ 7773 public WindowInsets getRootWindowInsets() { 7774 if (mAttachInfo != null) { 7775 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7776 } 7777 return null; 7778 } 7779 7780 /** 7781 * @hide Compute the insets that should be consumed by this view and the ones 7782 * that should propagate to those under it. 7783 */ 7784 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7785 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7786 || mAttachInfo == null 7787 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7788 && !mAttachInfo.mOverscanRequested)) { 7789 outLocalInsets.set(inoutInsets); 7790 inoutInsets.set(0, 0, 0, 0); 7791 return true; 7792 } else { 7793 // The application wants to take care of fitting system window for 7794 // the content... however we still need to take care of any overscan here. 7795 final Rect overscan = mAttachInfo.mOverscanInsets; 7796 outLocalInsets.set(overscan); 7797 inoutInsets.left -= overscan.left; 7798 inoutInsets.top -= overscan.top; 7799 inoutInsets.right -= overscan.right; 7800 inoutInsets.bottom -= overscan.bottom; 7801 return false; 7802 } 7803 } 7804 7805 /** 7806 * Compute insets that should be consumed by this view and the ones that should propagate 7807 * to those under it. 7808 * 7809 * @param in Insets currently being processed by this View, likely received as a parameter 7810 * to {@link #onApplyWindowInsets(WindowInsets)}. 7811 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7812 * by this view 7813 * @return Insets that should be passed along to views under this one 7814 */ 7815 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7816 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7817 || mAttachInfo == null 7818 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7819 outLocalInsets.set(in.getSystemWindowInsets()); 7820 return in.consumeSystemWindowInsets(); 7821 } else { 7822 outLocalInsets.set(0, 0, 0, 0); 7823 return in; 7824 } 7825 } 7826 7827 /** 7828 * Sets whether or not this view should account for system screen decorations 7829 * such as the status bar and inset its content; that is, controlling whether 7830 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7831 * executed. See that method for more details. 7832 * 7833 * <p>Note that if you are providing your own implementation of 7834 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7835 * flag to true -- your implementation will be overriding the default 7836 * implementation that checks this flag. 7837 * 7838 * @param fitSystemWindows If true, then the default implementation of 7839 * {@link #fitSystemWindows(Rect)} will be executed. 7840 * 7841 * @attr ref android.R.styleable#View_fitsSystemWindows 7842 * @see #getFitsSystemWindows() 7843 * @see #fitSystemWindows(Rect) 7844 * @see #setSystemUiVisibility(int) 7845 */ 7846 public void setFitsSystemWindows(boolean fitSystemWindows) { 7847 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7848 } 7849 7850 /** 7851 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7852 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7853 * will be executed. 7854 * 7855 * @return {@code true} if the default implementation of 7856 * {@link #fitSystemWindows(Rect)} will be executed. 7857 * 7858 * @attr ref android.R.styleable#View_fitsSystemWindows 7859 * @see #setFitsSystemWindows(boolean) 7860 * @see #fitSystemWindows(Rect) 7861 * @see #setSystemUiVisibility(int) 7862 */ 7863 @ViewDebug.ExportedProperty 7864 public boolean getFitsSystemWindows() { 7865 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7866 } 7867 7868 /** @hide */ 7869 public boolean fitsSystemWindows() { 7870 return getFitsSystemWindows(); 7871 } 7872 7873 /** 7874 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7875 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7876 */ 7877 public void requestFitSystemWindows() { 7878 if (mParent != null) { 7879 mParent.requestFitSystemWindows(); 7880 } 7881 } 7882 7883 /** 7884 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7885 */ 7886 public void requestApplyInsets() { 7887 requestFitSystemWindows(); 7888 } 7889 7890 /** 7891 * For use by PhoneWindow to make its own system window fitting optional. 7892 * @hide 7893 */ 7894 public void makeOptionalFitsSystemWindows() { 7895 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 7896 } 7897 7898 /** 7899 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 7900 * treat them as such. 7901 * @hide 7902 */ 7903 public void getOutsets(Rect outOutsetRect) { 7904 if (mAttachInfo != null) { 7905 outOutsetRect.set(mAttachInfo.mOutsets); 7906 } else { 7907 outOutsetRect.setEmpty(); 7908 } 7909 } 7910 7911 /** 7912 * Returns the visibility status for this view. 7913 * 7914 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7915 * @attr ref android.R.styleable#View_visibility 7916 */ 7917 @ViewDebug.ExportedProperty(mapping = { 7918 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 7919 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 7920 @ViewDebug.IntToString(from = GONE, to = "GONE") 7921 }) 7922 @Visibility 7923 public int getVisibility() { 7924 return mViewFlags & VISIBILITY_MASK; 7925 } 7926 7927 /** 7928 * Set the enabled state of this view. 7929 * 7930 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7931 * @attr ref android.R.styleable#View_visibility 7932 */ 7933 @RemotableViewMethod 7934 public void setVisibility(@Visibility int visibility) { 7935 setFlags(visibility, VISIBILITY_MASK); 7936 } 7937 7938 /** 7939 * Returns the enabled status for this view. The interpretation of the 7940 * enabled state varies by subclass. 7941 * 7942 * @return True if this view is enabled, false otherwise. 7943 */ 7944 @ViewDebug.ExportedProperty 7945 public boolean isEnabled() { 7946 return (mViewFlags & ENABLED_MASK) == ENABLED; 7947 } 7948 7949 /** 7950 * Set the enabled state of this view. The interpretation of the enabled 7951 * state varies by subclass. 7952 * 7953 * @param enabled True if this view is enabled, false otherwise. 7954 */ 7955 @RemotableViewMethod 7956 public void setEnabled(boolean enabled) { 7957 if (enabled == isEnabled()) return; 7958 7959 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 7960 7961 /* 7962 * The View most likely has to change its appearance, so refresh 7963 * the drawable state. 7964 */ 7965 refreshDrawableState(); 7966 7967 // Invalidate too, since the default behavior for views is to be 7968 // be drawn at 50% alpha rather than to change the drawable. 7969 invalidate(true); 7970 7971 if (!enabled) { 7972 cancelPendingInputEvents(); 7973 } 7974 } 7975 7976 /** 7977 * Set whether this view can receive the focus. 7978 * 7979 * Setting this to false will also ensure that this view is not focusable 7980 * in touch mode. 7981 * 7982 * @param focusable If true, this view can receive the focus. 7983 * 7984 * @see #setFocusableInTouchMode(boolean) 7985 * @attr ref android.R.styleable#View_focusable 7986 */ 7987 public void setFocusable(boolean focusable) { 7988 if (!focusable) { 7989 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 7990 } 7991 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 7992 } 7993 7994 /** 7995 * Set whether this view can receive focus while in touch mode. 7996 * 7997 * Setting this to true will also ensure that this view is focusable. 7998 * 7999 * @param focusableInTouchMode If true, this view can receive the focus while 8000 * in touch mode. 8001 * 8002 * @see #setFocusable(boolean) 8003 * @attr ref android.R.styleable#View_focusableInTouchMode 8004 */ 8005 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8006 // Focusable in touch mode should always be set before the focusable flag 8007 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8008 // which, in touch mode, will not successfully request focus on this view 8009 // because the focusable in touch mode flag is not set 8010 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8011 if (focusableInTouchMode) { 8012 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8013 } 8014 } 8015 8016 /** 8017 * Set whether this view should have sound effects enabled for events such as 8018 * clicking and touching. 8019 * 8020 * <p>You may wish to disable sound effects for a view if you already play sounds, 8021 * for instance, a dial key that plays dtmf tones. 8022 * 8023 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8024 * @see #isSoundEffectsEnabled() 8025 * @see #playSoundEffect(int) 8026 * @attr ref android.R.styleable#View_soundEffectsEnabled 8027 */ 8028 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8029 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8030 } 8031 8032 /** 8033 * @return whether this view should have sound effects enabled for events such as 8034 * clicking and touching. 8035 * 8036 * @see #setSoundEffectsEnabled(boolean) 8037 * @see #playSoundEffect(int) 8038 * @attr ref android.R.styleable#View_soundEffectsEnabled 8039 */ 8040 @ViewDebug.ExportedProperty 8041 public boolean isSoundEffectsEnabled() { 8042 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8043 } 8044 8045 /** 8046 * Set whether this view should have haptic feedback for events such as 8047 * long presses. 8048 * 8049 * <p>You may wish to disable haptic feedback if your view already controls 8050 * its own haptic feedback. 8051 * 8052 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8053 * @see #isHapticFeedbackEnabled() 8054 * @see #performHapticFeedback(int) 8055 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8056 */ 8057 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8058 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8059 } 8060 8061 /** 8062 * @return whether this view should have haptic feedback enabled for events 8063 * long presses. 8064 * 8065 * @see #setHapticFeedbackEnabled(boolean) 8066 * @see #performHapticFeedback(int) 8067 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8068 */ 8069 @ViewDebug.ExportedProperty 8070 public boolean isHapticFeedbackEnabled() { 8071 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8072 } 8073 8074 /** 8075 * Returns the layout direction for this view. 8076 * 8077 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8078 * {@link #LAYOUT_DIRECTION_RTL}, 8079 * {@link #LAYOUT_DIRECTION_INHERIT} or 8080 * {@link #LAYOUT_DIRECTION_LOCALE}. 8081 * 8082 * @attr ref android.R.styleable#View_layoutDirection 8083 * 8084 * @hide 8085 */ 8086 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8087 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8088 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8089 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8090 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8091 }) 8092 @LayoutDir 8093 public int getRawLayoutDirection() { 8094 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8095 } 8096 8097 /** 8098 * Set the layout direction for this view. This will propagate a reset of layout direction 8099 * resolution to the view's children and resolve layout direction for this view. 8100 * 8101 * @param layoutDirection the layout direction to set. Should be one of: 8102 * 8103 * {@link #LAYOUT_DIRECTION_LTR}, 8104 * {@link #LAYOUT_DIRECTION_RTL}, 8105 * {@link #LAYOUT_DIRECTION_INHERIT}, 8106 * {@link #LAYOUT_DIRECTION_LOCALE}. 8107 * 8108 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8109 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8110 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8111 * 8112 * @attr ref android.R.styleable#View_layoutDirection 8113 */ 8114 @RemotableViewMethod 8115 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8116 if (getRawLayoutDirection() != layoutDirection) { 8117 // Reset the current layout direction and the resolved one 8118 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8119 resetRtlProperties(); 8120 // Set the new layout direction (filtered) 8121 mPrivateFlags2 |= 8122 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8123 // We need to resolve all RTL properties as they all depend on layout direction 8124 resolveRtlPropertiesIfNeeded(); 8125 requestLayout(); 8126 invalidate(true); 8127 } 8128 } 8129 8130 /** 8131 * Returns the resolved layout direction for this view. 8132 * 8133 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8134 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8135 * 8136 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8137 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8138 * 8139 * @attr ref android.R.styleable#View_layoutDirection 8140 */ 8141 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8142 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8143 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8144 }) 8145 @ResolvedLayoutDir 8146 public int getLayoutDirection() { 8147 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8148 if (targetSdkVersion < JELLY_BEAN_MR1) { 8149 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8150 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8151 } 8152 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8153 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8154 } 8155 8156 /** 8157 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8158 * layout attribute and/or the inherited value from the parent 8159 * 8160 * @return true if the layout is right-to-left. 8161 * 8162 * @hide 8163 */ 8164 @ViewDebug.ExportedProperty(category = "layout") 8165 public boolean isLayoutRtl() { 8166 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8167 } 8168 8169 /** 8170 * Indicates whether the view is currently tracking transient state that the 8171 * app should not need to concern itself with saving and restoring, but that 8172 * the framework should take special note to preserve when possible. 8173 * 8174 * <p>A view with transient state cannot be trivially rebound from an external 8175 * data source, such as an adapter binding item views in a list. This may be 8176 * because the view is performing an animation, tracking user selection 8177 * of content, or similar.</p> 8178 * 8179 * @return true if the view has transient state 8180 */ 8181 @ViewDebug.ExportedProperty(category = "layout") 8182 public boolean hasTransientState() { 8183 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8184 } 8185 8186 /** 8187 * Set whether this view is currently tracking transient state that the 8188 * framework should attempt to preserve when possible. This flag is reference counted, 8189 * so every call to setHasTransientState(true) should be paired with a later call 8190 * to setHasTransientState(false). 8191 * 8192 * <p>A view with transient state cannot be trivially rebound from an external 8193 * data source, such as an adapter binding item views in a list. This may be 8194 * because the view is performing an animation, tracking user selection 8195 * of content, or similar.</p> 8196 * 8197 * @param hasTransientState true if this view has transient state 8198 */ 8199 public void setHasTransientState(boolean hasTransientState) { 8200 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8201 mTransientStateCount - 1; 8202 if (mTransientStateCount < 0) { 8203 mTransientStateCount = 0; 8204 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8205 "unmatched pair of setHasTransientState calls"); 8206 } else if ((hasTransientState && mTransientStateCount == 1) || 8207 (!hasTransientState && mTransientStateCount == 0)) { 8208 // update flag if we've just incremented up from 0 or decremented down to 0 8209 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8210 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8211 if (mParent != null) { 8212 try { 8213 mParent.childHasTransientStateChanged(this, hasTransientState); 8214 } catch (AbstractMethodError e) { 8215 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8216 " does not fully implement ViewParent", e); 8217 } 8218 } 8219 } 8220 } 8221 8222 /** 8223 * Returns true if this view is currently attached to a window. 8224 */ 8225 public boolean isAttachedToWindow() { 8226 return mAttachInfo != null; 8227 } 8228 8229 /** 8230 * Returns true if this view has been through at least one layout since it 8231 * was last attached to or detached from a window. 8232 */ 8233 public boolean isLaidOut() { 8234 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8235 } 8236 8237 /** 8238 * If this view doesn't do any drawing on its own, set this flag to 8239 * allow further optimizations. By default, this flag is not set on 8240 * View, but could be set on some View subclasses such as ViewGroup. 8241 * 8242 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8243 * you should clear this flag. 8244 * 8245 * @param willNotDraw whether or not this View draw on its own 8246 */ 8247 public void setWillNotDraw(boolean willNotDraw) { 8248 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8249 } 8250 8251 /** 8252 * Returns whether or not this View draws on its own. 8253 * 8254 * @return true if this view has nothing to draw, false otherwise 8255 */ 8256 @ViewDebug.ExportedProperty(category = "drawing") 8257 public boolean willNotDraw() { 8258 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8259 } 8260 8261 /** 8262 * When a View's drawing cache is enabled, drawing is redirected to an 8263 * offscreen bitmap. Some views, like an ImageView, must be able to 8264 * bypass this mechanism if they already draw a single bitmap, to avoid 8265 * unnecessary usage of the memory. 8266 * 8267 * @param willNotCacheDrawing true if this view does not cache its 8268 * drawing, false otherwise 8269 */ 8270 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8271 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8272 } 8273 8274 /** 8275 * Returns whether or not this View can cache its drawing or not. 8276 * 8277 * @return true if this view does not cache its drawing, false otherwise 8278 */ 8279 @ViewDebug.ExportedProperty(category = "drawing") 8280 public boolean willNotCacheDrawing() { 8281 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8282 } 8283 8284 /** 8285 * Indicates whether this view reacts to click events or not. 8286 * 8287 * @return true if the view is clickable, false otherwise 8288 * 8289 * @see #setClickable(boolean) 8290 * @attr ref android.R.styleable#View_clickable 8291 */ 8292 @ViewDebug.ExportedProperty 8293 public boolean isClickable() { 8294 return (mViewFlags & CLICKABLE) == CLICKABLE; 8295 } 8296 8297 /** 8298 * Enables or disables click events for this view. When a view 8299 * is clickable it will change its state to "pressed" on every click. 8300 * Subclasses should set the view clickable to visually react to 8301 * user's clicks. 8302 * 8303 * @param clickable true to make the view clickable, false otherwise 8304 * 8305 * @see #isClickable() 8306 * @attr ref android.R.styleable#View_clickable 8307 */ 8308 public void setClickable(boolean clickable) { 8309 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8310 } 8311 8312 /** 8313 * Indicates whether this view reacts to long click events or not. 8314 * 8315 * @return true if the view is long clickable, false otherwise 8316 * 8317 * @see #setLongClickable(boolean) 8318 * @attr ref android.R.styleable#View_longClickable 8319 */ 8320 public boolean isLongClickable() { 8321 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8322 } 8323 8324 /** 8325 * Enables or disables long click events for this view. When a view is long 8326 * clickable it reacts to the user holding down the button for a longer 8327 * duration than a tap. This event can either launch the listener or a 8328 * context menu. 8329 * 8330 * @param longClickable true to make the view long clickable, false otherwise 8331 * @see #isLongClickable() 8332 * @attr ref android.R.styleable#View_longClickable 8333 */ 8334 public void setLongClickable(boolean longClickable) { 8335 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8336 } 8337 8338 /** 8339 * Indicates whether this view reacts to context clicks or not. 8340 * 8341 * @return true if the view is context clickable, false otherwise 8342 * @see #setContextClickable(boolean) 8343 * @attr ref android.R.styleable#View_contextClickable 8344 */ 8345 public boolean isContextClickable() { 8346 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8347 } 8348 8349 /** 8350 * Enables or disables context clicking for this view. This event can launch the listener. 8351 * 8352 * @param contextClickable true to make the view react to a context click, false otherwise 8353 * @see #isContextClickable() 8354 * @attr ref android.R.styleable#View_contextClickable 8355 */ 8356 public void setContextClickable(boolean contextClickable) { 8357 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8358 } 8359 8360 /** 8361 * Sets the pressed state for this view and provides a touch coordinate for 8362 * animation hinting. 8363 * 8364 * @param pressed Pass true to set the View's internal state to "pressed", 8365 * or false to reverts the View's internal state from a 8366 * previously set "pressed" state. 8367 * @param x The x coordinate of the touch that caused the press 8368 * @param y The y coordinate of the touch that caused the press 8369 */ 8370 private void setPressed(boolean pressed, float x, float y) { 8371 if (pressed) { 8372 drawableHotspotChanged(x, y); 8373 } 8374 8375 setPressed(pressed); 8376 } 8377 8378 /** 8379 * Sets the pressed state for this view. 8380 * 8381 * @see #isClickable() 8382 * @see #setClickable(boolean) 8383 * 8384 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8385 * the View's internal state from a previously set "pressed" state. 8386 */ 8387 public void setPressed(boolean pressed) { 8388 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8389 8390 if (pressed) { 8391 mPrivateFlags |= PFLAG_PRESSED; 8392 } else { 8393 mPrivateFlags &= ~PFLAG_PRESSED; 8394 } 8395 8396 if (needsRefresh) { 8397 refreshDrawableState(); 8398 } 8399 dispatchSetPressed(pressed); 8400 } 8401 8402 /** 8403 * Dispatch setPressed to all of this View's children. 8404 * 8405 * @see #setPressed(boolean) 8406 * 8407 * @param pressed The new pressed state 8408 */ 8409 protected void dispatchSetPressed(boolean pressed) { 8410 } 8411 8412 /** 8413 * Indicates whether the view is currently in pressed state. Unless 8414 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8415 * the pressed state. 8416 * 8417 * @see #setPressed(boolean) 8418 * @see #isClickable() 8419 * @see #setClickable(boolean) 8420 * 8421 * @return true if the view is currently pressed, false otherwise 8422 */ 8423 @ViewDebug.ExportedProperty 8424 public boolean isPressed() { 8425 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8426 } 8427 8428 /** 8429 * @hide 8430 * Indicates whether this view will participate in data collection through 8431 * {@link ViewStructure}. If true, it will not provide any data 8432 * for itself or its children. If false, the normal data collection will be allowed. 8433 * 8434 * @return Returns false if assist data collection is not blocked, else true. 8435 * 8436 * @see #setAssistBlocked(boolean) 8437 * @attr ref android.R.styleable#View_assistBlocked 8438 */ 8439 public boolean isAssistBlocked() { 8440 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8441 } 8442 8443 /** 8444 * @hide 8445 * Controls whether assist data collection from this view and its children is enabled 8446 * (that is, whether {@link #onProvideStructure} and 8447 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8448 * allowing normal assist collection. Setting this to false will disable assist collection. 8449 * 8450 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8451 * (the default) to allow it. 8452 * 8453 * @see #isAssistBlocked() 8454 * @see #onProvideStructure 8455 * @see #onProvideVirtualStructure 8456 * @attr ref android.R.styleable#View_assistBlocked 8457 */ 8458 public void setAssistBlocked(boolean enabled) { 8459 if (enabled) { 8460 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8461 } else { 8462 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8463 } 8464 } 8465 8466 /** 8467 * Indicates whether this view will save its state (that is, 8468 * whether its {@link #onSaveInstanceState} method will be called). 8469 * 8470 * @return Returns true if the view state saving is enabled, else false. 8471 * 8472 * @see #setSaveEnabled(boolean) 8473 * @attr ref android.R.styleable#View_saveEnabled 8474 */ 8475 public boolean isSaveEnabled() { 8476 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8477 } 8478 8479 /** 8480 * Controls whether the saving of this view's state is 8481 * enabled (that is, whether its {@link #onSaveInstanceState} method 8482 * will be called). Note that even if freezing is enabled, the 8483 * view still must have an id assigned to it (via {@link #setId(int)}) 8484 * for its state to be saved. This flag can only disable the 8485 * saving of this view; any child views may still have their state saved. 8486 * 8487 * @param enabled Set to false to <em>disable</em> state saving, or true 8488 * (the default) to allow it. 8489 * 8490 * @see #isSaveEnabled() 8491 * @see #setId(int) 8492 * @see #onSaveInstanceState() 8493 * @attr ref android.R.styleable#View_saveEnabled 8494 */ 8495 public void setSaveEnabled(boolean enabled) { 8496 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8497 } 8498 8499 /** 8500 * Gets whether the framework should discard touches when the view's 8501 * window is obscured by another visible window. 8502 * Refer to the {@link View} security documentation for more details. 8503 * 8504 * @return True if touch filtering is enabled. 8505 * 8506 * @see #setFilterTouchesWhenObscured(boolean) 8507 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8508 */ 8509 @ViewDebug.ExportedProperty 8510 public boolean getFilterTouchesWhenObscured() { 8511 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8512 } 8513 8514 /** 8515 * Sets whether the framework should discard touches when the view's 8516 * window is obscured by another visible window. 8517 * Refer to the {@link View} security documentation for more details. 8518 * 8519 * @param enabled True if touch filtering should be enabled. 8520 * 8521 * @see #getFilterTouchesWhenObscured 8522 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8523 */ 8524 public void setFilterTouchesWhenObscured(boolean enabled) { 8525 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8526 FILTER_TOUCHES_WHEN_OBSCURED); 8527 } 8528 8529 /** 8530 * Indicates whether the entire hierarchy under this view will save its 8531 * state when a state saving traversal occurs from its parent. The default 8532 * is true; if false, these views will not be saved unless 8533 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8534 * 8535 * @return Returns true if the view state saving from parent is enabled, else false. 8536 * 8537 * @see #setSaveFromParentEnabled(boolean) 8538 */ 8539 public boolean isSaveFromParentEnabled() { 8540 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8541 } 8542 8543 /** 8544 * Controls whether the entire hierarchy under this view will save its 8545 * state when a state saving traversal occurs from its parent. The default 8546 * is true; if false, these views will not be saved unless 8547 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8548 * 8549 * @param enabled Set to false to <em>disable</em> state saving, or true 8550 * (the default) to allow it. 8551 * 8552 * @see #isSaveFromParentEnabled() 8553 * @see #setId(int) 8554 * @see #onSaveInstanceState() 8555 */ 8556 public void setSaveFromParentEnabled(boolean enabled) { 8557 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8558 } 8559 8560 8561 /** 8562 * Returns whether this View is able to take focus. 8563 * 8564 * @return True if this view can take focus, or false otherwise. 8565 * @attr ref android.R.styleable#View_focusable 8566 */ 8567 @ViewDebug.ExportedProperty(category = "focus") 8568 public final boolean isFocusable() { 8569 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8570 } 8571 8572 /** 8573 * When a view is focusable, it may not want to take focus when in touch mode. 8574 * For example, a button would like focus when the user is navigating via a D-pad 8575 * so that the user can click on it, but once the user starts touching the screen, 8576 * the button shouldn't take focus 8577 * @return Whether the view is focusable in touch mode. 8578 * @attr ref android.R.styleable#View_focusableInTouchMode 8579 */ 8580 @ViewDebug.ExportedProperty 8581 public final boolean isFocusableInTouchMode() { 8582 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8583 } 8584 8585 /** 8586 * Find the nearest view in the specified direction that can take focus. 8587 * This does not actually give focus to that view. 8588 * 8589 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8590 * 8591 * @return The nearest focusable in the specified direction, or null if none 8592 * can be found. 8593 */ 8594 public View focusSearch(@FocusRealDirection int direction) { 8595 if (mParent != null) { 8596 return mParent.focusSearch(this, direction); 8597 } else { 8598 return null; 8599 } 8600 } 8601 8602 /** 8603 * This method is the last chance for the focused view and its ancestors to 8604 * respond to an arrow key. This is called when the focused view did not 8605 * consume the key internally, nor could the view system find a new view in 8606 * the requested direction to give focus to. 8607 * 8608 * @param focused The currently focused view. 8609 * @param direction The direction focus wants to move. One of FOCUS_UP, 8610 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8611 * @return True if the this view consumed this unhandled move. 8612 */ 8613 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8614 return false; 8615 } 8616 8617 /** 8618 * If a user manually specified the next view id for a particular direction, 8619 * use the root to look up the view. 8620 * @param root The root view of the hierarchy containing this view. 8621 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8622 * or FOCUS_BACKWARD. 8623 * @return The user specified next view, or null if there is none. 8624 */ 8625 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8626 switch (direction) { 8627 case FOCUS_LEFT: 8628 if (mNextFocusLeftId == View.NO_ID) return null; 8629 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8630 case FOCUS_RIGHT: 8631 if (mNextFocusRightId == View.NO_ID) return null; 8632 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8633 case FOCUS_UP: 8634 if (mNextFocusUpId == View.NO_ID) return null; 8635 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8636 case FOCUS_DOWN: 8637 if (mNextFocusDownId == View.NO_ID) return null; 8638 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8639 case FOCUS_FORWARD: 8640 if (mNextFocusForwardId == View.NO_ID) return null; 8641 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8642 case FOCUS_BACKWARD: { 8643 if (mID == View.NO_ID) return null; 8644 final int id = mID; 8645 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8646 @Override 8647 public boolean apply(View t) { 8648 return t.mNextFocusForwardId == id; 8649 } 8650 }); 8651 } 8652 } 8653 return null; 8654 } 8655 8656 private View findViewInsideOutShouldExist(View root, int id) { 8657 if (mMatchIdPredicate == null) { 8658 mMatchIdPredicate = new MatchIdPredicate(); 8659 } 8660 mMatchIdPredicate.mId = id; 8661 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8662 if (result == null) { 8663 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8664 } 8665 return result; 8666 } 8667 8668 /** 8669 * Find and return all focusable views that are descendants of this view, 8670 * possibly including this view if it is focusable itself. 8671 * 8672 * @param direction The direction of the focus 8673 * @return A list of focusable views 8674 */ 8675 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8676 ArrayList<View> result = new ArrayList<View>(24); 8677 addFocusables(result, direction); 8678 return result; 8679 } 8680 8681 /** 8682 * Add any focusable views that are descendants of this view (possibly 8683 * including this view if it is focusable itself) to views. If we are in touch mode, 8684 * only add views that are also focusable in touch mode. 8685 * 8686 * @param views Focusable views found so far 8687 * @param direction The direction of the focus 8688 */ 8689 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8690 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 8691 } 8692 8693 /** 8694 * Adds any focusable views that are descendants of this view (possibly 8695 * including this view if it is focusable itself) to views. This method 8696 * adds all focusable views regardless if we are in touch mode or 8697 * only views focusable in touch mode if we are in touch mode or 8698 * only views that can take accessibility focus if accessibility is enabled 8699 * depending on the focusable mode parameter. 8700 * 8701 * @param views Focusable views found so far or null if all we are interested is 8702 * the number of focusables. 8703 * @param direction The direction of the focus. 8704 * @param focusableMode The type of focusables to be added. 8705 * 8706 * @see #FOCUSABLES_ALL 8707 * @see #FOCUSABLES_TOUCH_MODE 8708 */ 8709 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8710 @FocusableMode int focusableMode) { 8711 if (views == null) { 8712 return; 8713 } 8714 if (!isFocusable()) { 8715 return; 8716 } 8717 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8718 && isInTouchMode() && !isFocusableInTouchMode()) { 8719 return; 8720 } 8721 views.add(this); 8722 } 8723 8724 /** 8725 * Finds the Views that contain given text. The containment is case insensitive. 8726 * The search is performed by either the text that the View renders or the content 8727 * description that describes the view for accessibility purposes and the view does 8728 * not render or both. Clients can specify how the search is to be performed via 8729 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8730 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8731 * 8732 * @param outViews The output list of matching Views. 8733 * @param searched The text to match against. 8734 * 8735 * @see #FIND_VIEWS_WITH_TEXT 8736 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8737 * @see #setContentDescription(CharSequence) 8738 */ 8739 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8740 @FindViewFlags int flags) { 8741 if (getAccessibilityNodeProvider() != null) { 8742 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8743 outViews.add(this); 8744 } 8745 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8746 && (searched != null && searched.length() > 0) 8747 && (mContentDescription != null && mContentDescription.length() > 0)) { 8748 String searchedLowerCase = searched.toString().toLowerCase(); 8749 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8750 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8751 outViews.add(this); 8752 } 8753 } 8754 } 8755 8756 /** 8757 * Find and return all touchable views that are descendants of this view, 8758 * possibly including this view if it is touchable itself. 8759 * 8760 * @return A list of touchable views 8761 */ 8762 public ArrayList<View> getTouchables() { 8763 ArrayList<View> result = new ArrayList<View>(); 8764 addTouchables(result); 8765 return result; 8766 } 8767 8768 /** 8769 * Add any touchable views that are descendants of this view (possibly 8770 * including this view if it is touchable itself) to views. 8771 * 8772 * @param views Touchable views found so far 8773 */ 8774 public void addTouchables(ArrayList<View> views) { 8775 final int viewFlags = mViewFlags; 8776 8777 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8778 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8779 && (viewFlags & ENABLED_MASK) == ENABLED) { 8780 views.add(this); 8781 } 8782 } 8783 8784 /** 8785 * Returns whether this View is accessibility focused. 8786 * 8787 * @return True if this View is accessibility focused. 8788 */ 8789 public boolean isAccessibilityFocused() { 8790 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8791 } 8792 8793 /** 8794 * Call this to try to give accessibility focus to this view. 8795 * 8796 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8797 * returns false or the view is no visible or the view already has accessibility 8798 * focus. 8799 * 8800 * See also {@link #focusSearch(int)}, which is what you call to say that you 8801 * have focus, and you want your parent to look for the next one. 8802 * 8803 * @return Whether this view actually took accessibility focus. 8804 * 8805 * @hide 8806 */ 8807 public boolean requestAccessibilityFocus() { 8808 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8809 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8810 return false; 8811 } 8812 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8813 return false; 8814 } 8815 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8816 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8817 ViewRootImpl viewRootImpl = getViewRootImpl(); 8818 if (viewRootImpl != null) { 8819 viewRootImpl.setAccessibilityFocus(this, null); 8820 } 8821 invalidate(); 8822 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8823 return true; 8824 } 8825 return false; 8826 } 8827 8828 /** 8829 * Call this to try to clear accessibility focus of this view. 8830 * 8831 * See also {@link #focusSearch(int)}, which is what you call to say that you 8832 * have focus, and you want your parent to look for the next one. 8833 * 8834 * @hide 8835 */ 8836 public void clearAccessibilityFocus() { 8837 clearAccessibilityFocusNoCallbacks(); 8838 8839 // Clear the global reference of accessibility focus if this view or 8840 // any of its descendants had accessibility focus. This will NOT send 8841 // an event or update internal state if focus is cleared from a 8842 // descendant view, which may leave views in inconsistent states. 8843 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8844 if (viewRootImpl != null) { 8845 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8846 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8847 viewRootImpl.setAccessibilityFocus(null, null); 8848 } 8849 } 8850 } 8851 8852 private void sendAccessibilityHoverEvent(int eventType) { 8853 // Since we are not delivering to a client accessibility events from not 8854 // important views (unless the clinet request that) we need to fire the 8855 // event from the deepest view exposed to the client. As a consequence if 8856 // the user crosses a not exposed view the client will see enter and exit 8857 // of the exposed predecessor followed by and enter and exit of that same 8858 // predecessor when entering and exiting the not exposed descendant. This 8859 // is fine since the client has a clear idea which view is hovered at the 8860 // price of a couple more events being sent. This is a simple and 8861 // working solution. 8862 View source = this; 8863 while (true) { 8864 if (source.includeForAccessibility()) { 8865 source.sendAccessibilityEvent(eventType); 8866 return; 8867 } 8868 ViewParent parent = source.getParent(); 8869 if (parent instanceof View) { 8870 source = (View) parent; 8871 } else { 8872 return; 8873 } 8874 } 8875 } 8876 8877 /** 8878 * Clears accessibility focus without calling any callback methods 8879 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8880 * is used for clearing accessibility focus when giving this focus to 8881 * another view. 8882 */ 8883 void clearAccessibilityFocusNoCallbacks() { 8884 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8885 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8886 invalidate(); 8887 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8888 } 8889 } 8890 8891 /** 8892 * Call this to try to give focus to a specific view or to one of its 8893 * descendants. 8894 * 8895 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8896 * false), or if it is focusable and it is not focusable in touch mode 8897 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8898 * 8899 * See also {@link #focusSearch(int)}, which is what you call to say that you 8900 * have focus, and you want your parent to look for the next one. 8901 * 8902 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 8903 * {@link #FOCUS_DOWN} and <code>null</code>. 8904 * 8905 * @return Whether this view or one of its descendants actually took focus. 8906 */ 8907 public final boolean requestFocus() { 8908 return requestFocus(View.FOCUS_DOWN); 8909 } 8910 8911 /** 8912 * Call this to try to give focus to a specific view or to one of its 8913 * descendants and give it a hint about what direction focus is heading. 8914 * 8915 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8916 * false), or if it is focusable and it is not focusable in touch mode 8917 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8918 * 8919 * See also {@link #focusSearch(int)}, which is what you call to say that you 8920 * have focus, and you want your parent to look for the next one. 8921 * 8922 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 8923 * <code>null</code> set for the previously focused rectangle. 8924 * 8925 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8926 * @return Whether this view or one of its descendants actually took focus. 8927 */ 8928 public final boolean requestFocus(int direction) { 8929 return requestFocus(direction, null); 8930 } 8931 8932 /** 8933 * Call this to try to give focus to a specific view or to one of its descendants 8934 * and give it hints about the direction and a specific rectangle that the focus 8935 * is coming from. The rectangle can help give larger views a finer grained hint 8936 * about where focus is coming from, and therefore, where to show selection, or 8937 * forward focus change internally. 8938 * 8939 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8940 * false), or if it is focusable and it is not focusable in touch mode 8941 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8942 * 8943 * A View will not take focus if it is not visible. 8944 * 8945 * A View will not take focus if one of its parents has 8946 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 8947 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 8948 * 8949 * See also {@link #focusSearch(int)}, which is what you call to say that you 8950 * have focus, and you want your parent to look for the next one. 8951 * 8952 * You may wish to override this method if your custom {@link View} has an internal 8953 * {@link View} that it wishes to forward the request to. 8954 * 8955 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8956 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 8957 * to give a finer grained hint about where focus is coming from. May be null 8958 * if there is no hint. 8959 * @return Whether this view or one of its descendants actually took focus. 8960 */ 8961 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 8962 return requestFocusNoSearch(direction, previouslyFocusedRect); 8963 } 8964 8965 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 8966 // need to be focusable 8967 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 8968 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8969 return false; 8970 } 8971 8972 // need to be focusable in touch mode if in touch mode 8973 if (isInTouchMode() && 8974 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 8975 return false; 8976 } 8977 8978 // need to not have any parents blocking us 8979 if (hasAncestorThatBlocksDescendantFocus()) { 8980 return false; 8981 } 8982 8983 handleFocusGainInternal(direction, previouslyFocusedRect); 8984 return true; 8985 } 8986 8987 /** 8988 * Call this to try to give focus to a specific view or to one of its descendants. This is a 8989 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 8990 * touch mode to request focus when they are touched. 8991 * 8992 * @return Whether this view or one of its descendants actually took focus. 8993 * 8994 * @see #isInTouchMode() 8995 * 8996 */ 8997 public final boolean requestFocusFromTouch() { 8998 // Leave touch mode if we need to 8999 if (isInTouchMode()) { 9000 ViewRootImpl viewRoot = getViewRootImpl(); 9001 if (viewRoot != null) { 9002 viewRoot.ensureTouchMode(false); 9003 } 9004 } 9005 return requestFocus(View.FOCUS_DOWN); 9006 } 9007 9008 /** 9009 * @return Whether any ancestor of this view blocks descendant focus. 9010 */ 9011 private boolean hasAncestorThatBlocksDescendantFocus() { 9012 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9013 ViewParent ancestor = mParent; 9014 while (ancestor instanceof ViewGroup) { 9015 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9016 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9017 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9018 return true; 9019 } else { 9020 ancestor = vgAncestor.getParent(); 9021 } 9022 } 9023 return false; 9024 } 9025 9026 /** 9027 * Gets the mode for determining whether this View is important for accessibility 9028 * which is if it fires accessibility events and if it is reported to 9029 * accessibility services that query the screen. 9030 * 9031 * @return The mode for determining whether a View is important for accessibility. 9032 * 9033 * @attr ref android.R.styleable#View_importantForAccessibility 9034 * 9035 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9036 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9037 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9038 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9039 */ 9040 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9041 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9042 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9043 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9044 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9045 to = "noHideDescendants") 9046 }) 9047 public int getImportantForAccessibility() { 9048 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9049 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9050 } 9051 9052 /** 9053 * Sets the live region mode for this view. This indicates to accessibility 9054 * services whether they should automatically notify the user about changes 9055 * to the view's content description or text, or to the content descriptions 9056 * or text of the view's children (where applicable). 9057 * <p> 9058 * For example, in a login screen with a TextView that displays an "incorrect 9059 * password" notification, that view should be marked as a live region with 9060 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9061 * <p> 9062 * To disable change notifications for this view, use 9063 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9064 * mode for most views. 9065 * <p> 9066 * To indicate that the user should be notified of changes, use 9067 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9068 * <p> 9069 * If the view's changes should interrupt ongoing speech and notify the user 9070 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9071 * 9072 * @param mode The live region mode for this view, one of: 9073 * <ul> 9074 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9075 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9076 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9077 * </ul> 9078 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9079 */ 9080 public void setAccessibilityLiveRegion(int mode) { 9081 if (mode != getAccessibilityLiveRegion()) { 9082 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9083 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9084 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9085 notifyViewAccessibilityStateChangedIfNeeded( 9086 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9087 } 9088 } 9089 9090 /** 9091 * Gets the live region mode for this View. 9092 * 9093 * @return The live region mode for the view. 9094 * 9095 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9096 * 9097 * @see #setAccessibilityLiveRegion(int) 9098 */ 9099 public int getAccessibilityLiveRegion() { 9100 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9101 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9102 } 9103 9104 /** 9105 * Sets how to determine whether this view is important for accessibility 9106 * which is if it fires accessibility events and if it is reported to 9107 * accessibility services that query the screen. 9108 * 9109 * @param mode How to determine whether this view is important for accessibility. 9110 * 9111 * @attr ref android.R.styleable#View_importantForAccessibility 9112 * 9113 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9114 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9115 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9116 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9117 */ 9118 public void setImportantForAccessibility(int mode) { 9119 final int oldMode = getImportantForAccessibility(); 9120 if (mode != oldMode) { 9121 final boolean hideDescendants = 9122 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9123 9124 // If this node or its descendants are no longer important, try to 9125 // clear accessibility focus. 9126 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9127 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9128 if (focusHost != null) { 9129 focusHost.clearAccessibilityFocus(); 9130 } 9131 } 9132 9133 // If we're moving between AUTO and another state, we might not need 9134 // to send a subtree changed notification. We'll store the computed 9135 // importance, since we'll need to check it later to make sure. 9136 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9137 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9138 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9139 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9140 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9141 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9142 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9143 notifySubtreeAccessibilityStateChangedIfNeeded(); 9144 } else { 9145 notifyViewAccessibilityStateChangedIfNeeded( 9146 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9147 } 9148 } 9149 } 9150 9151 /** 9152 * Returns the view within this view's hierarchy that is hosting 9153 * accessibility focus. 9154 * 9155 * @param searchDescendants whether to search for focus in descendant views 9156 * @return the view hosting accessibility focus, or {@code null} 9157 */ 9158 private View findAccessibilityFocusHost(boolean searchDescendants) { 9159 if (isAccessibilityFocusedViewOrHost()) { 9160 return this; 9161 } 9162 9163 if (searchDescendants) { 9164 final ViewRootImpl viewRoot = getViewRootImpl(); 9165 if (viewRoot != null) { 9166 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9167 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9168 return focusHost; 9169 } 9170 } 9171 } 9172 9173 return null; 9174 } 9175 9176 /** 9177 * Computes whether this view should be exposed for accessibility. In 9178 * general, views that are interactive or provide information are exposed 9179 * while views that serve only as containers are hidden. 9180 * <p> 9181 * If an ancestor of this view has importance 9182 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9183 * returns <code>false</code>. 9184 * <p> 9185 * Otherwise, the value is computed according to the view's 9186 * {@link #getImportantForAccessibility()} value: 9187 * <ol> 9188 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9189 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9190 * </code> 9191 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9192 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9193 * view satisfies any of the following: 9194 * <ul> 9195 * <li>Is actionable, e.g. {@link #isClickable()}, 9196 * {@link #isLongClickable()}, or {@link #isFocusable()} 9197 * <li>Has an {@link AccessibilityDelegate} 9198 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9199 * {@link OnKeyListener}, etc. 9200 * <li>Is an accessibility live region, e.g. 9201 * {@link #getAccessibilityLiveRegion()} is not 9202 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9203 * </ul> 9204 * </ol> 9205 * 9206 * @return Whether the view is exposed for accessibility. 9207 * @see #setImportantForAccessibility(int) 9208 * @see #getImportantForAccessibility() 9209 */ 9210 public boolean isImportantForAccessibility() { 9211 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9212 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9213 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9214 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9215 return false; 9216 } 9217 9218 // Check parent mode to ensure we're not hidden. 9219 ViewParent parent = mParent; 9220 while (parent instanceof View) { 9221 if (((View) parent).getImportantForAccessibility() 9222 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9223 return false; 9224 } 9225 parent = parent.getParent(); 9226 } 9227 9228 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9229 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9230 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9231 } 9232 9233 /** 9234 * Gets the parent for accessibility purposes. Note that the parent for 9235 * accessibility is not necessary the immediate parent. It is the first 9236 * predecessor that is important for accessibility. 9237 * 9238 * @return The parent for accessibility purposes. 9239 */ 9240 public ViewParent getParentForAccessibility() { 9241 if (mParent instanceof View) { 9242 View parentView = (View) mParent; 9243 if (parentView.includeForAccessibility()) { 9244 return mParent; 9245 } else { 9246 return mParent.getParentForAccessibility(); 9247 } 9248 } 9249 return null; 9250 } 9251 9252 /** 9253 * Adds the children of this View relevant for accessibility to the given list 9254 * as output. Since some Views are not important for accessibility the added 9255 * child views are not necessarily direct children of this view, rather they are 9256 * the first level of descendants important for accessibility. 9257 * 9258 * @param outChildren The output list that will receive children for accessibility. 9259 */ 9260 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9261 9262 } 9263 9264 /** 9265 * Whether to regard this view for accessibility. A view is regarded for 9266 * accessibility if it is important for accessibility or the querying 9267 * accessibility service has explicitly requested that view not 9268 * important for accessibility are regarded. 9269 * 9270 * @return Whether to regard the view for accessibility. 9271 * 9272 * @hide 9273 */ 9274 public boolean includeForAccessibility() { 9275 if (mAttachInfo != null) { 9276 return (mAttachInfo.mAccessibilityFetchFlags 9277 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9278 || isImportantForAccessibility(); 9279 } 9280 return false; 9281 } 9282 9283 /** 9284 * Returns whether the View is considered actionable from 9285 * accessibility perspective. Such view are important for 9286 * accessibility. 9287 * 9288 * @return True if the view is actionable for accessibility. 9289 * 9290 * @hide 9291 */ 9292 public boolean isActionableForAccessibility() { 9293 return (isClickable() || isLongClickable() || isFocusable()); 9294 } 9295 9296 /** 9297 * Returns whether the View has registered callbacks which makes it 9298 * important for accessibility. 9299 * 9300 * @return True if the view is actionable for accessibility. 9301 */ 9302 private boolean hasListenersForAccessibility() { 9303 ListenerInfo info = getListenerInfo(); 9304 return mTouchDelegate != null || info.mOnKeyListener != null 9305 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9306 || info.mOnHoverListener != null || info.mOnDragListener != null; 9307 } 9308 9309 /** 9310 * Notifies that the accessibility state of this view changed. The change 9311 * is local to this view and does not represent structural changes such 9312 * as children and parent. For example, the view became focusable. The 9313 * notification is at at most once every 9314 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9315 * to avoid unnecessary load to the system. Also once a view has a pending 9316 * notification this method is a NOP until the notification has been sent. 9317 * 9318 * @hide 9319 */ 9320 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9321 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9322 return; 9323 } 9324 if (mSendViewStateChangedAccessibilityEvent == null) { 9325 mSendViewStateChangedAccessibilityEvent = 9326 new SendViewStateChangedAccessibilityEvent(); 9327 } 9328 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9329 } 9330 9331 /** 9332 * Notifies that the accessibility state of this view changed. The change 9333 * is *not* local to this view and does represent structural changes such 9334 * as children and parent. For example, the view size changed. The 9335 * notification is at at most once every 9336 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9337 * to avoid unnecessary load to the system. Also once a view has a pending 9338 * notification this method is a NOP until the notification has been sent. 9339 * 9340 * @hide 9341 */ 9342 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9343 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9344 return; 9345 } 9346 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9347 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9348 if (mParent != null) { 9349 try { 9350 mParent.notifySubtreeAccessibilityStateChanged( 9351 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9352 } catch (AbstractMethodError e) { 9353 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9354 " does not fully implement ViewParent", e); 9355 } 9356 } 9357 } 9358 } 9359 9360 /** 9361 * Change the visibility of the View without triggering any other changes. This is 9362 * important for transitions, where visibility changes should not adjust focus or 9363 * trigger a new layout. This is only used when the visibility has already been changed 9364 * and we need a transient value during an animation. When the animation completes, 9365 * the original visibility value is always restored. 9366 * 9367 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9368 * @hide 9369 */ 9370 public void setTransitionVisibility(@Visibility int visibility) { 9371 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9372 } 9373 9374 /** 9375 * Reset the flag indicating the accessibility state of the subtree rooted 9376 * at this view changed. 9377 */ 9378 void resetSubtreeAccessibilityStateChanged() { 9379 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9380 } 9381 9382 /** 9383 * Report an accessibility action to this view's parents for delegated processing. 9384 * 9385 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9386 * call this method to delegate an accessibility action to a supporting parent. If the parent 9387 * returns true from its 9388 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9389 * method this method will return true to signify that the action was consumed.</p> 9390 * 9391 * <p>This method is useful for implementing nested scrolling child views. If 9392 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9393 * a custom view implementation may invoke this method to allow a parent to consume the 9394 * scroll first. If this method returns true the custom view should skip its own scrolling 9395 * behavior.</p> 9396 * 9397 * @param action Accessibility action to delegate 9398 * @param arguments Optional action arguments 9399 * @return true if the action was consumed by a parent 9400 */ 9401 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9402 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9403 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9404 return true; 9405 } 9406 } 9407 return false; 9408 } 9409 9410 /** 9411 * Performs the specified accessibility action on the view. For 9412 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9413 * <p> 9414 * If an {@link AccessibilityDelegate} has been specified via calling 9415 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9416 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9417 * is responsible for handling this call. 9418 * </p> 9419 * 9420 * <p>The default implementation will delegate 9421 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9422 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9423 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9424 * 9425 * @param action The action to perform. 9426 * @param arguments Optional action arguments. 9427 * @return Whether the action was performed. 9428 */ 9429 public boolean performAccessibilityAction(int action, Bundle arguments) { 9430 if (mAccessibilityDelegate != null) { 9431 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9432 } else { 9433 return performAccessibilityActionInternal(action, arguments); 9434 } 9435 } 9436 9437 /** 9438 * @see #performAccessibilityAction(int, Bundle) 9439 * 9440 * Note: Called from the default {@link AccessibilityDelegate}. 9441 * 9442 * @hide 9443 */ 9444 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9445 if (isNestedScrollingEnabled() 9446 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9447 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9448 || action == R.id.accessibilityActionScrollUp 9449 || action == R.id.accessibilityActionScrollLeft 9450 || action == R.id.accessibilityActionScrollDown 9451 || action == R.id.accessibilityActionScrollRight)) { 9452 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9453 return true; 9454 } 9455 } 9456 9457 switch (action) { 9458 case AccessibilityNodeInfo.ACTION_CLICK: { 9459 if (isClickable()) { 9460 performClick(); 9461 return true; 9462 } 9463 } break; 9464 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9465 if (isLongClickable()) { 9466 performLongClick(); 9467 return true; 9468 } 9469 } break; 9470 case AccessibilityNodeInfo.ACTION_FOCUS: { 9471 if (!hasFocus()) { 9472 // Get out of touch mode since accessibility 9473 // wants to move focus around. 9474 getViewRootImpl().ensureTouchMode(false); 9475 return requestFocus(); 9476 } 9477 } break; 9478 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9479 if (hasFocus()) { 9480 clearFocus(); 9481 return !isFocused(); 9482 } 9483 } break; 9484 case AccessibilityNodeInfo.ACTION_SELECT: { 9485 if (!isSelected()) { 9486 setSelected(true); 9487 return isSelected(); 9488 } 9489 } break; 9490 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9491 if (isSelected()) { 9492 setSelected(false); 9493 return !isSelected(); 9494 } 9495 } break; 9496 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9497 if (!isAccessibilityFocused()) { 9498 return requestAccessibilityFocus(); 9499 } 9500 } break; 9501 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9502 if (isAccessibilityFocused()) { 9503 clearAccessibilityFocus(); 9504 return true; 9505 } 9506 } break; 9507 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 9508 if (arguments != null) { 9509 final int granularity = arguments.getInt( 9510 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9511 final boolean extendSelection = arguments.getBoolean( 9512 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9513 return traverseAtGranularity(granularity, true, extendSelection); 9514 } 9515 } break; 9516 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9517 if (arguments != null) { 9518 final int granularity = arguments.getInt( 9519 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9520 final boolean extendSelection = arguments.getBoolean( 9521 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9522 return traverseAtGranularity(granularity, false, extendSelection); 9523 } 9524 } break; 9525 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9526 CharSequence text = getIterableTextForAccessibility(); 9527 if (text == null) { 9528 return false; 9529 } 9530 final int start = (arguments != null) ? arguments.getInt( 9531 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9532 final int end = (arguments != null) ? arguments.getInt( 9533 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9534 // Only cursor position can be specified (selection length == 0) 9535 if ((getAccessibilitySelectionStart() != start 9536 || getAccessibilitySelectionEnd() != end) 9537 && (start == end)) { 9538 setAccessibilitySelection(start, end); 9539 notifyViewAccessibilityStateChangedIfNeeded( 9540 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9541 return true; 9542 } 9543 } break; 9544 case R.id.accessibilityActionShowOnScreen: { 9545 if (mAttachInfo != null) { 9546 final Rect r = mAttachInfo.mTmpInvalRect; 9547 getDrawingRect(r); 9548 return requestRectangleOnScreen(r, true); 9549 } 9550 } break; 9551 case R.id.accessibilityActionContextClick: { 9552 if (isContextClickable()) { 9553 performContextClick(); 9554 return true; 9555 } 9556 } break; 9557 } 9558 return false; 9559 } 9560 9561 private boolean traverseAtGranularity(int granularity, boolean forward, 9562 boolean extendSelection) { 9563 CharSequence text = getIterableTextForAccessibility(); 9564 if (text == null || text.length() == 0) { 9565 return false; 9566 } 9567 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9568 if (iterator == null) { 9569 return false; 9570 } 9571 int current = getAccessibilitySelectionEnd(); 9572 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9573 current = forward ? 0 : text.length(); 9574 } 9575 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9576 if (range == null) { 9577 return false; 9578 } 9579 final int segmentStart = range[0]; 9580 final int segmentEnd = range[1]; 9581 int selectionStart; 9582 int selectionEnd; 9583 if (extendSelection && isAccessibilitySelectionExtendable()) { 9584 selectionStart = getAccessibilitySelectionStart(); 9585 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9586 selectionStart = forward ? segmentStart : segmentEnd; 9587 } 9588 selectionEnd = forward ? segmentEnd : segmentStart; 9589 } else { 9590 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9591 } 9592 setAccessibilitySelection(selectionStart, selectionEnd); 9593 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9594 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9595 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9596 return true; 9597 } 9598 9599 /** 9600 * Gets the text reported for accessibility purposes. 9601 * 9602 * @return The accessibility text. 9603 * 9604 * @hide 9605 */ 9606 public CharSequence getIterableTextForAccessibility() { 9607 return getContentDescription(); 9608 } 9609 9610 /** 9611 * Gets whether accessibility selection can be extended. 9612 * 9613 * @return If selection is extensible. 9614 * 9615 * @hide 9616 */ 9617 public boolean isAccessibilitySelectionExtendable() { 9618 return false; 9619 } 9620 9621 /** 9622 * @hide 9623 */ 9624 public int getAccessibilitySelectionStart() { 9625 return mAccessibilityCursorPosition; 9626 } 9627 9628 /** 9629 * @hide 9630 */ 9631 public int getAccessibilitySelectionEnd() { 9632 return getAccessibilitySelectionStart(); 9633 } 9634 9635 /** 9636 * @hide 9637 */ 9638 public void setAccessibilitySelection(int start, int end) { 9639 if (start == end && end == mAccessibilityCursorPosition) { 9640 return; 9641 } 9642 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9643 mAccessibilityCursorPosition = start; 9644 } else { 9645 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9646 } 9647 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9648 } 9649 9650 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9651 int fromIndex, int toIndex) { 9652 if (mParent == null) { 9653 return; 9654 } 9655 AccessibilityEvent event = AccessibilityEvent.obtain( 9656 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9657 onInitializeAccessibilityEvent(event); 9658 onPopulateAccessibilityEvent(event); 9659 event.setFromIndex(fromIndex); 9660 event.setToIndex(toIndex); 9661 event.setAction(action); 9662 event.setMovementGranularity(granularity); 9663 mParent.requestSendAccessibilityEvent(this, event); 9664 } 9665 9666 /** 9667 * @hide 9668 */ 9669 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9670 switch (granularity) { 9671 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9672 CharSequence text = getIterableTextForAccessibility(); 9673 if (text != null && text.length() > 0) { 9674 CharacterTextSegmentIterator iterator = 9675 CharacterTextSegmentIterator.getInstance( 9676 mContext.getResources().getConfiguration().locale); 9677 iterator.initialize(text.toString()); 9678 return iterator; 9679 } 9680 } break; 9681 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9682 CharSequence text = getIterableTextForAccessibility(); 9683 if (text != null && text.length() > 0) { 9684 WordTextSegmentIterator iterator = 9685 WordTextSegmentIterator.getInstance( 9686 mContext.getResources().getConfiguration().locale); 9687 iterator.initialize(text.toString()); 9688 return iterator; 9689 } 9690 } break; 9691 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9692 CharSequence text = getIterableTextForAccessibility(); 9693 if (text != null && text.length() > 0) { 9694 ParagraphTextSegmentIterator iterator = 9695 ParagraphTextSegmentIterator.getInstance(); 9696 iterator.initialize(text.toString()); 9697 return iterator; 9698 } 9699 } break; 9700 } 9701 return null; 9702 } 9703 9704 /** 9705 * @hide 9706 */ 9707 public void dispatchStartTemporaryDetach() { 9708 onStartTemporaryDetach(); 9709 } 9710 9711 /** 9712 * This is called when a container is going to temporarily detach a child, with 9713 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9714 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9715 * {@link #onDetachedFromWindow()} when the container is done. 9716 */ 9717 public void onStartTemporaryDetach() { 9718 removeUnsetPressCallback(); 9719 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9720 } 9721 9722 /** 9723 * @hide 9724 */ 9725 public void dispatchFinishTemporaryDetach() { 9726 onFinishTemporaryDetach(); 9727 } 9728 9729 /** 9730 * Called after {@link #onStartTemporaryDetach} when the container is done 9731 * changing the view. 9732 */ 9733 public void onFinishTemporaryDetach() { 9734 } 9735 9736 /** 9737 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9738 * for this view's window. Returns null if the view is not currently attached 9739 * to the window. Normally you will not need to use this directly, but 9740 * just use the standard high-level event callbacks like 9741 * {@link #onKeyDown(int, KeyEvent)}. 9742 */ 9743 public KeyEvent.DispatcherState getKeyDispatcherState() { 9744 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9745 } 9746 9747 /** 9748 * Dispatch a key event before it is processed by any input method 9749 * associated with the view hierarchy. This can be used to intercept 9750 * key events in special situations before the IME consumes them; a 9751 * typical example would be handling the BACK key to update the application's 9752 * UI instead of allowing the IME to see it and close itself. 9753 * 9754 * @param event The key event to be dispatched. 9755 * @return True if the event was handled, false otherwise. 9756 */ 9757 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9758 return onKeyPreIme(event.getKeyCode(), event); 9759 } 9760 9761 /** 9762 * Dispatch a key event to the next view on the focus path. This path runs 9763 * from the top of the view tree down to the currently focused view. If this 9764 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9765 * the next node down the focus path. This method also fires any key 9766 * listeners. 9767 * 9768 * @param event The key event to be dispatched. 9769 * @return True if the event was handled, false otherwise. 9770 */ 9771 public boolean dispatchKeyEvent(KeyEvent event) { 9772 if (mInputEventConsistencyVerifier != null) { 9773 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9774 } 9775 9776 // Give any attached key listener a first crack at the event. 9777 //noinspection SimplifiableIfStatement 9778 ListenerInfo li = mListenerInfo; 9779 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9780 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9781 return true; 9782 } 9783 9784 if (event.dispatch(this, mAttachInfo != null 9785 ? mAttachInfo.mKeyDispatchState : null, this)) { 9786 return true; 9787 } 9788 9789 if (mInputEventConsistencyVerifier != null) { 9790 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9791 } 9792 return false; 9793 } 9794 9795 /** 9796 * Dispatches a key shortcut event. 9797 * 9798 * @param event The key event to be dispatched. 9799 * @return True if the event was handled by the view, false otherwise. 9800 */ 9801 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9802 return onKeyShortcut(event.getKeyCode(), event); 9803 } 9804 9805 /** 9806 * Pass the touch screen motion event down to the target view, or this 9807 * view if it is the target. 9808 * 9809 * @param event The motion event to be dispatched. 9810 * @return True if the event was handled by the view, false otherwise. 9811 */ 9812 public boolean dispatchTouchEvent(MotionEvent event) { 9813 // If the event should be handled by accessibility focus first. 9814 if (event.isTargetAccessibilityFocus()) { 9815 // We don't have focus or no virtual descendant has it, do not handle the event. 9816 if (!isAccessibilityFocusedViewOrHost()) { 9817 return false; 9818 } 9819 // We have focus and got the event, then use normal event dispatch. 9820 event.setTargetAccessibilityFocus(false); 9821 } 9822 9823 boolean result = false; 9824 9825 if (mInputEventConsistencyVerifier != null) { 9826 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9827 } 9828 9829 final int actionMasked = event.getActionMasked(); 9830 if (actionMasked == MotionEvent.ACTION_DOWN) { 9831 // Defensive cleanup for new gesture 9832 stopNestedScroll(); 9833 } 9834 9835 if (onFilterTouchEventForSecurity(event)) { 9836 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 9837 result = true; 9838 } 9839 //noinspection SimplifiableIfStatement 9840 ListenerInfo li = mListenerInfo; 9841 if (li != null && li.mOnTouchListener != null 9842 && (mViewFlags & ENABLED_MASK) == ENABLED 9843 && li.mOnTouchListener.onTouch(this, event)) { 9844 result = true; 9845 } 9846 9847 if (!result && onTouchEvent(event)) { 9848 result = true; 9849 } 9850 } 9851 9852 if (!result && mInputEventConsistencyVerifier != null) { 9853 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9854 } 9855 9856 // Clean up after nested scrolls if this is the end of a gesture; 9857 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 9858 // of the gesture. 9859 if (actionMasked == MotionEvent.ACTION_UP || 9860 actionMasked == MotionEvent.ACTION_CANCEL || 9861 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 9862 stopNestedScroll(); 9863 } 9864 9865 return result; 9866 } 9867 9868 boolean isAccessibilityFocusedViewOrHost() { 9869 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 9870 .getAccessibilityFocusedHost() == this); 9871 } 9872 9873 /** 9874 * Filter the touch event to apply security policies. 9875 * 9876 * @param event The motion event to be filtered. 9877 * @return True if the event should be dispatched, false if the event should be dropped. 9878 * 9879 * @see #getFilterTouchesWhenObscured 9880 */ 9881 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 9882 //noinspection RedundantIfStatement 9883 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 9884 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 9885 // Window is obscured, drop this touch. 9886 return false; 9887 } 9888 return true; 9889 } 9890 9891 /** 9892 * Pass a trackball motion event down to the focused view. 9893 * 9894 * @param event The motion event to be dispatched. 9895 * @return True if the event was handled by the view, false otherwise. 9896 */ 9897 public boolean dispatchTrackballEvent(MotionEvent event) { 9898 if (mInputEventConsistencyVerifier != null) { 9899 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 9900 } 9901 9902 return onTrackballEvent(event); 9903 } 9904 9905 /** 9906 * Dispatch a generic motion event. 9907 * <p> 9908 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9909 * are delivered to the view under the pointer. All other generic motion events are 9910 * delivered to the focused view. Hover events are handled specially and are delivered 9911 * to {@link #onHoverEvent(MotionEvent)}. 9912 * </p> 9913 * 9914 * @param event The motion event to be dispatched. 9915 * @return True if the event was handled by the view, false otherwise. 9916 */ 9917 public boolean dispatchGenericMotionEvent(MotionEvent event) { 9918 if (mInputEventConsistencyVerifier != null) { 9919 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 9920 } 9921 9922 final int source = event.getSource(); 9923 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 9924 final int action = event.getAction(); 9925 if (action == MotionEvent.ACTION_HOVER_ENTER 9926 || action == MotionEvent.ACTION_HOVER_MOVE 9927 || action == MotionEvent.ACTION_HOVER_EXIT) { 9928 if (dispatchHoverEvent(event)) { 9929 return true; 9930 } 9931 } else if (dispatchGenericPointerEvent(event)) { 9932 return true; 9933 } 9934 } else if (dispatchGenericFocusedEvent(event)) { 9935 return true; 9936 } 9937 9938 if (dispatchGenericMotionEventInternal(event)) { 9939 return true; 9940 } 9941 9942 if (mInputEventConsistencyVerifier != null) { 9943 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9944 } 9945 return false; 9946 } 9947 9948 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 9949 //noinspection SimplifiableIfStatement 9950 ListenerInfo li = mListenerInfo; 9951 if (li != null && li.mOnGenericMotionListener != null 9952 && (mViewFlags & ENABLED_MASK) == ENABLED 9953 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 9954 return true; 9955 } 9956 9957 if (onGenericMotionEvent(event)) { 9958 return true; 9959 } 9960 9961 final int actionButton = event.getActionButton(); 9962 switch (event.getActionMasked()) { 9963 case MotionEvent.ACTION_BUTTON_PRESS: 9964 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 9965 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 9966 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 9967 if (performContextClick()) { 9968 mInContextButtonPress = true; 9969 setPressed(true, event.getX(), event.getY()); 9970 removeTapCallback(); 9971 removeLongPressCallback(); 9972 return true; 9973 } 9974 } 9975 break; 9976 9977 case MotionEvent.ACTION_BUTTON_RELEASE: 9978 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 9979 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 9980 mInContextButtonPress = false; 9981 mIgnoreNextUpEvent = true; 9982 } 9983 break; 9984 } 9985 9986 if (mInputEventConsistencyVerifier != null) { 9987 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9988 } 9989 return false; 9990 } 9991 9992 /** 9993 * Dispatch a hover event. 9994 * <p> 9995 * Do not call this method directly. 9996 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 9997 * </p> 9998 * 9999 * @param event The motion event to be dispatched. 10000 * @return True if the event was handled by the view, false otherwise. 10001 */ 10002 protected boolean dispatchHoverEvent(MotionEvent event) { 10003 ListenerInfo li = mListenerInfo; 10004 //noinspection SimplifiableIfStatement 10005 if (li != null && li.mOnHoverListener != null 10006 && (mViewFlags & ENABLED_MASK) == ENABLED 10007 && li.mOnHoverListener.onHover(this, event)) { 10008 return true; 10009 } 10010 10011 return onHoverEvent(event); 10012 } 10013 10014 /** 10015 * Returns true if the view has a child to which it has recently sent 10016 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10017 * it does not have a hovered child, then it must be the innermost hovered view. 10018 * @hide 10019 */ 10020 protected boolean hasHoveredChild() { 10021 return false; 10022 } 10023 10024 /** 10025 * Dispatch a generic motion event to the view under the first pointer. 10026 * <p> 10027 * Do not call this method directly. 10028 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10029 * </p> 10030 * 10031 * @param event The motion event to be dispatched. 10032 * @return True if the event was handled by the view, false otherwise. 10033 */ 10034 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10035 return false; 10036 } 10037 10038 /** 10039 * Dispatch a generic motion event to the currently focused view. 10040 * <p> 10041 * Do not call this method directly. 10042 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10043 * </p> 10044 * 10045 * @param event The motion event to be dispatched. 10046 * @return True if the event was handled by the view, false otherwise. 10047 */ 10048 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10049 return false; 10050 } 10051 10052 /** 10053 * Dispatch a pointer event. 10054 * <p> 10055 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10056 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10057 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10058 * and should not be expected to handle other pointing device features. 10059 * </p> 10060 * 10061 * @param event The motion event to be dispatched. 10062 * @return True if the event was handled by the view, false otherwise. 10063 * @hide 10064 */ 10065 public final boolean dispatchPointerEvent(MotionEvent event) { 10066 if (event.isTouchEvent()) { 10067 return dispatchTouchEvent(event); 10068 } else { 10069 return dispatchGenericMotionEvent(event); 10070 } 10071 } 10072 10073 /** 10074 * Called when the window containing this view gains or loses window focus. 10075 * ViewGroups should override to route to their children. 10076 * 10077 * @param hasFocus True if the window containing this view now has focus, 10078 * false otherwise. 10079 */ 10080 public void dispatchWindowFocusChanged(boolean hasFocus) { 10081 onWindowFocusChanged(hasFocus); 10082 } 10083 10084 /** 10085 * Called when the window containing this view gains or loses focus. Note 10086 * that this is separate from view focus: to receive key events, both 10087 * your view and its window must have focus. If a window is displayed 10088 * on top of yours that takes input focus, then your own window will lose 10089 * focus but the view focus will remain unchanged. 10090 * 10091 * @param hasWindowFocus True if the window containing this view now has 10092 * focus, false otherwise. 10093 */ 10094 public void onWindowFocusChanged(boolean hasWindowFocus) { 10095 InputMethodManager imm = InputMethodManager.peekInstance(); 10096 if (!hasWindowFocus) { 10097 if (isPressed()) { 10098 setPressed(false); 10099 } 10100 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10101 imm.focusOut(this); 10102 } 10103 removeLongPressCallback(); 10104 removeTapCallback(); 10105 onFocusLost(); 10106 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10107 imm.focusIn(this); 10108 } 10109 refreshDrawableState(); 10110 } 10111 10112 /** 10113 * Returns true if this view is in a window that currently has window focus. 10114 * Note that this is not the same as the view itself having focus. 10115 * 10116 * @return True if this view is in a window that currently has window focus. 10117 */ 10118 public boolean hasWindowFocus() { 10119 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10120 } 10121 10122 /** 10123 * Dispatch a view visibility change down the view hierarchy. 10124 * ViewGroups should override to route to their children. 10125 * @param changedView The view whose visibility changed. Could be 'this' or 10126 * an ancestor view. 10127 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10128 * {@link #INVISIBLE} or {@link #GONE}. 10129 */ 10130 protected void dispatchVisibilityChanged(@NonNull View changedView, 10131 @Visibility int visibility) { 10132 onVisibilityChanged(changedView, visibility); 10133 } 10134 10135 /** 10136 * Called when the visibility of the view or an ancestor of the view has 10137 * changed. 10138 * 10139 * @param changedView The view whose visibility changed. May be 10140 * {@code this} or an ancestor view. 10141 * @param visibility The new visibility, one of {@link #VISIBLE}, 10142 * {@link #INVISIBLE} or {@link #GONE}. 10143 */ 10144 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10145 final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE; 10146 if (visible && mAttachInfo != null) { 10147 initialAwakenScrollBars(); 10148 } 10149 10150 final Drawable dr = mBackground; 10151 if (dr != null && visible != dr.isVisible()) { 10152 dr.setVisible(visible, false); 10153 } 10154 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10155 if (fg != null && visible != fg.isVisible()) { 10156 fg.setVisible(visible, false); 10157 } 10158 } 10159 10160 /** 10161 * Dispatch a hint about whether this view is displayed. For instance, when 10162 * a View moves out of the screen, it might receives a display hint indicating 10163 * the view is not displayed. Applications should not <em>rely</em> on this hint 10164 * as there is no guarantee that they will receive one. 10165 * 10166 * @param hint A hint about whether or not this view is displayed: 10167 * {@link #VISIBLE} or {@link #INVISIBLE}. 10168 */ 10169 public void dispatchDisplayHint(@Visibility int hint) { 10170 onDisplayHint(hint); 10171 } 10172 10173 /** 10174 * Gives this view a hint about whether is displayed or not. For instance, when 10175 * a View moves out of the screen, it might receives a display hint indicating 10176 * the view is not displayed. Applications should not <em>rely</em> on this hint 10177 * as there is no guarantee that they will receive one. 10178 * 10179 * @param hint A hint about whether or not this view is displayed: 10180 * {@link #VISIBLE} or {@link #INVISIBLE}. 10181 */ 10182 protected void onDisplayHint(@Visibility int hint) { 10183 } 10184 10185 /** 10186 * Dispatch a window visibility change down the view hierarchy. 10187 * ViewGroups should override to route to their children. 10188 * 10189 * @param visibility The new visibility of the window. 10190 * 10191 * @see #onWindowVisibilityChanged(int) 10192 */ 10193 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10194 onWindowVisibilityChanged(visibility); 10195 } 10196 10197 /** 10198 * Called when the window containing has change its visibility 10199 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10200 * that this tells you whether or not your window is being made visible 10201 * to the window manager; this does <em>not</em> tell you whether or not 10202 * your window is obscured by other windows on the screen, even if it 10203 * is itself visible. 10204 * 10205 * @param visibility The new visibility of the window. 10206 */ 10207 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10208 if (visibility == VISIBLE) { 10209 initialAwakenScrollBars(); 10210 } 10211 } 10212 10213 /** 10214 * Returns the current visibility of the window this view is attached to 10215 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10216 * 10217 * @return Returns the current visibility of the view's window. 10218 */ 10219 @Visibility 10220 public int getWindowVisibility() { 10221 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10222 } 10223 10224 /** 10225 * Retrieve the overall visible display size in which the window this view is 10226 * attached to has been positioned in. This takes into account screen 10227 * decorations above the window, for both cases where the window itself 10228 * is being position inside of them or the window is being placed under 10229 * then and covered insets are used for the window to position its content 10230 * inside. In effect, this tells you the available area where content can 10231 * be placed and remain visible to users. 10232 * 10233 * <p>This function requires an IPC back to the window manager to retrieve 10234 * the requested information, so should not be used in performance critical 10235 * code like drawing. 10236 * 10237 * @param outRect Filled in with the visible display frame. If the view 10238 * is not attached to a window, this is simply the raw display size. 10239 */ 10240 public void getWindowVisibleDisplayFrame(Rect outRect) { 10241 if (mAttachInfo != null) { 10242 try { 10243 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10244 } catch (RemoteException e) { 10245 return; 10246 } 10247 // XXX This is really broken, and probably all needs to be done 10248 // in the window manager, and we need to know more about whether 10249 // we want the area behind or in front of the IME. 10250 final Rect insets = mAttachInfo.mVisibleInsets; 10251 outRect.left += insets.left; 10252 outRect.top += insets.top; 10253 outRect.right -= insets.right; 10254 outRect.bottom -= insets.bottom; 10255 return; 10256 } 10257 // The view is not attached to a display so we don't have a context. 10258 // Make a best guess about the display size. 10259 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10260 d.getRectSize(outRect); 10261 } 10262 10263 /** 10264 * Dispatch a notification about a resource configuration change down 10265 * the view hierarchy. 10266 * ViewGroups should override to route to their children. 10267 * 10268 * @param newConfig The new resource configuration. 10269 * 10270 * @see #onConfigurationChanged(android.content.res.Configuration) 10271 */ 10272 public void dispatchConfigurationChanged(Configuration newConfig) { 10273 onConfigurationChanged(newConfig); 10274 } 10275 10276 /** 10277 * Called when the current configuration of the resources being used 10278 * by the application have changed. You can use this to decide when 10279 * to reload resources that can changed based on orientation and other 10280 * configuration characteristics. You only need to use this if you are 10281 * not relying on the normal {@link android.app.Activity} mechanism of 10282 * recreating the activity instance upon a configuration change. 10283 * 10284 * @param newConfig The new resource configuration. 10285 */ 10286 protected void onConfigurationChanged(Configuration newConfig) { 10287 } 10288 10289 /** 10290 * Private function to aggregate all per-view attributes in to the view 10291 * root. 10292 */ 10293 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10294 performCollectViewAttributes(attachInfo, visibility); 10295 } 10296 10297 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10298 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10299 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10300 attachInfo.mKeepScreenOn = true; 10301 } 10302 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10303 ListenerInfo li = mListenerInfo; 10304 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10305 attachInfo.mHasSystemUiListeners = true; 10306 } 10307 } 10308 } 10309 10310 void needGlobalAttributesUpdate(boolean force) { 10311 final AttachInfo ai = mAttachInfo; 10312 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10313 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10314 || ai.mHasSystemUiListeners) { 10315 ai.mRecomputeGlobalAttributes = true; 10316 } 10317 } 10318 } 10319 10320 /** 10321 * Returns whether the device is currently in touch mode. Touch mode is entered 10322 * once the user begins interacting with the device by touch, and affects various 10323 * things like whether focus is always visible to the user. 10324 * 10325 * @return Whether the device is in touch mode. 10326 */ 10327 @ViewDebug.ExportedProperty 10328 public boolean isInTouchMode() { 10329 if (mAttachInfo != null) { 10330 return mAttachInfo.mInTouchMode; 10331 } else { 10332 return ViewRootImpl.isInTouchMode(); 10333 } 10334 } 10335 10336 /** 10337 * Returns the context the view is running in, through which it can 10338 * access the current theme, resources, etc. 10339 * 10340 * @return The view's Context. 10341 */ 10342 @ViewDebug.CapturedViewProperty 10343 public final Context getContext() { 10344 return mContext; 10345 } 10346 10347 /** 10348 * Handle a key event before it is processed by any input method 10349 * associated with the view hierarchy. This can be used to intercept 10350 * key events in special situations before the IME consumes them; a 10351 * typical example would be handling the BACK key to update the application's 10352 * UI instead of allowing the IME to see it and close itself. 10353 * 10354 * @param keyCode The value in event.getKeyCode(). 10355 * @param event Description of the key event. 10356 * @return If you handled the event, return true. If you want to allow the 10357 * event to be handled by the next receiver, return false. 10358 */ 10359 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10360 return false; 10361 } 10362 10363 /** 10364 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10365 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10366 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10367 * is released, if the view is enabled and clickable. 10368 * <p> 10369 * Key presses in software keyboards will generally NOT trigger this 10370 * listener, although some may elect to do so in some situations. Do not 10371 * rely on this to catch software key presses. 10372 * 10373 * @param keyCode a key code that represents the button pressed, from 10374 * {@link android.view.KeyEvent} 10375 * @param event the KeyEvent object that defines the button action 10376 */ 10377 public boolean onKeyDown(int keyCode, KeyEvent event) { 10378 if (KeyEvent.isConfirmKey(keyCode)) { 10379 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10380 return true; 10381 } 10382 10383 // Long clickable items don't necessarily have to be clickable. 10384 if (((mViewFlags & CLICKABLE) == CLICKABLE 10385 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10386 && (event.getRepeatCount() == 0)) { 10387 // For the purposes of menu anchoring and drawable hotspots, 10388 // key events are considered to be at the center of the view. 10389 final float x = getWidth() / 2f; 10390 final float y = getHeight() / 2f; 10391 setPressed(true, x, y); 10392 checkForLongClick(0, x, y); 10393 return true; 10394 } 10395 } 10396 10397 return false; 10398 } 10399 10400 /** 10401 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10402 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10403 * the event). 10404 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10405 * although some may elect to do so in some situations. Do not rely on this to 10406 * catch software key presses. 10407 */ 10408 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10409 return false; 10410 } 10411 10412 /** 10413 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10414 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10415 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10416 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10417 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10418 * although some may elect to do so in some situations. Do not rely on this to 10419 * catch software key presses. 10420 * 10421 * @param keyCode A key code that represents the button pressed, from 10422 * {@link android.view.KeyEvent}. 10423 * @param event The KeyEvent object that defines the button action. 10424 */ 10425 public boolean onKeyUp(int keyCode, KeyEvent event) { 10426 if (KeyEvent.isConfirmKey(keyCode)) { 10427 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10428 return true; 10429 } 10430 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10431 setPressed(false); 10432 10433 if (!mHasPerformedLongPress) { 10434 // This is a tap, so remove the longpress check 10435 removeLongPressCallback(); 10436 return performClick(); 10437 } 10438 } 10439 } 10440 return false; 10441 } 10442 10443 /** 10444 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10445 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10446 * the event). 10447 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10448 * although some may elect to do so in some situations. Do not rely on this to 10449 * catch software key presses. 10450 * 10451 * @param keyCode A key code that represents the button pressed, from 10452 * {@link android.view.KeyEvent}. 10453 * @param repeatCount The number of times the action was made. 10454 * @param event The KeyEvent object that defines the button action. 10455 */ 10456 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10457 return false; 10458 } 10459 10460 /** 10461 * Called on the focused view when a key shortcut event is not handled. 10462 * Override this method to implement local key shortcuts for the View. 10463 * Key shortcuts can also be implemented by setting the 10464 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10465 * 10466 * @param keyCode The value in event.getKeyCode(). 10467 * @param event Description of the key event. 10468 * @return If you handled the event, return true. If you want to allow the 10469 * event to be handled by the next receiver, return false. 10470 */ 10471 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10472 return false; 10473 } 10474 10475 /** 10476 * Check whether the called view is a text editor, in which case it 10477 * would make sense to automatically display a soft input window for 10478 * it. Subclasses should override this if they implement 10479 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10480 * a call on that method would return a non-null InputConnection, and 10481 * they are really a first-class editor that the user would normally 10482 * start typing on when the go into a window containing your view. 10483 * 10484 * <p>The default implementation always returns false. This does 10485 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10486 * will not be called or the user can not otherwise perform edits on your 10487 * view; it is just a hint to the system that this is not the primary 10488 * purpose of this view. 10489 * 10490 * @return Returns true if this view is a text editor, else false. 10491 */ 10492 public boolean onCheckIsTextEditor() { 10493 return false; 10494 } 10495 10496 /** 10497 * Create a new InputConnection for an InputMethod to interact 10498 * with the view. The default implementation returns null, since it doesn't 10499 * support input methods. You can override this to implement such support. 10500 * This is only needed for views that take focus and text input. 10501 * 10502 * <p>When implementing this, you probably also want to implement 10503 * {@link #onCheckIsTextEditor()} to indicate you will return a 10504 * non-null InputConnection.</p> 10505 * 10506 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10507 * object correctly and in its entirety, so that the connected IME can rely 10508 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10509 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10510 * must be filled in with the correct cursor position for IMEs to work correctly 10511 * with your application.</p> 10512 * 10513 * @param outAttrs Fill in with attribute information about the connection. 10514 */ 10515 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10516 return null; 10517 } 10518 10519 /** 10520 * Called by the {@link android.view.inputmethod.InputMethodManager} 10521 * when a view who is not the current 10522 * input connection target is trying to make a call on the manager. The 10523 * default implementation returns false; you can override this to return 10524 * true for certain views if you are performing InputConnection proxying 10525 * to them. 10526 * @param view The View that is making the InputMethodManager call. 10527 * @return Return true to allow the call, false to reject. 10528 */ 10529 public boolean checkInputConnectionProxy(View view) { 10530 return false; 10531 } 10532 10533 /** 10534 * Show the context menu for this view. It is not safe to hold on to the 10535 * menu after returning from this method. 10536 * 10537 * You should normally not overload this method. Overload 10538 * {@link #onCreateContextMenu(ContextMenu)} or define an 10539 * {@link OnCreateContextMenuListener} to add items to the context menu. 10540 * 10541 * @param menu The context menu to populate 10542 */ 10543 public void createContextMenu(ContextMenu menu) { 10544 ContextMenuInfo menuInfo = getContextMenuInfo(); 10545 10546 // Sets the current menu info so all items added to menu will have 10547 // my extra info set. 10548 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10549 10550 onCreateContextMenu(menu); 10551 ListenerInfo li = mListenerInfo; 10552 if (li != null && li.mOnCreateContextMenuListener != null) { 10553 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10554 } 10555 10556 // Clear the extra information so subsequent items that aren't mine don't 10557 // have my extra info. 10558 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10559 10560 if (mParent != null) { 10561 mParent.createContextMenu(menu); 10562 } 10563 } 10564 10565 /** 10566 * Views should implement this if they have extra information to associate 10567 * with the context menu. The return result is supplied as a parameter to 10568 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10569 * callback. 10570 * 10571 * @return Extra information about the item for which the context menu 10572 * should be shown. This information will vary across different 10573 * subclasses of View. 10574 */ 10575 protected ContextMenuInfo getContextMenuInfo() { 10576 return null; 10577 } 10578 10579 /** 10580 * Views should implement this if the view itself is going to add items to 10581 * the context menu. 10582 * 10583 * @param menu the context menu to populate 10584 */ 10585 protected void onCreateContextMenu(ContextMenu menu) { 10586 } 10587 10588 /** 10589 * Implement this method to handle trackball motion events. The 10590 * <em>relative</em> movement of the trackball since the last event 10591 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10592 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10593 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10594 * they will often be fractional values, representing the more fine-grained 10595 * movement information available from a trackball). 10596 * 10597 * @param event The motion event. 10598 * @return True if the event was handled, false otherwise. 10599 */ 10600 public boolean onTrackballEvent(MotionEvent event) { 10601 return false; 10602 } 10603 10604 /** 10605 * Implement this method to handle generic motion events. 10606 * <p> 10607 * Generic motion events describe joystick movements, mouse hovers, track pad 10608 * touches, scroll wheel movements and other input events. The 10609 * {@link MotionEvent#getSource() source} of the motion event specifies 10610 * the class of input that was received. Implementations of this method 10611 * must examine the bits in the source before processing the event. 10612 * The following code example shows how this is done. 10613 * </p><p> 10614 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10615 * are delivered to the view under the pointer. All other generic motion events are 10616 * delivered to the focused view. 10617 * </p> 10618 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10619 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10620 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10621 * // process the joystick movement... 10622 * return true; 10623 * } 10624 * } 10625 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10626 * switch (event.getAction()) { 10627 * case MotionEvent.ACTION_HOVER_MOVE: 10628 * // process the mouse hover movement... 10629 * return true; 10630 * case MotionEvent.ACTION_SCROLL: 10631 * // process the scroll wheel movement... 10632 * return true; 10633 * } 10634 * } 10635 * return super.onGenericMotionEvent(event); 10636 * }</pre> 10637 * 10638 * @param event The generic motion event being processed. 10639 * @return True if the event was handled, false otherwise. 10640 */ 10641 public boolean onGenericMotionEvent(MotionEvent event) { 10642 return false; 10643 } 10644 10645 /** 10646 * Implement this method to handle hover events. 10647 * <p> 10648 * This method is called whenever a pointer is hovering into, over, or out of the 10649 * bounds of a view and the view is not currently being touched. 10650 * Hover events are represented as pointer events with action 10651 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10652 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10653 * </p> 10654 * <ul> 10655 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10656 * when the pointer enters the bounds of the view.</li> 10657 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10658 * when the pointer has already entered the bounds of the view and has moved.</li> 10659 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10660 * when the pointer has exited the bounds of the view or when the pointer is 10661 * about to go down due to a button click, tap, or similar user action that 10662 * causes the view to be touched.</li> 10663 * </ul> 10664 * <p> 10665 * The view should implement this method to return true to indicate that it is 10666 * handling the hover event, such as by changing its drawable state. 10667 * </p><p> 10668 * The default implementation calls {@link #setHovered} to update the hovered state 10669 * of the view when a hover enter or hover exit event is received, if the view 10670 * is enabled and is clickable. The default implementation also sends hover 10671 * accessibility events. 10672 * </p> 10673 * 10674 * @param event The motion event that describes the hover. 10675 * @return True if the view handled the hover event. 10676 * 10677 * @see #isHovered 10678 * @see #setHovered 10679 * @see #onHoverChanged 10680 */ 10681 public boolean onHoverEvent(MotionEvent event) { 10682 // The root view may receive hover (or touch) events that are outside the bounds of 10683 // the window. This code ensures that we only send accessibility events for 10684 // hovers that are actually within the bounds of the root view. 10685 final int action = event.getActionMasked(); 10686 if (!mSendingHoverAccessibilityEvents) { 10687 if ((action == MotionEvent.ACTION_HOVER_ENTER 10688 || action == MotionEvent.ACTION_HOVER_MOVE) 10689 && !hasHoveredChild() 10690 && pointInView(event.getX(), event.getY())) { 10691 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10692 mSendingHoverAccessibilityEvents = true; 10693 } 10694 } else { 10695 if (action == MotionEvent.ACTION_HOVER_EXIT 10696 || (action == MotionEvent.ACTION_MOVE 10697 && !pointInView(event.getX(), event.getY()))) { 10698 mSendingHoverAccessibilityEvents = false; 10699 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10700 } 10701 } 10702 10703 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10704 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10705 && isOnScrollbar(event.getX(), event.getY())) { 10706 awakenScrollBars(); 10707 } 10708 if (isHoverable()) { 10709 switch (action) { 10710 case MotionEvent.ACTION_HOVER_ENTER: 10711 setHovered(true); 10712 break; 10713 case MotionEvent.ACTION_HOVER_EXIT: 10714 setHovered(false); 10715 break; 10716 } 10717 10718 // Dispatch the event to onGenericMotionEvent before returning true. 10719 // This is to provide compatibility with existing applications that 10720 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10721 // break because of the new default handling for hoverable views 10722 // in onHoverEvent. 10723 // Note that onGenericMotionEvent will be called by default when 10724 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10725 dispatchGenericMotionEventInternal(event); 10726 // The event was already handled by calling setHovered(), so always 10727 // return true. 10728 return true; 10729 } 10730 10731 return false; 10732 } 10733 10734 /** 10735 * Returns true if the view should handle {@link #onHoverEvent} 10736 * by calling {@link #setHovered} to change its hovered state. 10737 * 10738 * @return True if the view is hoverable. 10739 */ 10740 private boolean isHoverable() { 10741 final int viewFlags = mViewFlags; 10742 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10743 return false; 10744 } 10745 10746 return (viewFlags & CLICKABLE) == CLICKABLE 10747 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10748 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10749 } 10750 10751 /** 10752 * Returns true if the view is currently hovered. 10753 * 10754 * @return True if the view is currently hovered. 10755 * 10756 * @see #setHovered 10757 * @see #onHoverChanged 10758 */ 10759 @ViewDebug.ExportedProperty 10760 public boolean isHovered() { 10761 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10762 } 10763 10764 /** 10765 * Sets whether the view is currently hovered. 10766 * <p> 10767 * Calling this method also changes the drawable state of the view. This 10768 * enables the view to react to hover by using different drawable resources 10769 * to change its appearance. 10770 * </p><p> 10771 * The {@link #onHoverChanged} method is called when the hovered state changes. 10772 * </p> 10773 * 10774 * @param hovered True if the view is hovered. 10775 * 10776 * @see #isHovered 10777 * @see #onHoverChanged 10778 */ 10779 public void setHovered(boolean hovered) { 10780 if (hovered) { 10781 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10782 mPrivateFlags |= PFLAG_HOVERED; 10783 refreshDrawableState(); 10784 onHoverChanged(true); 10785 } 10786 } else { 10787 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10788 mPrivateFlags &= ~PFLAG_HOVERED; 10789 refreshDrawableState(); 10790 onHoverChanged(false); 10791 } 10792 } 10793 } 10794 10795 /** 10796 * Implement this method to handle hover state changes. 10797 * <p> 10798 * This method is called whenever the hover state changes as a result of a 10799 * call to {@link #setHovered}. 10800 * </p> 10801 * 10802 * @param hovered The current hover state, as returned by {@link #isHovered}. 10803 * 10804 * @see #isHovered 10805 * @see #setHovered 10806 */ 10807 public void onHoverChanged(boolean hovered) { 10808 } 10809 10810 /** 10811 * Handles scroll bar dragging by mouse input. 10812 * 10813 * @hide 10814 * @param event The motion event. 10815 * 10816 * @return true if the event was handled as a scroll bar dragging, false otherwise. 10817 */ 10818 protected boolean handleScrollBarDragging(MotionEvent event) { 10819 if (mScrollCache == null) { 10820 return false; 10821 } 10822 final float x = event.getX(); 10823 final float y = event.getY(); 10824 final int action = event.getAction(); 10825 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 10826 && action != MotionEvent.ACTION_DOWN) 10827 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 10828 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 10829 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 10830 return false; 10831 } 10832 10833 switch (action) { 10834 case MotionEvent.ACTION_MOVE: 10835 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 10836 return false; 10837 } 10838 if (mScrollCache.mScrollBarDraggingState 10839 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 10840 final Rect bounds = mScrollCache.mScrollBarBounds; 10841 getVerticalScrollBarBounds(bounds); 10842 final int range = computeVerticalScrollRange(); 10843 final int offset = computeVerticalScrollOffset(); 10844 final int extent = computeVerticalScrollExtent(); 10845 10846 final int thumbLength = ScrollBarUtils.getThumbLength( 10847 bounds.height(), bounds.width(), extent, range); 10848 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10849 bounds.height(), thumbLength, extent, range, offset); 10850 10851 final float diff = y - mScrollCache.mScrollBarDraggingPos; 10852 final float maxThumbOffset = bounds.height() - thumbLength; 10853 final float newThumbOffset = 10854 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 10855 final int height = getHeight(); 10856 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 10857 && height > 0 && extent > 0) { 10858 final int newY = Math.round((range - extent) 10859 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 10860 if (newY != getScrollY()) { 10861 mScrollCache.mScrollBarDraggingPos = y; 10862 setScrollY(newY); 10863 } 10864 } 10865 return true; 10866 } 10867 if (mScrollCache.mScrollBarDraggingState 10868 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 10869 final Rect bounds = mScrollCache.mScrollBarBounds; 10870 getHorizontalScrollBarBounds(bounds); 10871 final int range = computeHorizontalScrollRange(); 10872 final int offset = computeHorizontalScrollOffset(); 10873 final int extent = computeHorizontalScrollExtent(); 10874 10875 final int thumbLength = ScrollBarUtils.getThumbLength( 10876 bounds.width(), bounds.height(), extent, range); 10877 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10878 bounds.width(), thumbLength, extent, range, offset); 10879 10880 final float diff = x - mScrollCache.mScrollBarDraggingPos; 10881 final float maxThumbOffset = bounds.width() - thumbLength; 10882 final float newThumbOffset = 10883 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 10884 final int width = getWidth(); 10885 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 10886 && width > 0 && extent > 0) { 10887 final int newX = Math.round((range - extent) 10888 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 10889 if (newX != getScrollX()) { 10890 mScrollCache.mScrollBarDraggingPos = x; 10891 setScrollX(newX); 10892 } 10893 } 10894 return true; 10895 } 10896 case MotionEvent.ACTION_DOWN: 10897 if (isOnVerticalScrollbarThumb(x, y)) { 10898 mScrollCache.mScrollBarDraggingState = 10899 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 10900 mScrollCache.mScrollBarDraggingPos = y; 10901 return true; 10902 } 10903 if (isOnHorizontalScrollbarThumb(x, y)) { 10904 mScrollCache.mScrollBarDraggingState = 10905 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 10906 mScrollCache.mScrollBarDraggingPos = x; 10907 return true; 10908 } 10909 } 10910 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 10911 return false; 10912 } 10913 10914 /** 10915 * Implement this method to handle touch screen motion events. 10916 * <p> 10917 * If this method is used to detect click actions, it is recommended that 10918 * the actions be performed by implementing and calling 10919 * {@link #performClick()}. This will ensure consistent system behavior, 10920 * including: 10921 * <ul> 10922 * <li>obeying click sound preferences 10923 * <li>dispatching OnClickListener calls 10924 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 10925 * accessibility features are enabled 10926 * </ul> 10927 * 10928 * @param event The motion event. 10929 * @return True if the event was handled, false otherwise. 10930 */ 10931 public boolean onTouchEvent(MotionEvent event) { 10932 final float x = event.getX(); 10933 final float y = event.getY(); 10934 final int viewFlags = mViewFlags; 10935 final int action = event.getAction(); 10936 10937 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10938 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 10939 setPressed(false); 10940 } 10941 // A disabled view that is clickable still consumes the touch 10942 // events, it just doesn't respond to them. 10943 return (((viewFlags & CLICKABLE) == CLICKABLE 10944 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10945 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 10946 } 10947 if (mTouchDelegate != null) { 10948 if (mTouchDelegate.onTouchEvent(event)) { 10949 return true; 10950 } 10951 } 10952 10953 if (((viewFlags & CLICKABLE) == CLICKABLE || 10954 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 10955 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 10956 switch (action) { 10957 case MotionEvent.ACTION_UP: 10958 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 10959 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 10960 // take focus if we don't have it already and we should in 10961 // touch mode. 10962 boolean focusTaken = false; 10963 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 10964 focusTaken = requestFocus(); 10965 } 10966 10967 if (prepressed) { 10968 // The button is being released before we actually 10969 // showed it as pressed. Make it show the pressed 10970 // state now (before scheduling the click) to ensure 10971 // the user sees it. 10972 setPressed(true, x, y); 10973 } 10974 10975 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 10976 // This is a tap, so remove the longpress check 10977 removeLongPressCallback(); 10978 10979 // Only perform take click actions if we were in the pressed state 10980 if (!focusTaken) { 10981 // Use a Runnable and post this rather than calling 10982 // performClick directly. This lets other visual state 10983 // of the view update before click actions start. 10984 if (mPerformClick == null) { 10985 mPerformClick = new PerformClick(); 10986 } 10987 if (!post(mPerformClick)) { 10988 performClick(); 10989 } 10990 } 10991 } 10992 10993 if (mUnsetPressedState == null) { 10994 mUnsetPressedState = new UnsetPressedState(); 10995 } 10996 10997 if (prepressed) { 10998 postDelayed(mUnsetPressedState, 10999 ViewConfiguration.getPressedStateDuration()); 11000 } else if (!post(mUnsetPressedState)) { 11001 // If the post failed, unpress right now 11002 mUnsetPressedState.run(); 11003 } 11004 11005 removeTapCallback(); 11006 } 11007 mIgnoreNextUpEvent = false; 11008 break; 11009 11010 case MotionEvent.ACTION_DOWN: 11011 mHasPerformedLongPress = false; 11012 11013 if (performButtonActionOnTouchDown(event)) { 11014 break; 11015 } 11016 11017 // Walk up the hierarchy to determine if we're inside a scrolling container. 11018 boolean isInScrollingContainer = isInScrollingContainer(); 11019 11020 // For views inside a scrolling container, delay the pressed feedback for 11021 // a short period in case this is a scroll. 11022 if (isInScrollingContainer) { 11023 mPrivateFlags |= PFLAG_PREPRESSED; 11024 if (mPendingCheckForTap == null) { 11025 mPendingCheckForTap = new CheckForTap(); 11026 } 11027 mPendingCheckForTap.x = event.getX(); 11028 mPendingCheckForTap.y = event.getY(); 11029 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11030 } else { 11031 // Not inside a scrolling container, so show the feedback right away 11032 setPressed(true, x, y); 11033 checkForLongClick(0, x, y); 11034 } 11035 break; 11036 11037 case MotionEvent.ACTION_CANCEL: 11038 setPressed(false); 11039 removeTapCallback(); 11040 removeLongPressCallback(); 11041 mInContextButtonPress = false; 11042 mHasPerformedLongPress = false; 11043 mIgnoreNextUpEvent = false; 11044 break; 11045 11046 case MotionEvent.ACTION_MOVE: 11047 drawableHotspotChanged(x, y); 11048 11049 // Be lenient about moving outside of buttons 11050 if (!pointInView(x, y, mTouchSlop)) { 11051 // Outside button 11052 removeTapCallback(); 11053 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11054 // Remove any future long press/tap checks 11055 removeLongPressCallback(); 11056 11057 setPressed(false); 11058 } 11059 } 11060 break; 11061 } 11062 11063 return true; 11064 } 11065 11066 return false; 11067 } 11068 11069 /** 11070 * @hide 11071 */ 11072 public boolean isInScrollingContainer() { 11073 ViewParent p = getParent(); 11074 while (p != null && p instanceof ViewGroup) { 11075 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11076 return true; 11077 } 11078 p = p.getParent(); 11079 } 11080 return false; 11081 } 11082 11083 /** 11084 * Remove the longpress detection timer. 11085 */ 11086 private void removeLongPressCallback() { 11087 if (mPendingCheckForLongPress != null) { 11088 removeCallbacks(mPendingCheckForLongPress); 11089 } 11090 } 11091 11092 /** 11093 * Remove the pending click action 11094 */ 11095 private void removePerformClickCallback() { 11096 if (mPerformClick != null) { 11097 removeCallbacks(mPerformClick); 11098 } 11099 } 11100 11101 /** 11102 * Remove the prepress detection timer. 11103 */ 11104 private void removeUnsetPressCallback() { 11105 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11106 setPressed(false); 11107 removeCallbacks(mUnsetPressedState); 11108 } 11109 } 11110 11111 /** 11112 * Remove the tap detection timer. 11113 */ 11114 private void removeTapCallback() { 11115 if (mPendingCheckForTap != null) { 11116 mPrivateFlags &= ~PFLAG_PREPRESSED; 11117 removeCallbacks(mPendingCheckForTap); 11118 } 11119 } 11120 11121 /** 11122 * Cancels a pending long press. Your subclass can use this if you 11123 * want the context menu to come up if the user presses and holds 11124 * at the same place, but you don't want it to come up if they press 11125 * and then move around enough to cause scrolling. 11126 */ 11127 public void cancelLongPress() { 11128 removeLongPressCallback(); 11129 11130 /* 11131 * The prepressed state handled by the tap callback is a display 11132 * construct, but the tap callback will post a long press callback 11133 * less its own timeout. Remove it here. 11134 */ 11135 removeTapCallback(); 11136 } 11137 11138 /** 11139 * Remove the pending callback for sending a 11140 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11141 */ 11142 private void removeSendViewScrolledAccessibilityEventCallback() { 11143 if (mSendViewScrolledAccessibilityEvent != null) { 11144 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11145 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11146 } 11147 } 11148 11149 /** 11150 * Sets the TouchDelegate for this View. 11151 */ 11152 public void setTouchDelegate(TouchDelegate delegate) { 11153 mTouchDelegate = delegate; 11154 } 11155 11156 /** 11157 * Gets the TouchDelegate for this View. 11158 */ 11159 public TouchDelegate getTouchDelegate() { 11160 return mTouchDelegate; 11161 } 11162 11163 /** 11164 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11165 * 11166 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11167 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11168 * available. This method should only be called for touch events. 11169 * 11170 * <p class="note">This api is not intended for most applications. Buffered dispatch 11171 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11172 * streams will not improve your input latency. Side effects include: increased latency, 11173 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11174 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11175 * you.</p> 11176 */ 11177 public final void requestUnbufferedDispatch(MotionEvent event) { 11178 final int action = event.getAction(); 11179 if (mAttachInfo == null 11180 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11181 || !event.isTouchEvent()) { 11182 return; 11183 } 11184 mAttachInfo.mUnbufferedDispatchRequested = true; 11185 } 11186 11187 /** 11188 * Set flags controlling behavior of this view. 11189 * 11190 * @param flags Constant indicating the value which should be set 11191 * @param mask Constant indicating the bit range that should be changed 11192 */ 11193 void setFlags(int flags, int mask) { 11194 final boolean accessibilityEnabled = 11195 AccessibilityManager.getInstance(mContext).isEnabled(); 11196 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11197 11198 int old = mViewFlags; 11199 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11200 11201 int changed = mViewFlags ^ old; 11202 if (changed == 0) { 11203 return; 11204 } 11205 int privateFlags = mPrivateFlags; 11206 11207 /* Check if the FOCUSABLE bit has changed */ 11208 if (((changed & FOCUSABLE_MASK) != 0) && 11209 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11210 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11211 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11212 /* Give up focus if we are no longer focusable */ 11213 clearFocus(); 11214 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11215 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11216 /* 11217 * Tell the view system that we are now available to take focus 11218 * if no one else already has it. 11219 */ 11220 if (mParent != null) mParent.focusableViewAvailable(this); 11221 } 11222 } 11223 11224 final int newVisibility = flags & VISIBILITY_MASK; 11225 if (newVisibility == VISIBLE) { 11226 if ((changed & VISIBILITY_MASK) != 0) { 11227 /* 11228 * If this view is becoming visible, invalidate it in case it changed while 11229 * it was not visible. Marking it drawn ensures that the invalidation will 11230 * go through. 11231 */ 11232 mPrivateFlags |= PFLAG_DRAWN; 11233 invalidate(true); 11234 11235 needGlobalAttributesUpdate(true); 11236 11237 // a view becoming visible is worth notifying the parent 11238 // about in case nothing has focus. even if this specific view 11239 // isn't focusable, it may contain something that is, so let 11240 // the root view try to give this focus if nothing else does. 11241 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11242 mParent.focusableViewAvailable(this); 11243 } 11244 } 11245 } 11246 11247 /* Check if the GONE bit has changed */ 11248 if ((changed & GONE) != 0) { 11249 needGlobalAttributesUpdate(false); 11250 requestLayout(); 11251 11252 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11253 if (hasFocus()) clearFocus(); 11254 clearAccessibilityFocus(); 11255 destroyDrawingCache(); 11256 if (mParent instanceof View) { 11257 // GONE views noop invalidation, so invalidate the parent 11258 ((View) mParent).invalidate(true); 11259 } 11260 // Mark the view drawn to ensure that it gets invalidated properly the next 11261 // time it is visible and gets invalidated 11262 mPrivateFlags |= PFLAG_DRAWN; 11263 } 11264 if (mAttachInfo != null) { 11265 mAttachInfo.mViewVisibilityChanged = true; 11266 } 11267 } 11268 11269 /* Check if the VISIBLE bit has changed */ 11270 if ((changed & INVISIBLE) != 0) { 11271 needGlobalAttributesUpdate(false); 11272 /* 11273 * If this view is becoming invisible, set the DRAWN flag so that 11274 * the next invalidate() will not be skipped. 11275 */ 11276 mPrivateFlags |= PFLAG_DRAWN; 11277 11278 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11279 // root view becoming invisible shouldn't clear focus and accessibility focus 11280 if (getRootView() != this) { 11281 if (hasFocus()) clearFocus(); 11282 clearAccessibilityFocus(); 11283 } 11284 } 11285 if (mAttachInfo != null) { 11286 mAttachInfo.mViewVisibilityChanged = true; 11287 } 11288 } 11289 11290 if ((changed & VISIBILITY_MASK) != 0) { 11291 // If the view is invisible, cleanup its display list to free up resources 11292 if (newVisibility != VISIBLE && mAttachInfo != null) { 11293 cleanupDraw(); 11294 } 11295 11296 if (mParent instanceof ViewGroup) { 11297 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11298 (changed & VISIBILITY_MASK), newVisibility); 11299 ((View) mParent).invalidate(true); 11300 } else if (mParent != null) { 11301 mParent.invalidateChild(this, null); 11302 } 11303 11304 if (mAttachInfo != null) { 11305 dispatchVisibilityChanged(this, newVisibility); 11306 notifySubtreeAccessibilityStateChangedIfNeeded(); 11307 } 11308 } 11309 11310 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11311 destroyDrawingCache(); 11312 } 11313 11314 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11315 destroyDrawingCache(); 11316 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11317 invalidateParentCaches(); 11318 } 11319 11320 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11321 destroyDrawingCache(); 11322 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11323 } 11324 11325 if ((changed & DRAW_MASK) != 0) { 11326 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11327 if (mBackground != null 11328 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11329 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11330 } else { 11331 mPrivateFlags |= PFLAG_SKIP_DRAW; 11332 } 11333 } else { 11334 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11335 } 11336 requestLayout(); 11337 invalidate(true); 11338 } 11339 11340 if ((changed & KEEP_SCREEN_ON) != 0) { 11341 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11342 mParent.recomputeViewAttributes(this); 11343 } 11344 } 11345 11346 if (accessibilityEnabled) { 11347 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11348 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11349 || (changed & CONTEXT_CLICKABLE) != 0) { 11350 if (oldIncludeForAccessibility != includeForAccessibility()) { 11351 notifySubtreeAccessibilityStateChangedIfNeeded(); 11352 } else { 11353 notifyViewAccessibilityStateChangedIfNeeded( 11354 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11355 } 11356 } else if ((changed & ENABLED_MASK) != 0) { 11357 notifyViewAccessibilityStateChangedIfNeeded( 11358 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11359 } 11360 } 11361 } 11362 11363 /** 11364 * Change the view's z order in the tree, so it's on top of other sibling 11365 * views. This ordering change may affect layout, if the parent container 11366 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11367 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11368 * method should be followed by calls to {@link #requestLayout()} and 11369 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11370 * with the new child ordering. 11371 * 11372 * @see ViewGroup#bringChildToFront(View) 11373 */ 11374 public void bringToFront() { 11375 if (mParent != null) { 11376 mParent.bringChildToFront(this); 11377 } 11378 } 11379 11380 /** 11381 * This is called in response to an internal scroll in this view (i.e., the 11382 * view scrolled its own contents). This is typically as a result of 11383 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11384 * called. 11385 * 11386 * @param l Current horizontal scroll origin. 11387 * @param t Current vertical scroll origin. 11388 * @param oldl Previous horizontal scroll origin. 11389 * @param oldt Previous vertical scroll origin. 11390 */ 11391 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11392 notifySubtreeAccessibilityStateChangedIfNeeded(); 11393 11394 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11395 postSendViewScrolledAccessibilityEventCallback(); 11396 } 11397 11398 mBackgroundSizeChanged = true; 11399 if (mForegroundInfo != null) { 11400 mForegroundInfo.mBoundsChanged = true; 11401 } 11402 11403 final AttachInfo ai = mAttachInfo; 11404 if (ai != null) { 11405 ai.mViewScrollChanged = true; 11406 } 11407 11408 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11409 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11410 } 11411 } 11412 11413 /** 11414 * Interface definition for a callback to be invoked when the scroll 11415 * X or Y positions of a view change. 11416 * <p> 11417 * <b>Note:</b> Some views handle scrolling independently from View and may 11418 * have their own separate listeners for scroll-type events. For example, 11419 * {@link android.widget.ListView ListView} allows clients to register an 11420 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11421 * to listen for changes in list scroll position. 11422 * 11423 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11424 */ 11425 public interface OnScrollChangeListener { 11426 /** 11427 * Called when the scroll position of a view changes. 11428 * 11429 * @param v The view whose scroll position has changed. 11430 * @param scrollX Current horizontal scroll origin. 11431 * @param scrollY Current vertical scroll origin. 11432 * @param oldScrollX Previous horizontal scroll origin. 11433 * @param oldScrollY Previous vertical scroll origin. 11434 */ 11435 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11436 } 11437 11438 /** 11439 * Interface definition for a callback to be invoked when the layout bounds of a view 11440 * changes due to layout processing. 11441 */ 11442 public interface OnLayoutChangeListener { 11443 /** 11444 * Called when the layout bounds of a view changes due to layout processing. 11445 * 11446 * @param v The view whose bounds have changed. 11447 * @param left The new value of the view's left property. 11448 * @param top The new value of the view's top property. 11449 * @param right The new value of the view's right property. 11450 * @param bottom The new value of the view's bottom property. 11451 * @param oldLeft The previous value of the view's left property. 11452 * @param oldTop The previous value of the view's top property. 11453 * @param oldRight The previous value of the view's right property. 11454 * @param oldBottom The previous value of the view's bottom property. 11455 */ 11456 void onLayoutChange(View v, int left, int top, int right, int bottom, 11457 int oldLeft, int oldTop, int oldRight, int oldBottom); 11458 } 11459 11460 /** 11461 * This is called during layout when the size of this view has changed. If 11462 * you were just added to the view hierarchy, you're called with the old 11463 * values of 0. 11464 * 11465 * @param w Current width of this view. 11466 * @param h Current height of this view. 11467 * @param oldw Old width of this view. 11468 * @param oldh Old height of this view. 11469 */ 11470 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11471 } 11472 11473 /** 11474 * Called by draw to draw the child views. This may be overridden 11475 * by derived classes to gain control just before its children are drawn 11476 * (but after its own view has been drawn). 11477 * @param canvas the canvas on which to draw the view 11478 */ 11479 protected void dispatchDraw(Canvas canvas) { 11480 11481 } 11482 11483 /** 11484 * Gets the parent of this view. Note that the parent is a 11485 * ViewParent and not necessarily a View. 11486 * 11487 * @return Parent of this view. 11488 */ 11489 public final ViewParent getParent() { 11490 return mParent; 11491 } 11492 11493 /** 11494 * Set the horizontal scrolled position of your view. This will cause a call to 11495 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11496 * invalidated. 11497 * @param value the x position to scroll to 11498 */ 11499 public void setScrollX(int value) { 11500 scrollTo(value, mScrollY); 11501 } 11502 11503 /** 11504 * Set the vertical scrolled position of your view. This will cause a call to 11505 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11506 * invalidated. 11507 * @param value the y position to scroll to 11508 */ 11509 public void setScrollY(int value) { 11510 scrollTo(mScrollX, value); 11511 } 11512 11513 /** 11514 * Return the scrolled left position of this view. This is the left edge of 11515 * the displayed part of your view. You do not need to draw any pixels 11516 * farther left, since those are outside of the frame of your view on 11517 * screen. 11518 * 11519 * @return The left edge of the displayed part of your view, in pixels. 11520 */ 11521 public final int getScrollX() { 11522 return mScrollX; 11523 } 11524 11525 /** 11526 * Return the scrolled top position of this view. This is the top edge of 11527 * the displayed part of your view. You do not need to draw any pixels above 11528 * it, since those are outside of the frame of your view on screen. 11529 * 11530 * @return The top edge of the displayed part of your view, in pixels. 11531 */ 11532 public final int getScrollY() { 11533 return mScrollY; 11534 } 11535 11536 /** 11537 * Return the width of the your view. 11538 * 11539 * @return The width of your view, in pixels. 11540 */ 11541 @ViewDebug.ExportedProperty(category = "layout") 11542 public final int getWidth() { 11543 return mRight - mLeft; 11544 } 11545 11546 /** 11547 * Return the height of your view. 11548 * 11549 * @return The height of your view, in pixels. 11550 */ 11551 @ViewDebug.ExportedProperty(category = "layout") 11552 public final int getHeight() { 11553 return mBottom - mTop; 11554 } 11555 11556 /** 11557 * Return the visible drawing bounds of your view. Fills in the output 11558 * rectangle with the values from getScrollX(), getScrollY(), 11559 * getWidth(), and getHeight(). These bounds do not account for any 11560 * transformation properties currently set on the view, such as 11561 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11562 * 11563 * @param outRect The (scrolled) drawing bounds of the view. 11564 */ 11565 public void getDrawingRect(Rect outRect) { 11566 outRect.left = mScrollX; 11567 outRect.top = mScrollY; 11568 outRect.right = mScrollX + (mRight - mLeft); 11569 outRect.bottom = mScrollY + (mBottom - mTop); 11570 } 11571 11572 /** 11573 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11574 * raw width component (that is the result is masked by 11575 * {@link #MEASURED_SIZE_MASK}). 11576 * 11577 * @return The raw measured width of this view. 11578 */ 11579 public final int getMeasuredWidth() { 11580 return mMeasuredWidth & MEASURED_SIZE_MASK; 11581 } 11582 11583 /** 11584 * Return the full width measurement information for this view as computed 11585 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11586 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11587 * This should be used during measurement and layout calculations only. Use 11588 * {@link #getWidth()} to see how wide a view is after layout. 11589 * 11590 * @return The measured width of this view as a bit mask. 11591 */ 11592 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11593 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11594 name = "MEASURED_STATE_TOO_SMALL"), 11595 }) 11596 public final int getMeasuredWidthAndState() { 11597 return mMeasuredWidth; 11598 } 11599 11600 /** 11601 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11602 * raw width component (that is the result is masked by 11603 * {@link #MEASURED_SIZE_MASK}). 11604 * 11605 * @return The raw measured height of this view. 11606 */ 11607 public final int getMeasuredHeight() { 11608 return mMeasuredHeight & MEASURED_SIZE_MASK; 11609 } 11610 11611 /** 11612 * Return the full height measurement information for this view as computed 11613 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11614 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11615 * This should be used during measurement and layout calculations only. Use 11616 * {@link #getHeight()} to see how wide a view is after layout. 11617 * 11618 * @return The measured width of this view as a bit mask. 11619 */ 11620 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11621 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11622 name = "MEASURED_STATE_TOO_SMALL"), 11623 }) 11624 public final int getMeasuredHeightAndState() { 11625 return mMeasuredHeight; 11626 } 11627 11628 /** 11629 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11630 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11631 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11632 * and the height component is at the shifted bits 11633 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11634 */ 11635 public final int getMeasuredState() { 11636 return (mMeasuredWidth&MEASURED_STATE_MASK) 11637 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11638 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11639 } 11640 11641 /** 11642 * The transform matrix of this view, which is calculated based on the current 11643 * rotation, scale, and pivot properties. 11644 * 11645 * @see #getRotation() 11646 * @see #getScaleX() 11647 * @see #getScaleY() 11648 * @see #getPivotX() 11649 * @see #getPivotY() 11650 * @return The current transform matrix for the view 11651 */ 11652 public Matrix getMatrix() { 11653 ensureTransformationInfo(); 11654 final Matrix matrix = mTransformationInfo.mMatrix; 11655 mRenderNode.getMatrix(matrix); 11656 return matrix; 11657 } 11658 11659 /** 11660 * Returns true if the transform matrix is the identity matrix. 11661 * Recomputes the matrix if necessary. 11662 * 11663 * @return True if the transform matrix is the identity matrix, false otherwise. 11664 */ 11665 final boolean hasIdentityMatrix() { 11666 return mRenderNode.hasIdentityMatrix(); 11667 } 11668 11669 void ensureTransformationInfo() { 11670 if (mTransformationInfo == null) { 11671 mTransformationInfo = new TransformationInfo(); 11672 } 11673 } 11674 11675 /** 11676 * Utility method to retrieve the inverse of the current mMatrix property. 11677 * We cache the matrix to avoid recalculating it when transform properties 11678 * have not changed. 11679 * 11680 * @return The inverse of the current matrix of this view. 11681 * @hide 11682 */ 11683 public final Matrix getInverseMatrix() { 11684 ensureTransformationInfo(); 11685 if (mTransformationInfo.mInverseMatrix == null) { 11686 mTransformationInfo.mInverseMatrix = new Matrix(); 11687 } 11688 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11689 mRenderNode.getInverseMatrix(matrix); 11690 return matrix; 11691 } 11692 11693 /** 11694 * Gets the distance along the Z axis from the camera to this view. 11695 * 11696 * @see #setCameraDistance(float) 11697 * 11698 * @return The distance along the Z axis. 11699 */ 11700 public float getCameraDistance() { 11701 final float dpi = mResources.getDisplayMetrics().densityDpi; 11702 return -(mRenderNode.getCameraDistance() * dpi); 11703 } 11704 11705 /** 11706 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11707 * views are drawn) from the camera to this view. The camera's distance 11708 * affects 3D transformations, for instance rotations around the X and Y 11709 * axis. If the rotationX or rotationY properties are changed and this view is 11710 * large (more than half the size of the screen), it is recommended to always 11711 * use a camera distance that's greater than the height (X axis rotation) or 11712 * the width (Y axis rotation) of this view.</p> 11713 * 11714 * <p>The distance of the camera from the view plane can have an affect on the 11715 * perspective distortion of the view when it is rotated around the x or y axis. 11716 * For example, a large distance will result in a large viewing angle, and there 11717 * will not be much perspective distortion of the view as it rotates. A short 11718 * distance may cause much more perspective distortion upon rotation, and can 11719 * also result in some drawing artifacts if the rotated view ends up partially 11720 * behind the camera (which is why the recommendation is to use a distance at 11721 * least as far as the size of the view, if the view is to be rotated.)</p> 11722 * 11723 * <p>The distance is expressed in "depth pixels." The default distance depends 11724 * on the screen density. For instance, on a medium density display, the 11725 * default distance is 1280. On a high density display, the default distance 11726 * is 1920.</p> 11727 * 11728 * <p>If you want to specify a distance that leads to visually consistent 11729 * results across various densities, use the following formula:</p> 11730 * <pre> 11731 * float scale = context.getResources().getDisplayMetrics().density; 11732 * view.setCameraDistance(distance * scale); 11733 * </pre> 11734 * 11735 * <p>The density scale factor of a high density display is 1.5, 11736 * and 1920 = 1280 * 1.5.</p> 11737 * 11738 * @param distance The distance in "depth pixels", if negative the opposite 11739 * value is used 11740 * 11741 * @see #setRotationX(float) 11742 * @see #setRotationY(float) 11743 */ 11744 public void setCameraDistance(float distance) { 11745 final float dpi = mResources.getDisplayMetrics().densityDpi; 11746 11747 invalidateViewProperty(true, false); 11748 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11749 invalidateViewProperty(false, false); 11750 11751 invalidateParentIfNeededAndWasQuickRejected(); 11752 } 11753 11754 /** 11755 * The degrees that the view is rotated around the pivot point. 11756 * 11757 * @see #setRotation(float) 11758 * @see #getPivotX() 11759 * @see #getPivotY() 11760 * 11761 * @return The degrees of rotation. 11762 */ 11763 @ViewDebug.ExportedProperty(category = "drawing") 11764 public float getRotation() { 11765 return mRenderNode.getRotation(); 11766 } 11767 11768 /** 11769 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11770 * result in clockwise rotation. 11771 * 11772 * @param rotation The degrees of rotation. 11773 * 11774 * @see #getRotation() 11775 * @see #getPivotX() 11776 * @see #getPivotY() 11777 * @see #setRotationX(float) 11778 * @see #setRotationY(float) 11779 * 11780 * @attr ref android.R.styleable#View_rotation 11781 */ 11782 public void setRotation(float rotation) { 11783 if (rotation != getRotation()) { 11784 // Double-invalidation is necessary to capture view's old and new areas 11785 invalidateViewProperty(true, false); 11786 mRenderNode.setRotation(rotation); 11787 invalidateViewProperty(false, true); 11788 11789 invalidateParentIfNeededAndWasQuickRejected(); 11790 notifySubtreeAccessibilityStateChangedIfNeeded(); 11791 } 11792 } 11793 11794 /** 11795 * The degrees that the view is rotated around the vertical axis through the pivot point. 11796 * 11797 * @see #getPivotX() 11798 * @see #getPivotY() 11799 * @see #setRotationY(float) 11800 * 11801 * @return The degrees of Y rotation. 11802 */ 11803 @ViewDebug.ExportedProperty(category = "drawing") 11804 public float getRotationY() { 11805 return mRenderNode.getRotationY(); 11806 } 11807 11808 /** 11809 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 11810 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 11811 * down the y axis. 11812 * 11813 * When rotating large views, it is recommended to adjust the camera distance 11814 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11815 * 11816 * @param rotationY The degrees of Y rotation. 11817 * 11818 * @see #getRotationY() 11819 * @see #getPivotX() 11820 * @see #getPivotY() 11821 * @see #setRotation(float) 11822 * @see #setRotationX(float) 11823 * @see #setCameraDistance(float) 11824 * 11825 * @attr ref android.R.styleable#View_rotationY 11826 */ 11827 public void setRotationY(float rotationY) { 11828 if (rotationY != getRotationY()) { 11829 invalidateViewProperty(true, false); 11830 mRenderNode.setRotationY(rotationY); 11831 invalidateViewProperty(false, true); 11832 11833 invalidateParentIfNeededAndWasQuickRejected(); 11834 notifySubtreeAccessibilityStateChangedIfNeeded(); 11835 } 11836 } 11837 11838 /** 11839 * The degrees that the view is rotated around the horizontal axis through the pivot point. 11840 * 11841 * @see #getPivotX() 11842 * @see #getPivotY() 11843 * @see #setRotationX(float) 11844 * 11845 * @return The degrees of X rotation. 11846 */ 11847 @ViewDebug.ExportedProperty(category = "drawing") 11848 public float getRotationX() { 11849 return mRenderNode.getRotationX(); 11850 } 11851 11852 /** 11853 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 11854 * Increasing values result in clockwise rotation from the viewpoint of looking down the 11855 * x axis. 11856 * 11857 * When rotating large views, it is recommended to adjust the camera distance 11858 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11859 * 11860 * @param rotationX The degrees of X rotation. 11861 * 11862 * @see #getRotationX() 11863 * @see #getPivotX() 11864 * @see #getPivotY() 11865 * @see #setRotation(float) 11866 * @see #setRotationY(float) 11867 * @see #setCameraDistance(float) 11868 * 11869 * @attr ref android.R.styleable#View_rotationX 11870 */ 11871 public void setRotationX(float rotationX) { 11872 if (rotationX != getRotationX()) { 11873 invalidateViewProperty(true, false); 11874 mRenderNode.setRotationX(rotationX); 11875 invalidateViewProperty(false, true); 11876 11877 invalidateParentIfNeededAndWasQuickRejected(); 11878 notifySubtreeAccessibilityStateChangedIfNeeded(); 11879 } 11880 } 11881 11882 /** 11883 * The amount that the view is scaled in x around the pivot point, as a proportion of 11884 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 11885 * 11886 * <p>By default, this is 1.0f. 11887 * 11888 * @see #getPivotX() 11889 * @see #getPivotY() 11890 * @return The scaling factor. 11891 */ 11892 @ViewDebug.ExportedProperty(category = "drawing") 11893 public float getScaleX() { 11894 return mRenderNode.getScaleX(); 11895 } 11896 11897 /** 11898 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 11899 * the view's unscaled width. A value of 1 means that no scaling is applied. 11900 * 11901 * @param scaleX The scaling factor. 11902 * @see #getPivotX() 11903 * @see #getPivotY() 11904 * 11905 * @attr ref android.R.styleable#View_scaleX 11906 */ 11907 public void setScaleX(float scaleX) { 11908 if (scaleX != getScaleX()) { 11909 invalidateViewProperty(true, false); 11910 mRenderNode.setScaleX(scaleX); 11911 invalidateViewProperty(false, true); 11912 11913 invalidateParentIfNeededAndWasQuickRejected(); 11914 notifySubtreeAccessibilityStateChangedIfNeeded(); 11915 } 11916 } 11917 11918 /** 11919 * The amount that the view is scaled in y around the pivot point, as a proportion of 11920 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 11921 * 11922 * <p>By default, this is 1.0f. 11923 * 11924 * @see #getPivotX() 11925 * @see #getPivotY() 11926 * @return The scaling factor. 11927 */ 11928 @ViewDebug.ExportedProperty(category = "drawing") 11929 public float getScaleY() { 11930 return mRenderNode.getScaleY(); 11931 } 11932 11933 /** 11934 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 11935 * the view's unscaled width. A value of 1 means that no scaling is applied. 11936 * 11937 * @param scaleY The scaling factor. 11938 * @see #getPivotX() 11939 * @see #getPivotY() 11940 * 11941 * @attr ref android.R.styleable#View_scaleY 11942 */ 11943 public void setScaleY(float scaleY) { 11944 if (scaleY != getScaleY()) { 11945 invalidateViewProperty(true, false); 11946 mRenderNode.setScaleY(scaleY); 11947 invalidateViewProperty(false, true); 11948 11949 invalidateParentIfNeededAndWasQuickRejected(); 11950 notifySubtreeAccessibilityStateChangedIfNeeded(); 11951 } 11952 } 11953 11954 /** 11955 * The x location of the point around which the view is {@link #setRotation(float) rotated} 11956 * and {@link #setScaleX(float) scaled}. 11957 * 11958 * @see #getRotation() 11959 * @see #getScaleX() 11960 * @see #getScaleY() 11961 * @see #getPivotY() 11962 * @return The x location of the pivot point. 11963 * 11964 * @attr ref android.R.styleable#View_transformPivotX 11965 */ 11966 @ViewDebug.ExportedProperty(category = "drawing") 11967 public float getPivotX() { 11968 return mRenderNode.getPivotX(); 11969 } 11970 11971 /** 11972 * Sets the x location of the point around which the view is 11973 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 11974 * By default, the pivot point is centered on the object. 11975 * Setting this property disables this behavior and causes the view to use only the 11976 * explicitly set pivotX and pivotY values. 11977 * 11978 * @param pivotX The x location of the pivot point. 11979 * @see #getRotation() 11980 * @see #getScaleX() 11981 * @see #getScaleY() 11982 * @see #getPivotY() 11983 * 11984 * @attr ref android.R.styleable#View_transformPivotX 11985 */ 11986 public void setPivotX(float pivotX) { 11987 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 11988 invalidateViewProperty(true, false); 11989 mRenderNode.setPivotX(pivotX); 11990 invalidateViewProperty(false, true); 11991 11992 invalidateParentIfNeededAndWasQuickRejected(); 11993 } 11994 } 11995 11996 /** 11997 * The y location of the point around which the view is {@link #setRotation(float) rotated} 11998 * and {@link #setScaleY(float) scaled}. 11999 * 12000 * @see #getRotation() 12001 * @see #getScaleX() 12002 * @see #getScaleY() 12003 * @see #getPivotY() 12004 * @return The y location of the pivot point. 12005 * 12006 * @attr ref android.R.styleable#View_transformPivotY 12007 */ 12008 @ViewDebug.ExportedProperty(category = "drawing") 12009 public float getPivotY() { 12010 return mRenderNode.getPivotY(); 12011 } 12012 12013 /** 12014 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12015 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12016 * Setting this property disables this behavior and causes the view to use only the 12017 * explicitly set pivotX and pivotY values. 12018 * 12019 * @param pivotY The y location of the pivot point. 12020 * @see #getRotation() 12021 * @see #getScaleX() 12022 * @see #getScaleY() 12023 * @see #getPivotY() 12024 * 12025 * @attr ref android.R.styleable#View_transformPivotY 12026 */ 12027 public void setPivotY(float pivotY) { 12028 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12029 invalidateViewProperty(true, false); 12030 mRenderNode.setPivotY(pivotY); 12031 invalidateViewProperty(false, true); 12032 12033 invalidateParentIfNeededAndWasQuickRejected(); 12034 } 12035 } 12036 12037 /** 12038 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12039 * completely transparent and 1 means the view is completely opaque. 12040 * 12041 * <p>By default this is 1.0f. 12042 * @return The opacity of the view. 12043 */ 12044 @ViewDebug.ExportedProperty(category = "drawing") 12045 public float getAlpha() { 12046 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12047 } 12048 12049 /** 12050 * Returns whether this View has content which overlaps. 12051 * 12052 * <p>This function, intended to be overridden by specific View types, is an optimization when 12053 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12054 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12055 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12056 * directly. An example of overlapping rendering is a TextView with a background image, such as 12057 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12058 * ImageView with only the foreground image. The default implementation returns true; subclasses 12059 * should override if they have cases which can be optimized.</p> 12060 * 12061 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12062 * necessitates that a View return true if it uses the methods internally without passing the 12063 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12064 * 12065 * @return true if the content in this view might overlap, false otherwise. 12066 */ 12067 @ViewDebug.ExportedProperty(category = "drawing") 12068 public boolean hasOverlappingRendering() { 12069 return true; 12070 } 12071 12072 /** 12073 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12074 * completely transparent and 1 means the view is completely opaque. 12075 * 12076 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12077 * can have significant performance implications, especially for large views. It is best to use 12078 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12079 * 12080 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12081 * strongly recommended for performance reasons to either override 12082 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12083 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12084 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12085 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12086 * of rendering cost, even for simple or small views. Starting with 12087 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12088 * applied to the view at the rendering level.</p> 12089 * 12090 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12091 * responsible for applying the opacity itself.</p> 12092 * 12093 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12094 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12095 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12096 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12097 * 12098 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12099 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12100 * {@link #hasOverlappingRendering}.</p> 12101 * 12102 * @param alpha The opacity of the view. 12103 * 12104 * @see #hasOverlappingRendering() 12105 * @see #setLayerType(int, android.graphics.Paint) 12106 * 12107 * @attr ref android.R.styleable#View_alpha 12108 */ 12109 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12110 ensureTransformationInfo(); 12111 if (mTransformationInfo.mAlpha != alpha) { 12112 mTransformationInfo.mAlpha = alpha; 12113 if (onSetAlpha((int) (alpha * 255))) { 12114 mPrivateFlags |= PFLAG_ALPHA_SET; 12115 // subclass is handling alpha - don't optimize rendering cache invalidation 12116 invalidateParentCaches(); 12117 invalidate(true); 12118 } else { 12119 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12120 invalidateViewProperty(true, false); 12121 mRenderNode.setAlpha(getFinalAlpha()); 12122 notifyViewAccessibilityStateChangedIfNeeded( 12123 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12124 } 12125 } 12126 } 12127 12128 /** 12129 * Faster version of setAlpha() which performs the same steps except there are 12130 * no calls to invalidate(). The caller of this function should perform proper invalidation 12131 * on the parent and this object. The return value indicates whether the subclass handles 12132 * alpha (the return value for onSetAlpha()). 12133 * 12134 * @param alpha The new value for the alpha property 12135 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12136 * the new value for the alpha property is different from the old value 12137 */ 12138 boolean setAlphaNoInvalidation(float alpha) { 12139 ensureTransformationInfo(); 12140 if (mTransformationInfo.mAlpha != alpha) { 12141 mTransformationInfo.mAlpha = alpha; 12142 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12143 if (subclassHandlesAlpha) { 12144 mPrivateFlags |= PFLAG_ALPHA_SET; 12145 return true; 12146 } else { 12147 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12148 mRenderNode.setAlpha(getFinalAlpha()); 12149 } 12150 } 12151 return false; 12152 } 12153 12154 /** 12155 * This property is hidden and intended only for use by the Fade transition, which 12156 * animates it to produce a visual translucency that does not side-effect (or get 12157 * affected by) the real alpha property. This value is composited with the other 12158 * alpha value (and the AlphaAnimation value, when that is present) to produce 12159 * a final visual translucency result, which is what is passed into the DisplayList. 12160 * 12161 * @hide 12162 */ 12163 public void setTransitionAlpha(float alpha) { 12164 ensureTransformationInfo(); 12165 if (mTransformationInfo.mTransitionAlpha != alpha) { 12166 mTransformationInfo.mTransitionAlpha = alpha; 12167 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12168 invalidateViewProperty(true, false); 12169 mRenderNode.setAlpha(getFinalAlpha()); 12170 } 12171 } 12172 12173 /** 12174 * Calculates the visual alpha of this view, which is a combination of the actual 12175 * alpha value and the transitionAlpha value (if set). 12176 */ 12177 private float getFinalAlpha() { 12178 if (mTransformationInfo != null) { 12179 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12180 } 12181 return 1; 12182 } 12183 12184 /** 12185 * This property is hidden and intended only for use by the Fade transition, which 12186 * animates it to produce a visual translucency that does not side-effect (or get 12187 * affected by) the real alpha property. This value is composited with the other 12188 * alpha value (and the AlphaAnimation value, when that is present) to produce 12189 * a final visual translucency result, which is what is passed into the DisplayList. 12190 * 12191 * @hide 12192 */ 12193 @ViewDebug.ExportedProperty(category = "drawing") 12194 public float getTransitionAlpha() { 12195 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12196 } 12197 12198 /** 12199 * Top position of this view relative to its parent. 12200 * 12201 * @return The top of this view, in pixels. 12202 */ 12203 @ViewDebug.CapturedViewProperty 12204 public final int getTop() { 12205 return mTop; 12206 } 12207 12208 /** 12209 * Sets the top position of this view relative to its parent. This method is meant to be called 12210 * by the layout system and should not generally be called otherwise, because the property 12211 * may be changed at any time by the layout. 12212 * 12213 * @param top The top of this view, in pixels. 12214 */ 12215 public final void setTop(int top) { 12216 if (top != mTop) { 12217 final boolean matrixIsIdentity = hasIdentityMatrix(); 12218 if (matrixIsIdentity) { 12219 if (mAttachInfo != null) { 12220 int minTop; 12221 int yLoc; 12222 if (top < mTop) { 12223 minTop = top; 12224 yLoc = top - mTop; 12225 } else { 12226 minTop = mTop; 12227 yLoc = 0; 12228 } 12229 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12230 } 12231 } else { 12232 // Double-invalidation is necessary to capture view's old and new areas 12233 invalidate(true); 12234 } 12235 12236 int width = mRight - mLeft; 12237 int oldHeight = mBottom - mTop; 12238 12239 mTop = top; 12240 mRenderNode.setTop(mTop); 12241 12242 sizeChange(width, mBottom - mTop, width, oldHeight); 12243 12244 if (!matrixIsIdentity) { 12245 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12246 invalidate(true); 12247 } 12248 mBackgroundSizeChanged = true; 12249 if (mForegroundInfo != null) { 12250 mForegroundInfo.mBoundsChanged = true; 12251 } 12252 invalidateParentIfNeeded(); 12253 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12254 // View was rejected last time it was drawn by its parent; this may have changed 12255 invalidateParentIfNeeded(); 12256 } 12257 } 12258 } 12259 12260 /** 12261 * Bottom position of this view relative to its parent. 12262 * 12263 * @return The bottom of this view, in pixels. 12264 */ 12265 @ViewDebug.CapturedViewProperty 12266 public final int getBottom() { 12267 return mBottom; 12268 } 12269 12270 /** 12271 * True if this view has changed since the last time being drawn. 12272 * 12273 * @return The dirty state of this view. 12274 */ 12275 public boolean isDirty() { 12276 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12277 } 12278 12279 /** 12280 * Sets the bottom position of this view relative to its parent. This method is meant to be 12281 * called by the layout system and should not generally be called otherwise, because the 12282 * property may be changed at any time by the layout. 12283 * 12284 * @param bottom The bottom of this view, in pixels. 12285 */ 12286 public final void setBottom(int bottom) { 12287 if (bottom != mBottom) { 12288 final boolean matrixIsIdentity = hasIdentityMatrix(); 12289 if (matrixIsIdentity) { 12290 if (mAttachInfo != null) { 12291 int maxBottom; 12292 if (bottom < mBottom) { 12293 maxBottom = mBottom; 12294 } else { 12295 maxBottom = bottom; 12296 } 12297 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12298 } 12299 } else { 12300 // Double-invalidation is necessary to capture view's old and new areas 12301 invalidate(true); 12302 } 12303 12304 int width = mRight - mLeft; 12305 int oldHeight = mBottom - mTop; 12306 12307 mBottom = bottom; 12308 mRenderNode.setBottom(mBottom); 12309 12310 sizeChange(width, mBottom - mTop, width, oldHeight); 12311 12312 if (!matrixIsIdentity) { 12313 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12314 invalidate(true); 12315 } 12316 mBackgroundSizeChanged = true; 12317 if (mForegroundInfo != null) { 12318 mForegroundInfo.mBoundsChanged = true; 12319 } 12320 invalidateParentIfNeeded(); 12321 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12322 // View was rejected last time it was drawn by its parent; this may have changed 12323 invalidateParentIfNeeded(); 12324 } 12325 } 12326 } 12327 12328 /** 12329 * Left position of this view relative to its parent. 12330 * 12331 * @return The left edge of this view, in pixels. 12332 */ 12333 @ViewDebug.CapturedViewProperty 12334 public final int getLeft() { 12335 return mLeft; 12336 } 12337 12338 /** 12339 * Sets the left position of this view relative to its parent. This method is meant to be called 12340 * by the layout system and should not generally be called otherwise, because the property 12341 * may be changed at any time by the layout. 12342 * 12343 * @param left The left of this view, in pixels. 12344 */ 12345 public final void setLeft(int left) { 12346 if (left != mLeft) { 12347 final boolean matrixIsIdentity = hasIdentityMatrix(); 12348 if (matrixIsIdentity) { 12349 if (mAttachInfo != null) { 12350 int minLeft; 12351 int xLoc; 12352 if (left < mLeft) { 12353 minLeft = left; 12354 xLoc = left - mLeft; 12355 } else { 12356 minLeft = mLeft; 12357 xLoc = 0; 12358 } 12359 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12360 } 12361 } else { 12362 // Double-invalidation is necessary to capture view's old and new areas 12363 invalidate(true); 12364 } 12365 12366 int oldWidth = mRight - mLeft; 12367 int height = mBottom - mTop; 12368 12369 mLeft = left; 12370 mRenderNode.setLeft(left); 12371 12372 sizeChange(mRight - mLeft, height, oldWidth, height); 12373 12374 if (!matrixIsIdentity) { 12375 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12376 invalidate(true); 12377 } 12378 mBackgroundSizeChanged = true; 12379 if (mForegroundInfo != null) { 12380 mForegroundInfo.mBoundsChanged = true; 12381 } 12382 invalidateParentIfNeeded(); 12383 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12384 // View was rejected last time it was drawn by its parent; this may have changed 12385 invalidateParentIfNeeded(); 12386 } 12387 } 12388 } 12389 12390 /** 12391 * Right position of this view relative to its parent. 12392 * 12393 * @return The right edge of this view, in pixels. 12394 */ 12395 @ViewDebug.CapturedViewProperty 12396 public final int getRight() { 12397 return mRight; 12398 } 12399 12400 /** 12401 * Sets the right position of this view relative to its parent. This method is meant to be called 12402 * by the layout system and should not generally be called otherwise, because the property 12403 * may be changed at any time by the layout. 12404 * 12405 * @param right The right of this view, in pixels. 12406 */ 12407 public final void setRight(int right) { 12408 if (right != mRight) { 12409 final boolean matrixIsIdentity = hasIdentityMatrix(); 12410 if (matrixIsIdentity) { 12411 if (mAttachInfo != null) { 12412 int maxRight; 12413 if (right < mRight) { 12414 maxRight = mRight; 12415 } else { 12416 maxRight = right; 12417 } 12418 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12419 } 12420 } else { 12421 // Double-invalidation is necessary to capture view's old and new areas 12422 invalidate(true); 12423 } 12424 12425 int oldWidth = mRight - mLeft; 12426 int height = mBottom - mTop; 12427 12428 mRight = right; 12429 mRenderNode.setRight(mRight); 12430 12431 sizeChange(mRight - mLeft, height, oldWidth, height); 12432 12433 if (!matrixIsIdentity) { 12434 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12435 invalidate(true); 12436 } 12437 mBackgroundSizeChanged = true; 12438 if (mForegroundInfo != null) { 12439 mForegroundInfo.mBoundsChanged = true; 12440 } 12441 invalidateParentIfNeeded(); 12442 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12443 // View was rejected last time it was drawn by its parent; this may have changed 12444 invalidateParentIfNeeded(); 12445 } 12446 } 12447 } 12448 12449 /** 12450 * The visual x position of this view, in pixels. This is equivalent to the 12451 * {@link #setTranslationX(float) translationX} property plus the current 12452 * {@link #getLeft() left} property. 12453 * 12454 * @return The visual x position of this view, in pixels. 12455 */ 12456 @ViewDebug.ExportedProperty(category = "drawing") 12457 public float getX() { 12458 return mLeft + getTranslationX(); 12459 } 12460 12461 /** 12462 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12463 * {@link #setTranslationX(float) translationX} property to be the difference between 12464 * the x value passed in and the current {@link #getLeft() left} property. 12465 * 12466 * @param x The visual x position of this view, in pixels. 12467 */ 12468 public void setX(float x) { 12469 setTranslationX(x - mLeft); 12470 } 12471 12472 /** 12473 * The visual y position of this view, in pixels. This is equivalent to the 12474 * {@link #setTranslationY(float) translationY} property plus the current 12475 * {@link #getTop() top} property. 12476 * 12477 * @return The visual y position of this view, in pixels. 12478 */ 12479 @ViewDebug.ExportedProperty(category = "drawing") 12480 public float getY() { 12481 return mTop + getTranslationY(); 12482 } 12483 12484 /** 12485 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12486 * {@link #setTranslationY(float) translationY} property to be the difference between 12487 * the y value passed in and the current {@link #getTop() top} property. 12488 * 12489 * @param y The visual y position of this view, in pixels. 12490 */ 12491 public void setY(float y) { 12492 setTranslationY(y - mTop); 12493 } 12494 12495 /** 12496 * The visual z position of this view, in pixels. This is equivalent to the 12497 * {@link #setTranslationZ(float) translationZ} property plus the current 12498 * {@link #getElevation() elevation} property. 12499 * 12500 * @return The visual z position of this view, in pixels. 12501 */ 12502 @ViewDebug.ExportedProperty(category = "drawing") 12503 public float getZ() { 12504 return getElevation() + getTranslationZ(); 12505 } 12506 12507 /** 12508 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12509 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12510 * the x value passed in and the current {@link #getElevation() elevation} property. 12511 * 12512 * @param z The visual z position of this view, in pixels. 12513 */ 12514 public void setZ(float z) { 12515 setTranslationZ(z - getElevation()); 12516 } 12517 12518 /** 12519 * The base elevation of this view relative to its parent, in pixels. 12520 * 12521 * @return The base depth position of the view, in pixels. 12522 */ 12523 @ViewDebug.ExportedProperty(category = "drawing") 12524 public float getElevation() { 12525 return mRenderNode.getElevation(); 12526 } 12527 12528 /** 12529 * Sets the base elevation of this view, in pixels. 12530 * 12531 * @attr ref android.R.styleable#View_elevation 12532 */ 12533 public void setElevation(float elevation) { 12534 if (elevation != getElevation()) { 12535 invalidateViewProperty(true, false); 12536 mRenderNode.setElevation(elevation); 12537 invalidateViewProperty(false, true); 12538 12539 invalidateParentIfNeededAndWasQuickRejected(); 12540 } 12541 } 12542 12543 /** 12544 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12545 * This position is post-layout, in addition to wherever the object's 12546 * layout placed it. 12547 * 12548 * @return The horizontal position of this view relative to its left position, in pixels. 12549 */ 12550 @ViewDebug.ExportedProperty(category = "drawing") 12551 public float getTranslationX() { 12552 return mRenderNode.getTranslationX(); 12553 } 12554 12555 /** 12556 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12557 * This effectively positions the object post-layout, in addition to wherever the object's 12558 * layout placed it. 12559 * 12560 * @param translationX The horizontal position of this view relative to its left position, 12561 * in pixels. 12562 * 12563 * @attr ref android.R.styleable#View_translationX 12564 */ 12565 public void setTranslationX(float translationX) { 12566 if (translationX != getTranslationX()) { 12567 invalidateViewProperty(true, false); 12568 mRenderNode.setTranslationX(translationX); 12569 invalidateViewProperty(false, true); 12570 12571 invalidateParentIfNeededAndWasQuickRejected(); 12572 notifySubtreeAccessibilityStateChangedIfNeeded(); 12573 } 12574 } 12575 12576 /** 12577 * The vertical location of this view relative to its {@link #getTop() top} position. 12578 * This position is post-layout, in addition to wherever the object's 12579 * layout placed it. 12580 * 12581 * @return The vertical position of this view relative to its top position, 12582 * in pixels. 12583 */ 12584 @ViewDebug.ExportedProperty(category = "drawing") 12585 public float getTranslationY() { 12586 return mRenderNode.getTranslationY(); 12587 } 12588 12589 /** 12590 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12591 * This effectively positions the object post-layout, in addition to wherever the object's 12592 * layout placed it. 12593 * 12594 * @param translationY The vertical position of this view relative to its top position, 12595 * in pixels. 12596 * 12597 * @attr ref android.R.styleable#View_translationY 12598 */ 12599 public void setTranslationY(float translationY) { 12600 if (translationY != getTranslationY()) { 12601 invalidateViewProperty(true, false); 12602 mRenderNode.setTranslationY(translationY); 12603 invalidateViewProperty(false, true); 12604 12605 invalidateParentIfNeededAndWasQuickRejected(); 12606 notifySubtreeAccessibilityStateChangedIfNeeded(); 12607 } 12608 } 12609 12610 /** 12611 * The depth location of this view relative to its {@link #getElevation() elevation}. 12612 * 12613 * @return The depth of this view relative to its elevation. 12614 */ 12615 @ViewDebug.ExportedProperty(category = "drawing") 12616 public float getTranslationZ() { 12617 return mRenderNode.getTranslationZ(); 12618 } 12619 12620 /** 12621 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12622 * 12623 * @attr ref android.R.styleable#View_translationZ 12624 */ 12625 public void setTranslationZ(float translationZ) { 12626 if (translationZ != getTranslationZ()) { 12627 invalidateViewProperty(true, false); 12628 mRenderNode.setTranslationZ(translationZ); 12629 invalidateViewProperty(false, true); 12630 12631 invalidateParentIfNeededAndWasQuickRejected(); 12632 } 12633 } 12634 12635 /** @hide */ 12636 public void setAnimationMatrix(Matrix matrix) { 12637 invalidateViewProperty(true, false); 12638 mRenderNode.setAnimationMatrix(matrix); 12639 invalidateViewProperty(false, true); 12640 12641 invalidateParentIfNeededAndWasQuickRejected(); 12642 } 12643 12644 /** 12645 * Returns the current StateListAnimator if exists. 12646 * 12647 * @return StateListAnimator or null if it does not exists 12648 * @see #setStateListAnimator(android.animation.StateListAnimator) 12649 */ 12650 public StateListAnimator getStateListAnimator() { 12651 return mStateListAnimator; 12652 } 12653 12654 /** 12655 * Attaches the provided StateListAnimator to this View. 12656 * <p> 12657 * Any previously attached StateListAnimator will be detached. 12658 * 12659 * @param stateListAnimator The StateListAnimator to update the view 12660 * @see {@link android.animation.StateListAnimator} 12661 */ 12662 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12663 if (mStateListAnimator == stateListAnimator) { 12664 return; 12665 } 12666 if (mStateListAnimator != null) { 12667 mStateListAnimator.setTarget(null); 12668 } 12669 mStateListAnimator = stateListAnimator; 12670 if (stateListAnimator != null) { 12671 stateListAnimator.setTarget(this); 12672 if (isAttachedToWindow()) { 12673 stateListAnimator.setState(getDrawableState()); 12674 } 12675 } 12676 } 12677 12678 /** 12679 * Returns whether the Outline should be used to clip the contents of the View. 12680 * <p> 12681 * Note that this flag will only be respected if the View's Outline returns true from 12682 * {@link Outline#canClip()}. 12683 * 12684 * @see #setOutlineProvider(ViewOutlineProvider) 12685 * @see #setClipToOutline(boolean) 12686 */ 12687 public final boolean getClipToOutline() { 12688 return mRenderNode.getClipToOutline(); 12689 } 12690 12691 /** 12692 * Sets whether the View's Outline should be used to clip the contents of the View. 12693 * <p> 12694 * Only a single non-rectangular clip can be applied on a View at any time. 12695 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12696 * circular reveal} animation take priority over Outline clipping, and 12697 * child Outline clipping takes priority over Outline clipping done by a 12698 * parent. 12699 * <p> 12700 * Note that this flag will only be respected if the View's Outline returns true from 12701 * {@link Outline#canClip()}. 12702 * 12703 * @see #setOutlineProvider(ViewOutlineProvider) 12704 * @see #getClipToOutline() 12705 */ 12706 public void setClipToOutline(boolean clipToOutline) { 12707 damageInParent(); 12708 if (getClipToOutline() != clipToOutline) { 12709 mRenderNode.setClipToOutline(clipToOutline); 12710 } 12711 } 12712 12713 // correspond to the enum values of View_outlineProvider 12714 private static final int PROVIDER_BACKGROUND = 0; 12715 private static final int PROVIDER_NONE = 1; 12716 private static final int PROVIDER_BOUNDS = 2; 12717 private static final int PROVIDER_PADDED_BOUNDS = 3; 12718 private void setOutlineProviderFromAttribute(int providerInt) { 12719 switch (providerInt) { 12720 case PROVIDER_BACKGROUND: 12721 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12722 break; 12723 case PROVIDER_NONE: 12724 setOutlineProvider(null); 12725 break; 12726 case PROVIDER_BOUNDS: 12727 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12728 break; 12729 case PROVIDER_PADDED_BOUNDS: 12730 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12731 break; 12732 } 12733 } 12734 12735 /** 12736 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12737 * the shape of the shadow it casts, and enables outline clipping. 12738 * <p> 12739 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12740 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12741 * outline provider with this method allows this behavior to be overridden. 12742 * <p> 12743 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12744 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12745 * <p> 12746 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 12747 * 12748 * @see #setClipToOutline(boolean) 12749 * @see #getClipToOutline() 12750 * @see #getOutlineProvider() 12751 */ 12752 public void setOutlineProvider(ViewOutlineProvider provider) { 12753 mOutlineProvider = provider; 12754 invalidateOutline(); 12755 } 12756 12757 /** 12758 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 12759 * that defines the shape of the shadow it casts, and enables outline clipping. 12760 * 12761 * @see #setOutlineProvider(ViewOutlineProvider) 12762 */ 12763 public ViewOutlineProvider getOutlineProvider() { 12764 return mOutlineProvider; 12765 } 12766 12767 /** 12768 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 12769 * 12770 * @see #setOutlineProvider(ViewOutlineProvider) 12771 */ 12772 public void invalidateOutline() { 12773 rebuildOutline(); 12774 12775 notifySubtreeAccessibilityStateChangedIfNeeded(); 12776 invalidateViewProperty(false, false); 12777 } 12778 12779 /** 12780 * Internal version of {@link #invalidateOutline()} which invalidates the 12781 * outline without invalidating the view itself. This is intended to be called from 12782 * within methods in the View class itself which are the result of the view being 12783 * invalidated already. For example, when we are drawing the background of a View, 12784 * we invalidate the outline in case it changed in the meantime, but we do not 12785 * need to invalidate the view because we're already drawing the background as part 12786 * of drawing the view in response to an earlier invalidation of the view. 12787 */ 12788 private void rebuildOutline() { 12789 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 12790 if (mAttachInfo == null) return; 12791 12792 if (mOutlineProvider == null) { 12793 // no provider, remove outline 12794 mRenderNode.setOutline(null); 12795 } else { 12796 final Outline outline = mAttachInfo.mTmpOutline; 12797 outline.setEmpty(); 12798 outline.setAlpha(1.0f); 12799 12800 mOutlineProvider.getOutline(this, outline); 12801 mRenderNode.setOutline(outline); 12802 } 12803 } 12804 12805 /** 12806 * HierarchyViewer only 12807 * 12808 * @hide 12809 */ 12810 @ViewDebug.ExportedProperty(category = "drawing") 12811 public boolean hasShadow() { 12812 return mRenderNode.hasShadow(); 12813 } 12814 12815 12816 /** @hide */ 12817 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 12818 mRenderNode.setRevealClip(shouldClip, x, y, radius); 12819 invalidateViewProperty(false, false); 12820 } 12821 12822 /** 12823 * Hit rectangle in parent's coordinates 12824 * 12825 * @param outRect The hit rectangle of the view. 12826 */ 12827 public void getHitRect(Rect outRect) { 12828 if (hasIdentityMatrix() || mAttachInfo == null) { 12829 outRect.set(mLeft, mTop, mRight, mBottom); 12830 } else { 12831 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 12832 tmpRect.set(0, 0, getWidth(), getHeight()); 12833 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 12834 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 12835 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 12836 } 12837 } 12838 12839 /** 12840 * Determines whether the given point, in local coordinates is inside the view. 12841 */ 12842 /*package*/ final boolean pointInView(float localX, float localY) { 12843 return pointInView(localX, localY, 0); 12844 } 12845 12846 /** 12847 * Utility method to determine whether the given point, in local coordinates, 12848 * is inside the view, where the area of the view is expanded by the slop factor. 12849 * This method is called while processing touch-move events to determine if the event 12850 * is still within the view. 12851 * 12852 * @hide 12853 */ 12854 public boolean pointInView(float localX, float localY, float slop) { 12855 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 12856 localY < ((mBottom - mTop) + slop); 12857 } 12858 12859 /** 12860 * When a view has focus and the user navigates away from it, the next view is searched for 12861 * starting from the rectangle filled in by this method. 12862 * 12863 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 12864 * of the view. However, if your view maintains some idea of internal selection, 12865 * such as a cursor, or a selected row or column, you should override this method and 12866 * fill in a more specific rectangle. 12867 * 12868 * @param r The rectangle to fill in, in this view's coordinates. 12869 */ 12870 public void getFocusedRect(Rect r) { 12871 getDrawingRect(r); 12872 } 12873 12874 /** 12875 * If some part of this view is not clipped by any of its parents, then 12876 * return that area in r in global (root) coordinates. To convert r to local 12877 * coordinates (without taking possible View rotations into account), offset 12878 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 12879 * If the view is completely clipped or translated out, return false. 12880 * 12881 * @param r If true is returned, r holds the global coordinates of the 12882 * visible portion of this view. 12883 * @param globalOffset If true is returned, globalOffset holds the dx,dy 12884 * between this view and its root. globalOffet may be null. 12885 * @return true if r is non-empty (i.e. part of the view is visible at the 12886 * root level. 12887 */ 12888 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 12889 int width = mRight - mLeft; 12890 int height = mBottom - mTop; 12891 if (width > 0 && height > 0) { 12892 r.set(0, 0, width, height); 12893 if (globalOffset != null) { 12894 globalOffset.set(-mScrollX, -mScrollY); 12895 } 12896 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 12897 } 12898 return false; 12899 } 12900 12901 public final boolean getGlobalVisibleRect(Rect r) { 12902 return getGlobalVisibleRect(r, null); 12903 } 12904 12905 public final boolean getLocalVisibleRect(Rect r) { 12906 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 12907 if (getGlobalVisibleRect(r, offset)) { 12908 r.offset(-offset.x, -offset.y); // make r local 12909 return true; 12910 } 12911 return false; 12912 } 12913 12914 /** 12915 * Offset this view's vertical location by the specified number of pixels. 12916 * 12917 * @param offset the number of pixels to offset the view by 12918 */ 12919 public void offsetTopAndBottom(int offset) { 12920 if (offset != 0) { 12921 final boolean matrixIsIdentity = hasIdentityMatrix(); 12922 if (matrixIsIdentity) { 12923 if (isHardwareAccelerated()) { 12924 invalidateViewProperty(false, false); 12925 } else { 12926 final ViewParent p = mParent; 12927 if (p != null && mAttachInfo != null) { 12928 final Rect r = mAttachInfo.mTmpInvalRect; 12929 int minTop; 12930 int maxBottom; 12931 int yLoc; 12932 if (offset < 0) { 12933 minTop = mTop + offset; 12934 maxBottom = mBottom; 12935 yLoc = offset; 12936 } else { 12937 minTop = mTop; 12938 maxBottom = mBottom + offset; 12939 yLoc = 0; 12940 } 12941 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 12942 p.invalidateChild(this, r); 12943 } 12944 } 12945 } else { 12946 invalidateViewProperty(false, false); 12947 } 12948 12949 mTop += offset; 12950 mBottom += offset; 12951 mRenderNode.offsetTopAndBottom(offset); 12952 if (isHardwareAccelerated()) { 12953 invalidateViewProperty(false, false); 12954 invalidateParentIfNeededAndWasQuickRejected(); 12955 } else { 12956 if (!matrixIsIdentity) { 12957 invalidateViewProperty(false, true); 12958 } 12959 invalidateParentIfNeeded(); 12960 } 12961 notifySubtreeAccessibilityStateChangedIfNeeded(); 12962 } 12963 } 12964 12965 /** 12966 * Offset this view's horizontal location by the specified amount of pixels. 12967 * 12968 * @param offset the number of pixels to offset the view by 12969 */ 12970 public void offsetLeftAndRight(int offset) { 12971 if (offset != 0) { 12972 final boolean matrixIsIdentity = hasIdentityMatrix(); 12973 if (matrixIsIdentity) { 12974 if (isHardwareAccelerated()) { 12975 invalidateViewProperty(false, false); 12976 } else { 12977 final ViewParent p = mParent; 12978 if (p != null && mAttachInfo != null) { 12979 final Rect r = mAttachInfo.mTmpInvalRect; 12980 int minLeft; 12981 int maxRight; 12982 if (offset < 0) { 12983 minLeft = mLeft + offset; 12984 maxRight = mRight; 12985 } else { 12986 minLeft = mLeft; 12987 maxRight = mRight + offset; 12988 } 12989 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 12990 p.invalidateChild(this, r); 12991 } 12992 } 12993 } else { 12994 invalidateViewProperty(false, false); 12995 } 12996 12997 mLeft += offset; 12998 mRight += offset; 12999 mRenderNode.offsetLeftAndRight(offset); 13000 if (isHardwareAccelerated()) { 13001 invalidateViewProperty(false, false); 13002 invalidateParentIfNeededAndWasQuickRejected(); 13003 } else { 13004 if (!matrixIsIdentity) { 13005 invalidateViewProperty(false, true); 13006 } 13007 invalidateParentIfNeeded(); 13008 } 13009 notifySubtreeAccessibilityStateChangedIfNeeded(); 13010 } 13011 } 13012 13013 /** 13014 * Get the LayoutParams associated with this view. All views should have 13015 * layout parameters. These supply parameters to the <i>parent</i> of this 13016 * view specifying how it should be arranged. There are many subclasses of 13017 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13018 * of ViewGroup that are responsible for arranging their children. 13019 * 13020 * This method may return null if this View is not attached to a parent 13021 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13022 * was not invoked successfully. When a View is attached to a parent 13023 * ViewGroup, this method must not return null. 13024 * 13025 * @return The LayoutParams associated with this view, or null if no 13026 * parameters have been set yet 13027 */ 13028 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13029 public ViewGroup.LayoutParams getLayoutParams() { 13030 return mLayoutParams; 13031 } 13032 13033 /** 13034 * Set the layout parameters associated with this view. These supply 13035 * parameters to the <i>parent</i> of this view specifying how it should be 13036 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13037 * correspond to the different subclasses of ViewGroup that are responsible 13038 * for arranging their children. 13039 * 13040 * @param params The layout parameters for this view, cannot be null 13041 */ 13042 public void setLayoutParams(ViewGroup.LayoutParams params) { 13043 if (params == null) { 13044 throw new NullPointerException("Layout parameters cannot be null"); 13045 } 13046 mLayoutParams = params; 13047 resolveLayoutParams(); 13048 if (mParent instanceof ViewGroup) { 13049 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13050 } 13051 requestLayout(); 13052 } 13053 13054 /** 13055 * Resolve the layout parameters depending on the resolved layout direction 13056 * 13057 * @hide 13058 */ 13059 public void resolveLayoutParams() { 13060 if (mLayoutParams != null) { 13061 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13062 } 13063 } 13064 13065 /** 13066 * Set the scrolled position of your view. This will cause a call to 13067 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13068 * invalidated. 13069 * @param x the x position to scroll to 13070 * @param y the y position to scroll to 13071 */ 13072 public void scrollTo(int x, int y) { 13073 if (mScrollX != x || mScrollY != y) { 13074 int oldX = mScrollX; 13075 int oldY = mScrollY; 13076 mScrollX = x; 13077 mScrollY = y; 13078 invalidateParentCaches(); 13079 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13080 if (!awakenScrollBars()) { 13081 postInvalidateOnAnimation(); 13082 } 13083 } 13084 } 13085 13086 /** 13087 * Move the scrolled position of your view. This will cause a call to 13088 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13089 * invalidated. 13090 * @param x the amount of pixels to scroll by horizontally 13091 * @param y the amount of pixels to scroll by vertically 13092 */ 13093 public void scrollBy(int x, int y) { 13094 scrollTo(mScrollX + x, mScrollY + y); 13095 } 13096 13097 /** 13098 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13099 * animation to fade the scrollbars out after a default delay. If a subclass 13100 * provides animated scrolling, the start delay should equal the duration 13101 * of the scrolling animation.</p> 13102 * 13103 * <p>The animation starts only if at least one of the scrollbars is 13104 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13105 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13106 * this method returns true, and false otherwise. If the animation is 13107 * started, this method calls {@link #invalidate()}; in that case the 13108 * caller should not call {@link #invalidate()}.</p> 13109 * 13110 * <p>This method should be invoked every time a subclass directly updates 13111 * the scroll parameters.</p> 13112 * 13113 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13114 * and {@link #scrollTo(int, int)}.</p> 13115 * 13116 * @return true if the animation is played, false otherwise 13117 * 13118 * @see #awakenScrollBars(int) 13119 * @see #scrollBy(int, int) 13120 * @see #scrollTo(int, int) 13121 * @see #isHorizontalScrollBarEnabled() 13122 * @see #isVerticalScrollBarEnabled() 13123 * @see #setHorizontalScrollBarEnabled(boolean) 13124 * @see #setVerticalScrollBarEnabled(boolean) 13125 */ 13126 protected boolean awakenScrollBars() { 13127 return mScrollCache != null && 13128 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13129 } 13130 13131 /** 13132 * Trigger the scrollbars to draw. 13133 * This method differs from awakenScrollBars() only in its default duration. 13134 * initialAwakenScrollBars() will show the scroll bars for longer than 13135 * usual to give the user more of a chance to notice them. 13136 * 13137 * @return true if the animation is played, false otherwise. 13138 */ 13139 private boolean initialAwakenScrollBars() { 13140 return mScrollCache != null && 13141 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13142 } 13143 13144 /** 13145 * <p> 13146 * Trigger the scrollbars to draw. When invoked this method starts an 13147 * animation to fade the scrollbars out after a fixed delay. If a subclass 13148 * provides animated scrolling, the start delay should equal the duration of 13149 * the scrolling animation. 13150 * </p> 13151 * 13152 * <p> 13153 * The animation starts only if at least one of the scrollbars is enabled, 13154 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13155 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13156 * this method returns true, and false otherwise. If the animation is 13157 * started, this method calls {@link #invalidate()}; in that case the caller 13158 * should not call {@link #invalidate()}. 13159 * </p> 13160 * 13161 * <p> 13162 * This method should be invoked every time a subclass directly updates the 13163 * scroll parameters. 13164 * </p> 13165 * 13166 * @param startDelay the delay, in milliseconds, after which the animation 13167 * should start; when the delay is 0, the animation starts 13168 * immediately 13169 * @return true if the animation is played, false otherwise 13170 * 13171 * @see #scrollBy(int, int) 13172 * @see #scrollTo(int, int) 13173 * @see #isHorizontalScrollBarEnabled() 13174 * @see #isVerticalScrollBarEnabled() 13175 * @see #setHorizontalScrollBarEnabled(boolean) 13176 * @see #setVerticalScrollBarEnabled(boolean) 13177 */ 13178 protected boolean awakenScrollBars(int startDelay) { 13179 return awakenScrollBars(startDelay, true); 13180 } 13181 13182 /** 13183 * <p> 13184 * Trigger the scrollbars to draw. When invoked this method starts an 13185 * animation to fade the scrollbars out after a fixed delay. If a subclass 13186 * provides animated scrolling, the start delay should equal the duration of 13187 * the scrolling animation. 13188 * </p> 13189 * 13190 * <p> 13191 * The animation starts only if at least one of the scrollbars is enabled, 13192 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13193 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13194 * this method returns true, and false otherwise. If the animation is 13195 * started, this method calls {@link #invalidate()} if the invalidate parameter 13196 * is set to true; in that case the caller 13197 * should not call {@link #invalidate()}. 13198 * </p> 13199 * 13200 * <p> 13201 * This method should be invoked every time a subclass directly updates the 13202 * scroll parameters. 13203 * </p> 13204 * 13205 * @param startDelay the delay, in milliseconds, after which the animation 13206 * should start; when the delay is 0, the animation starts 13207 * immediately 13208 * 13209 * @param invalidate Whether this method should call invalidate 13210 * 13211 * @return true if the animation is played, false otherwise 13212 * 13213 * @see #scrollBy(int, int) 13214 * @see #scrollTo(int, int) 13215 * @see #isHorizontalScrollBarEnabled() 13216 * @see #isVerticalScrollBarEnabled() 13217 * @see #setHorizontalScrollBarEnabled(boolean) 13218 * @see #setVerticalScrollBarEnabled(boolean) 13219 */ 13220 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13221 final ScrollabilityCache scrollCache = mScrollCache; 13222 13223 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13224 return false; 13225 } 13226 13227 if (scrollCache.scrollBar == null) { 13228 scrollCache.scrollBar = new ScrollBarDrawable(); 13229 scrollCache.scrollBar.setCallback(this); 13230 scrollCache.scrollBar.setState(getDrawableState()); 13231 } 13232 13233 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13234 13235 if (invalidate) { 13236 // Invalidate to show the scrollbars 13237 postInvalidateOnAnimation(); 13238 } 13239 13240 if (scrollCache.state == ScrollabilityCache.OFF) { 13241 // FIXME: this is copied from WindowManagerService. 13242 // We should get this value from the system when it 13243 // is possible to do so. 13244 final int KEY_REPEAT_FIRST_DELAY = 750; 13245 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13246 } 13247 13248 // Tell mScrollCache when we should start fading. This may 13249 // extend the fade start time if one was already scheduled 13250 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13251 scrollCache.fadeStartTime = fadeStartTime; 13252 scrollCache.state = ScrollabilityCache.ON; 13253 13254 // Schedule our fader to run, unscheduling any old ones first 13255 if (mAttachInfo != null) { 13256 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13257 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13258 } 13259 13260 return true; 13261 } 13262 13263 return false; 13264 } 13265 13266 /** 13267 * Do not invalidate views which are not visible and which are not running an animation. They 13268 * will not get drawn and they should not set dirty flags as if they will be drawn 13269 */ 13270 private boolean skipInvalidate() { 13271 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13272 (!(mParent instanceof ViewGroup) || 13273 !((ViewGroup) mParent).isViewTransitioning(this)); 13274 } 13275 13276 /** 13277 * Mark the area defined by dirty as needing to be drawn. If the view is 13278 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13279 * point in the future. 13280 * <p> 13281 * This must be called from a UI thread. To call from a non-UI thread, call 13282 * {@link #postInvalidate()}. 13283 * <p> 13284 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13285 * {@code dirty}. 13286 * 13287 * @param dirty the rectangle representing the bounds of the dirty region 13288 */ 13289 public void invalidate(Rect dirty) { 13290 final int scrollX = mScrollX; 13291 final int scrollY = mScrollY; 13292 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13293 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13294 } 13295 13296 /** 13297 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13298 * coordinates of the dirty rect are relative to the view. If the view is 13299 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13300 * point in the future. 13301 * <p> 13302 * This must be called from a UI thread. To call from a non-UI thread, call 13303 * {@link #postInvalidate()}. 13304 * 13305 * @param l the left position of the dirty region 13306 * @param t the top position of the dirty region 13307 * @param r the right position of the dirty region 13308 * @param b the bottom position of the dirty region 13309 */ 13310 public void invalidate(int l, int t, int r, int b) { 13311 final int scrollX = mScrollX; 13312 final int scrollY = mScrollY; 13313 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13314 } 13315 13316 /** 13317 * Invalidate the whole view. If the view is visible, 13318 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13319 * the future. 13320 * <p> 13321 * This must be called from a UI thread. To call from a non-UI thread, call 13322 * {@link #postInvalidate()}. 13323 */ 13324 public void invalidate() { 13325 invalidate(true); 13326 } 13327 13328 /** 13329 * This is where the invalidate() work actually happens. A full invalidate() 13330 * causes the drawing cache to be invalidated, but this function can be 13331 * called with invalidateCache set to false to skip that invalidation step 13332 * for cases that do not need it (for example, a component that remains at 13333 * the same dimensions with the same content). 13334 * 13335 * @param invalidateCache Whether the drawing cache for this view should be 13336 * invalidated as well. This is usually true for a full 13337 * invalidate, but may be set to false if the View's contents or 13338 * dimensions have not changed. 13339 */ 13340 void invalidate(boolean invalidateCache) { 13341 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13342 } 13343 13344 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13345 boolean fullInvalidate) { 13346 if (mGhostView != null) { 13347 mGhostView.invalidate(true); 13348 return; 13349 } 13350 13351 if (skipInvalidate()) { 13352 return; 13353 } 13354 13355 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13356 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13357 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13358 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13359 if (fullInvalidate) { 13360 mLastIsOpaque = isOpaque(); 13361 mPrivateFlags &= ~PFLAG_DRAWN; 13362 } 13363 13364 mPrivateFlags |= PFLAG_DIRTY; 13365 13366 if (invalidateCache) { 13367 mPrivateFlags |= PFLAG_INVALIDATED; 13368 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13369 } 13370 13371 // Propagate the damage rectangle to the parent view. 13372 final AttachInfo ai = mAttachInfo; 13373 final ViewParent p = mParent; 13374 if (p != null && ai != null && l < r && t < b) { 13375 final Rect damage = ai.mTmpInvalRect; 13376 damage.set(l, t, r, b); 13377 p.invalidateChild(this, damage); 13378 } 13379 13380 // Damage the entire projection receiver, if necessary. 13381 if (mBackground != null && mBackground.isProjected()) { 13382 final View receiver = getProjectionReceiver(); 13383 if (receiver != null) { 13384 receiver.damageInParent(); 13385 } 13386 } 13387 13388 // Damage the entire IsolatedZVolume receiving this view's shadow. 13389 if (isHardwareAccelerated() && getZ() != 0) { 13390 damageShadowReceiver(); 13391 } 13392 } 13393 } 13394 13395 /** 13396 * @return this view's projection receiver, or {@code null} if none exists 13397 */ 13398 private View getProjectionReceiver() { 13399 ViewParent p = getParent(); 13400 while (p != null && p instanceof View) { 13401 final View v = (View) p; 13402 if (v.isProjectionReceiver()) { 13403 return v; 13404 } 13405 p = p.getParent(); 13406 } 13407 13408 return null; 13409 } 13410 13411 /** 13412 * @return whether the view is a projection receiver 13413 */ 13414 private boolean isProjectionReceiver() { 13415 return mBackground != null; 13416 } 13417 13418 /** 13419 * Damage area of the screen that can be covered by this View's shadow. 13420 * 13421 * This method will guarantee that any changes to shadows cast by a View 13422 * are damaged on the screen for future redraw. 13423 */ 13424 private void damageShadowReceiver() { 13425 final AttachInfo ai = mAttachInfo; 13426 if (ai != null) { 13427 ViewParent p = getParent(); 13428 if (p != null && p instanceof ViewGroup) { 13429 final ViewGroup vg = (ViewGroup) p; 13430 vg.damageInParent(); 13431 } 13432 } 13433 } 13434 13435 /** 13436 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13437 * set any flags or handle all of the cases handled by the default invalidation methods. 13438 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13439 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13440 * walk up the hierarchy, transforming the dirty rect as necessary. 13441 * 13442 * The method also handles normal invalidation logic if display list properties are not 13443 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13444 * backup approach, to handle these cases used in the various property-setting methods. 13445 * 13446 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13447 * are not being used in this view 13448 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13449 * list properties are not being used in this view 13450 */ 13451 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13452 if (!isHardwareAccelerated() 13453 || !mRenderNode.isValid() 13454 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13455 if (invalidateParent) { 13456 invalidateParentCaches(); 13457 } 13458 if (forceRedraw) { 13459 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13460 } 13461 invalidate(false); 13462 } else { 13463 damageInParent(); 13464 } 13465 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13466 damageShadowReceiver(); 13467 } 13468 } 13469 13470 /** 13471 * Tells the parent view to damage this view's bounds. 13472 * 13473 * @hide 13474 */ 13475 protected void damageInParent() { 13476 final AttachInfo ai = mAttachInfo; 13477 final ViewParent p = mParent; 13478 if (p != null && ai != null) { 13479 final Rect r = ai.mTmpInvalRect; 13480 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13481 if (mParent instanceof ViewGroup) { 13482 ((ViewGroup) mParent).damageChild(this, r); 13483 } else { 13484 mParent.invalidateChild(this, r); 13485 } 13486 } 13487 } 13488 13489 /** 13490 * Utility method to transform a given Rect by the current matrix of this view. 13491 */ 13492 void transformRect(final Rect rect) { 13493 if (!getMatrix().isIdentity()) { 13494 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13495 boundingRect.set(rect); 13496 getMatrix().mapRect(boundingRect); 13497 rect.set((int) Math.floor(boundingRect.left), 13498 (int) Math.floor(boundingRect.top), 13499 (int) Math.ceil(boundingRect.right), 13500 (int) Math.ceil(boundingRect.bottom)); 13501 } 13502 } 13503 13504 /** 13505 * Used to indicate that the parent of this view should clear its caches. This functionality 13506 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13507 * which is necessary when various parent-managed properties of the view change, such as 13508 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13509 * clears the parent caches and does not causes an invalidate event. 13510 * 13511 * @hide 13512 */ 13513 protected void invalidateParentCaches() { 13514 if (mParent instanceof View) { 13515 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13516 } 13517 } 13518 13519 /** 13520 * Used to indicate that the parent of this view should be invalidated. This functionality 13521 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13522 * which is necessary when various parent-managed properties of the view change, such as 13523 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13524 * an invalidation event to the parent. 13525 * 13526 * @hide 13527 */ 13528 protected void invalidateParentIfNeeded() { 13529 if (isHardwareAccelerated() && mParent instanceof View) { 13530 ((View) mParent).invalidate(true); 13531 } 13532 } 13533 13534 /** 13535 * @hide 13536 */ 13537 protected void invalidateParentIfNeededAndWasQuickRejected() { 13538 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13539 // View was rejected last time it was drawn by its parent; this may have changed 13540 invalidateParentIfNeeded(); 13541 } 13542 } 13543 13544 /** 13545 * Indicates whether this View is opaque. An opaque View guarantees that it will 13546 * draw all the pixels overlapping its bounds using a fully opaque color. 13547 * 13548 * Subclasses of View should override this method whenever possible to indicate 13549 * whether an instance is opaque. Opaque Views are treated in a special way by 13550 * the View hierarchy, possibly allowing it to perform optimizations during 13551 * invalidate/draw passes. 13552 * 13553 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13554 */ 13555 @ViewDebug.ExportedProperty(category = "drawing") 13556 public boolean isOpaque() { 13557 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13558 getFinalAlpha() >= 1.0f; 13559 } 13560 13561 /** 13562 * @hide 13563 */ 13564 protected void computeOpaqueFlags() { 13565 // Opaque if: 13566 // - Has a background 13567 // - Background is opaque 13568 // - Doesn't have scrollbars or scrollbars overlay 13569 13570 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13571 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13572 } else { 13573 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13574 } 13575 13576 final int flags = mViewFlags; 13577 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13578 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13579 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13580 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13581 } else { 13582 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13583 } 13584 } 13585 13586 /** 13587 * @hide 13588 */ 13589 protected boolean hasOpaqueScrollbars() { 13590 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13591 } 13592 13593 /** 13594 * @return A handler associated with the thread running the View. This 13595 * handler can be used to pump events in the UI events queue. 13596 */ 13597 public Handler getHandler() { 13598 final AttachInfo attachInfo = mAttachInfo; 13599 if (attachInfo != null) { 13600 return attachInfo.mHandler; 13601 } 13602 return null; 13603 } 13604 13605 /** 13606 * Returns the queue of runnable for this view. 13607 * 13608 * @return the queue of runnables for this view 13609 */ 13610 private HandlerActionQueue getRunQueue() { 13611 if (mRunQueue == null) { 13612 mRunQueue = new HandlerActionQueue(); 13613 } 13614 return mRunQueue; 13615 } 13616 13617 /** 13618 * Gets the view root associated with the View. 13619 * @return The view root, or null if none. 13620 * @hide 13621 */ 13622 public ViewRootImpl getViewRootImpl() { 13623 if (mAttachInfo != null) { 13624 return mAttachInfo.mViewRootImpl; 13625 } 13626 return null; 13627 } 13628 13629 /** 13630 * @hide 13631 */ 13632 public ThreadedRenderer getHardwareRenderer() { 13633 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 13634 } 13635 13636 /** 13637 * <p>Causes the Runnable to be added to the message queue. 13638 * The runnable will be run on the user interface thread.</p> 13639 * 13640 * @param action The Runnable that will be executed. 13641 * 13642 * @return Returns true if the Runnable was successfully placed in to the 13643 * message queue. Returns false on failure, usually because the 13644 * looper processing the message queue is exiting. 13645 * 13646 * @see #postDelayed 13647 * @see #removeCallbacks 13648 */ 13649 public boolean post(Runnable action) { 13650 final AttachInfo attachInfo = mAttachInfo; 13651 if (attachInfo != null) { 13652 return attachInfo.mHandler.post(action); 13653 } 13654 13655 // Postpone the runnable until we know on which thread it needs to run. 13656 // Assume that the runnable will be successfully placed after attach. 13657 getRunQueue().post(action); 13658 return true; 13659 } 13660 13661 /** 13662 * <p>Causes the Runnable to be added to the message queue, to be run 13663 * after the specified amount of time elapses. 13664 * The runnable will be run on the user interface thread.</p> 13665 * 13666 * @param action The Runnable that will be executed. 13667 * @param delayMillis The delay (in milliseconds) until the Runnable 13668 * will be executed. 13669 * 13670 * @return true if the Runnable was successfully placed in to the 13671 * message queue. Returns false on failure, usually because the 13672 * looper processing the message queue is exiting. Note that a 13673 * result of true does not mean the Runnable will be processed -- 13674 * if the looper is quit before the delivery time of the message 13675 * occurs then the message will be dropped. 13676 * 13677 * @see #post 13678 * @see #removeCallbacks 13679 */ 13680 public boolean postDelayed(Runnable action, long delayMillis) { 13681 final AttachInfo attachInfo = mAttachInfo; 13682 if (attachInfo != null) { 13683 return attachInfo.mHandler.postDelayed(action, delayMillis); 13684 } 13685 13686 // Postpone the runnable until we know on which thread it needs to run. 13687 // Assume that the runnable will be successfully placed after attach. 13688 getRunQueue().postDelayed(action, delayMillis); 13689 return true; 13690 } 13691 13692 /** 13693 * <p>Causes the Runnable to execute on the next animation time step. 13694 * The runnable will be run on the user interface thread.</p> 13695 * 13696 * @param action The Runnable that will be executed. 13697 * 13698 * @see #postOnAnimationDelayed 13699 * @see #removeCallbacks 13700 */ 13701 public void postOnAnimation(Runnable action) { 13702 final AttachInfo attachInfo = mAttachInfo; 13703 if (attachInfo != null) { 13704 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13705 Choreographer.CALLBACK_ANIMATION, action, null); 13706 } else { 13707 // Postpone the runnable until we know 13708 // on which thread it needs to run. 13709 getRunQueue().post(action); 13710 } 13711 } 13712 13713 /** 13714 * <p>Causes the Runnable to execute on the next animation time step, 13715 * after the specified amount of time elapses. 13716 * The runnable will be run on the user interface thread.</p> 13717 * 13718 * @param action The Runnable that will be executed. 13719 * @param delayMillis The delay (in milliseconds) until the Runnable 13720 * will be executed. 13721 * 13722 * @see #postOnAnimation 13723 * @see #removeCallbacks 13724 */ 13725 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13726 final AttachInfo attachInfo = mAttachInfo; 13727 if (attachInfo != null) { 13728 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13729 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 13730 } else { 13731 // Postpone the runnable until we know 13732 // on which thread it needs to run. 13733 getRunQueue().postDelayed(action, delayMillis); 13734 } 13735 } 13736 13737 /** 13738 * <p>Removes the specified Runnable from the message queue.</p> 13739 * 13740 * @param action The Runnable to remove from the message handling queue 13741 * 13742 * @return true if this view could ask the Handler to remove the Runnable, 13743 * false otherwise. When the returned value is true, the Runnable 13744 * may or may not have been actually removed from the message queue 13745 * (for instance, if the Runnable was not in the queue already.) 13746 * 13747 * @see #post 13748 * @see #postDelayed 13749 * @see #postOnAnimation 13750 * @see #postOnAnimationDelayed 13751 */ 13752 public boolean removeCallbacks(Runnable action) { 13753 if (action != null) { 13754 final AttachInfo attachInfo = mAttachInfo; 13755 if (attachInfo != null) { 13756 attachInfo.mHandler.removeCallbacks(action); 13757 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13758 Choreographer.CALLBACK_ANIMATION, action, null); 13759 } 13760 getRunQueue().removeCallbacks(action); 13761 } 13762 return true; 13763 } 13764 13765 /** 13766 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 13767 * Use this to invalidate the View from a non-UI thread.</p> 13768 * 13769 * <p>This method can be invoked from outside of the UI thread 13770 * only when this View is attached to a window.</p> 13771 * 13772 * @see #invalidate() 13773 * @see #postInvalidateDelayed(long) 13774 */ 13775 public void postInvalidate() { 13776 postInvalidateDelayed(0); 13777 } 13778 13779 /** 13780 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13781 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 13782 * 13783 * <p>This method can be invoked from outside of the UI thread 13784 * only when this View is attached to a window.</p> 13785 * 13786 * @param left The left coordinate of the rectangle to invalidate. 13787 * @param top The top coordinate of the rectangle to invalidate. 13788 * @param right The right coordinate of the rectangle to invalidate. 13789 * @param bottom The bottom coordinate of the rectangle to invalidate. 13790 * 13791 * @see #invalidate(int, int, int, int) 13792 * @see #invalidate(Rect) 13793 * @see #postInvalidateDelayed(long, int, int, int, int) 13794 */ 13795 public void postInvalidate(int left, int top, int right, int bottom) { 13796 postInvalidateDelayed(0, left, top, right, bottom); 13797 } 13798 13799 /** 13800 * <p>Cause an invalidate to happen on a subsequent cycle through the event 13801 * loop. Waits for the specified amount of time.</p> 13802 * 13803 * <p>This method can be invoked from outside of the UI thread 13804 * only when this View is attached to a window.</p> 13805 * 13806 * @param delayMilliseconds the duration in milliseconds to delay the 13807 * invalidation by 13808 * 13809 * @see #invalidate() 13810 * @see #postInvalidate() 13811 */ 13812 public void postInvalidateDelayed(long delayMilliseconds) { 13813 // We try only with the AttachInfo because there's no point in invalidating 13814 // if we are not attached to our window 13815 final AttachInfo attachInfo = mAttachInfo; 13816 if (attachInfo != null) { 13817 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 13818 } 13819 } 13820 13821 /** 13822 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13823 * through the event loop. Waits for the specified amount of time.</p> 13824 * 13825 * <p>This method can be invoked from outside of the UI thread 13826 * only when this View is attached to a window.</p> 13827 * 13828 * @param delayMilliseconds the duration in milliseconds to delay the 13829 * invalidation by 13830 * @param left The left coordinate of the rectangle to invalidate. 13831 * @param top The top coordinate of the rectangle to invalidate. 13832 * @param right The right coordinate of the rectangle to invalidate. 13833 * @param bottom The bottom coordinate of the rectangle to invalidate. 13834 * 13835 * @see #invalidate(int, int, int, int) 13836 * @see #invalidate(Rect) 13837 * @see #postInvalidate(int, int, int, int) 13838 */ 13839 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 13840 int right, int bottom) { 13841 13842 // We try only with the AttachInfo because there's no point in invalidating 13843 // if we are not attached to our window 13844 final AttachInfo attachInfo = mAttachInfo; 13845 if (attachInfo != null) { 13846 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13847 info.target = this; 13848 info.left = left; 13849 info.top = top; 13850 info.right = right; 13851 info.bottom = bottom; 13852 13853 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 13854 } 13855 } 13856 13857 /** 13858 * <p>Cause an invalidate to happen on the next animation time step, typically the 13859 * next display frame.</p> 13860 * 13861 * <p>This method can be invoked from outside of the UI thread 13862 * only when this View is attached to a window.</p> 13863 * 13864 * @see #invalidate() 13865 */ 13866 public void postInvalidateOnAnimation() { 13867 // We try only with the AttachInfo because there's no point in invalidating 13868 // if we are not attached to our window 13869 final AttachInfo attachInfo = mAttachInfo; 13870 if (attachInfo != null) { 13871 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 13872 } 13873 } 13874 13875 /** 13876 * <p>Cause an invalidate of the specified area to happen on the next animation 13877 * time step, typically the next display frame.</p> 13878 * 13879 * <p>This method can be invoked from outside of the UI thread 13880 * only when this View is attached to a window.</p> 13881 * 13882 * @param left The left coordinate of the rectangle to invalidate. 13883 * @param top The top coordinate of the rectangle to invalidate. 13884 * @param right The right coordinate of the rectangle to invalidate. 13885 * @param bottom The bottom coordinate of the rectangle to invalidate. 13886 * 13887 * @see #invalidate(int, int, int, int) 13888 * @see #invalidate(Rect) 13889 */ 13890 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 13891 // We try only with the AttachInfo because there's no point in invalidating 13892 // if we are not attached to our window 13893 final AttachInfo attachInfo = mAttachInfo; 13894 if (attachInfo != null) { 13895 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13896 info.target = this; 13897 info.left = left; 13898 info.top = top; 13899 info.right = right; 13900 info.bottom = bottom; 13901 13902 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 13903 } 13904 } 13905 13906 /** 13907 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 13908 * This event is sent at most once every 13909 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 13910 */ 13911 private void postSendViewScrolledAccessibilityEventCallback() { 13912 if (mSendViewScrolledAccessibilityEvent == null) { 13913 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 13914 } 13915 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 13916 mSendViewScrolledAccessibilityEvent.mIsPending = true; 13917 postDelayed(mSendViewScrolledAccessibilityEvent, 13918 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 13919 } 13920 } 13921 13922 /** 13923 * Called by a parent to request that a child update its values for mScrollX 13924 * and mScrollY if necessary. This will typically be done if the child is 13925 * animating a scroll using a {@link android.widget.Scroller Scroller} 13926 * object. 13927 */ 13928 public void computeScroll() { 13929 } 13930 13931 /** 13932 * <p>Indicate whether the horizontal edges are faded when the view is 13933 * scrolled horizontally.</p> 13934 * 13935 * @return true if the horizontal edges should are faded on scroll, false 13936 * otherwise 13937 * 13938 * @see #setHorizontalFadingEdgeEnabled(boolean) 13939 * 13940 * @attr ref android.R.styleable#View_requiresFadingEdge 13941 */ 13942 public boolean isHorizontalFadingEdgeEnabled() { 13943 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 13944 } 13945 13946 /** 13947 * <p>Define whether the horizontal edges should be faded when this view 13948 * is scrolled horizontally.</p> 13949 * 13950 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 13951 * be faded when the view is scrolled 13952 * horizontally 13953 * 13954 * @see #isHorizontalFadingEdgeEnabled() 13955 * 13956 * @attr ref android.R.styleable#View_requiresFadingEdge 13957 */ 13958 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 13959 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 13960 if (horizontalFadingEdgeEnabled) { 13961 initScrollCache(); 13962 } 13963 13964 mViewFlags ^= FADING_EDGE_HORIZONTAL; 13965 } 13966 } 13967 13968 /** 13969 * <p>Indicate whether the vertical edges are faded when the view is 13970 * scrolled horizontally.</p> 13971 * 13972 * @return true if the vertical edges should are faded on scroll, false 13973 * otherwise 13974 * 13975 * @see #setVerticalFadingEdgeEnabled(boolean) 13976 * 13977 * @attr ref android.R.styleable#View_requiresFadingEdge 13978 */ 13979 public boolean isVerticalFadingEdgeEnabled() { 13980 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 13981 } 13982 13983 /** 13984 * <p>Define whether the vertical edges should be faded when this view 13985 * is scrolled vertically.</p> 13986 * 13987 * @param verticalFadingEdgeEnabled true if the vertical edges should 13988 * be faded when the view is scrolled 13989 * vertically 13990 * 13991 * @see #isVerticalFadingEdgeEnabled() 13992 * 13993 * @attr ref android.R.styleable#View_requiresFadingEdge 13994 */ 13995 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 13996 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 13997 if (verticalFadingEdgeEnabled) { 13998 initScrollCache(); 13999 } 14000 14001 mViewFlags ^= FADING_EDGE_VERTICAL; 14002 } 14003 } 14004 14005 /** 14006 * Returns the strength, or intensity, of the top faded edge. The strength is 14007 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14008 * returns 0.0 or 1.0 but no value in between. 14009 * 14010 * Subclasses should override this method to provide a smoother fade transition 14011 * when scrolling occurs. 14012 * 14013 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14014 */ 14015 protected float getTopFadingEdgeStrength() { 14016 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14017 } 14018 14019 /** 14020 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14021 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14022 * returns 0.0 or 1.0 but no value in between. 14023 * 14024 * Subclasses should override this method to provide a smoother fade transition 14025 * when scrolling occurs. 14026 * 14027 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14028 */ 14029 protected float getBottomFadingEdgeStrength() { 14030 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14031 computeVerticalScrollRange() ? 1.0f : 0.0f; 14032 } 14033 14034 /** 14035 * Returns the strength, or intensity, of the left faded edge. The strength is 14036 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14037 * returns 0.0 or 1.0 but no value in between. 14038 * 14039 * Subclasses should override this method to provide a smoother fade transition 14040 * when scrolling occurs. 14041 * 14042 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14043 */ 14044 protected float getLeftFadingEdgeStrength() { 14045 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14046 } 14047 14048 /** 14049 * Returns the strength, or intensity, of the right faded edge. The strength is 14050 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14051 * returns 0.0 or 1.0 but no value in between. 14052 * 14053 * Subclasses should override this method to provide a smoother fade transition 14054 * when scrolling occurs. 14055 * 14056 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14057 */ 14058 protected float getRightFadingEdgeStrength() { 14059 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14060 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14061 } 14062 14063 /** 14064 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14065 * scrollbar is not drawn by default.</p> 14066 * 14067 * @return true if the horizontal scrollbar should be painted, false 14068 * otherwise 14069 * 14070 * @see #setHorizontalScrollBarEnabled(boolean) 14071 */ 14072 public boolean isHorizontalScrollBarEnabled() { 14073 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14074 } 14075 14076 /** 14077 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14078 * scrollbar is not drawn by default.</p> 14079 * 14080 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14081 * be painted 14082 * 14083 * @see #isHorizontalScrollBarEnabled() 14084 */ 14085 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14086 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14087 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14088 computeOpaqueFlags(); 14089 resolvePadding(); 14090 } 14091 } 14092 14093 /** 14094 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14095 * scrollbar is not drawn by default.</p> 14096 * 14097 * @return true if the vertical scrollbar should be painted, false 14098 * otherwise 14099 * 14100 * @see #setVerticalScrollBarEnabled(boolean) 14101 */ 14102 public boolean isVerticalScrollBarEnabled() { 14103 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14104 } 14105 14106 /** 14107 * <p>Define whether the vertical scrollbar should be drawn or not. The 14108 * scrollbar is not drawn by default.</p> 14109 * 14110 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14111 * be painted 14112 * 14113 * @see #isVerticalScrollBarEnabled() 14114 */ 14115 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14116 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14117 mViewFlags ^= SCROLLBARS_VERTICAL; 14118 computeOpaqueFlags(); 14119 resolvePadding(); 14120 } 14121 } 14122 14123 /** 14124 * @hide 14125 */ 14126 protected void recomputePadding() { 14127 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14128 } 14129 14130 /** 14131 * Define whether scrollbars will fade when the view is not scrolling. 14132 * 14133 * @param fadeScrollbars whether to enable fading 14134 * 14135 * @attr ref android.R.styleable#View_fadeScrollbars 14136 */ 14137 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14138 initScrollCache(); 14139 final ScrollabilityCache scrollabilityCache = mScrollCache; 14140 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14141 if (fadeScrollbars) { 14142 scrollabilityCache.state = ScrollabilityCache.OFF; 14143 } else { 14144 scrollabilityCache.state = ScrollabilityCache.ON; 14145 } 14146 } 14147 14148 /** 14149 * 14150 * Returns true if scrollbars will fade when this view is not scrolling 14151 * 14152 * @return true if scrollbar fading is enabled 14153 * 14154 * @attr ref android.R.styleable#View_fadeScrollbars 14155 */ 14156 public boolean isScrollbarFadingEnabled() { 14157 return mScrollCache != null && mScrollCache.fadeScrollBars; 14158 } 14159 14160 /** 14161 * 14162 * Returns the delay before scrollbars fade. 14163 * 14164 * @return the delay before scrollbars fade 14165 * 14166 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14167 */ 14168 public int getScrollBarDefaultDelayBeforeFade() { 14169 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14170 mScrollCache.scrollBarDefaultDelayBeforeFade; 14171 } 14172 14173 /** 14174 * Define the delay before scrollbars fade. 14175 * 14176 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14177 * 14178 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14179 */ 14180 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14181 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14182 } 14183 14184 /** 14185 * 14186 * Returns the scrollbar fade duration. 14187 * 14188 * @return the scrollbar fade duration 14189 * 14190 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14191 */ 14192 public int getScrollBarFadeDuration() { 14193 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14194 mScrollCache.scrollBarFadeDuration; 14195 } 14196 14197 /** 14198 * Define the scrollbar fade duration. 14199 * 14200 * @param scrollBarFadeDuration - the scrollbar fade duration 14201 * 14202 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14203 */ 14204 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14205 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14206 } 14207 14208 /** 14209 * 14210 * Returns the scrollbar size. 14211 * 14212 * @return the scrollbar size 14213 * 14214 * @attr ref android.R.styleable#View_scrollbarSize 14215 */ 14216 public int getScrollBarSize() { 14217 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14218 mScrollCache.scrollBarSize; 14219 } 14220 14221 /** 14222 * Define the scrollbar size. 14223 * 14224 * @param scrollBarSize - the scrollbar size 14225 * 14226 * @attr ref android.R.styleable#View_scrollbarSize 14227 */ 14228 public void setScrollBarSize(int scrollBarSize) { 14229 getScrollCache().scrollBarSize = scrollBarSize; 14230 } 14231 14232 /** 14233 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14234 * inset. When inset, they add to the padding of the view. And the scrollbars 14235 * can be drawn inside the padding area or on the edge of the view. For example, 14236 * if a view has a background drawable and you want to draw the scrollbars 14237 * inside the padding specified by the drawable, you can use 14238 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14239 * appear at the edge of the view, ignoring the padding, then you can use 14240 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14241 * @param style the style of the scrollbars. Should be one of 14242 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14243 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14244 * @see #SCROLLBARS_INSIDE_OVERLAY 14245 * @see #SCROLLBARS_INSIDE_INSET 14246 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14247 * @see #SCROLLBARS_OUTSIDE_INSET 14248 * 14249 * @attr ref android.R.styleable#View_scrollbarStyle 14250 */ 14251 public void setScrollBarStyle(@ScrollBarStyle int style) { 14252 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14253 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14254 computeOpaqueFlags(); 14255 resolvePadding(); 14256 } 14257 } 14258 14259 /** 14260 * <p>Returns the current scrollbar style.</p> 14261 * @return the current scrollbar style 14262 * @see #SCROLLBARS_INSIDE_OVERLAY 14263 * @see #SCROLLBARS_INSIDE_INSET 14264 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14265 * @see #SCROLLBARS_OUTSIDE_INSET 14266 * 14267 * @attr ref android.R.styleable#View_scrollbarStyle 14268 */ 14269 @ViewDebug.ExportedProperty(mapping = { 14270 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14271 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14272 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14273 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14274 }) 14275 @ScrollBarStyle 14276 public int getScrollBarStyle() { 14277 return mViewFlags & SCROLLBARS_STYLE_MASK; 14278 } 14279 14280 /** 14281 * <p>Compute the horizontal range that the horizontal scrollbar 14282 * represents.</p> 14283 * 14284 * <p>The range is expressed in arbitrary units that must be the same as the 14285 * units used by {@link #computeHorizontalScrollExtent()} and 14286 * {@link #computeHorizontalScrollOffset()}.</p> 14287 * 14288 * <p>The default range is the drawing width of this view.</p> 14289 * 14290 * @return the total horizontal range represented by the horizontal 14291 * scrollbar 14292 * 14293 * @see #computeHorizontalScrollExtent() 14294 * @see #computeHorizontalScrollOffset() 14295 * @see android.widget.ScrollBarDrawable 14296 */ 14297 protected int computeHorizontalScrollRange() { 14298 return getWidth(); 14299 } 14300 14301 /** 14302 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14303 * within the horizontal range. This value is used to compute the position 14304 * of the thumb within the scrollbar's track.</p> 14305 * 14306 * <p>The range is expressed in arbitrary units that must be the same as the 14307 * units used by {@link #computeHorizontalScrollRange()} and 14308 * {@link #computeHorizontalScrollExtent()}.</p> 14309 * 14310 * <p>The default offset is the scroll offset of this view.</p> 14311 * 14312 * @return the horizontal offset of the scrollbar's thumb 14313 * 14314 * @see #computeHorizontalScrollRange() 14315 * @see #computeHorizontalScrollExtent() 14316 * @see android.widget.ScrollBarDrawable 14317 */ 14318 protected int computeHorizontalScrollOffset() { 14319 return mScrollX; 14320 } 14321 14322 /** 14323 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14324 * within the horizontal range. This value is used to compute the length 14325 * of the thumb within the scrollbar's track.</p> 14326 * 14327 * <p>The range is expressed in arbitrary units that must be the same as the 14328 * units used by {@link #computeHorizontalScrollRange()} and 14329 * {@link #computeHorizontalScrollOffset()}.</p> 14330 * 14331 * <p>The default extent is the drawing width of this view.</p> 14332 * 14333 * @return the horizontal extent of the scrollbar's thumb 14334 * 14335 * @see #computeHorizontalScrollRange() 14336 * @see #computeHorizontalScrollOffset() 14337 * @see android.widget.ScrollBarDrawable 14338 */ 14339 protected int computeHorizontalScrollExtent() { 14340 return getWidth(); 14341 } 14342 14343 /** 14344 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14345 * 14346 * <p>The range is expressed in arbitrary units that must be the same as the 14347 * units used by {@link #computeVerticalScrollExtent()} and 14348 * {@link #computeVerticalScrollOffset()}.</p> 14349 * 14350 * @return the total vertical range represented by the vertical scrollbar 14351 * 14352 * <p>The default range is the drawing height of this view.</p> 14353 * 14354 * @see #computeVerticalScrollExtent() 14355 * @see #computeVerticalScrollOffset() 14356 * @see android.widget.ScrollBarDrawable 14357 */ 14358 protected int computeVerticalScrollRange() { 14359 return getHeight(); 14360 } 14361 14362 /** 14363 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14364 * within the horizontal range. This value is used to compute the position 14365 * of the thumb within the scrollbar's track.</p> 14366 * 14367 * <p>The range is expressed in arbitrary units that must be the same as the 14368 * units used by {@link #computeVerticalScrollRange()} and 14369 * {@link #computeVerticalScrollExtent()}.</p> 14370 * 14371 * <p>The default offset is the scroll offset of this view.</p> 14372 * 14373 * @return the vertical offset of the scrollbar's thumb 14374 * 14375 * @see #computeVerticalScrollRange() 14376 * @see #computeVerticalScrollExtent() 14377 * @see android.widget.ScrollBarDrawable 14378 */ 14379 protected int computeVerticalScrollOffset() { 14380 return mScrollY; 14381 } 14382 14383 /** 14384 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14385 * within the vertical range. This value is used to compute the length 14386 * of the thumb within the scrollbar's track.</p> 14387 * 14388 * <p>The range is expressed in arbitrary units that must be the same as the 14389 * units used by {@link #computeVerticalScrollRange()} and 14390 * {@link #computeVerticalScrollOffset()}.</p> 14391 * 14392 * <p>The default extent is the drawing height of this view.</p> 14393 * 14394 * @return the vertical extent of the scrollbar's thumb 14395 * 14396 * @see #computeVerticalScrollRange() 14397 * @see #computeVerticalScrollOffset() 14398 * @see android.widget.ScrollBarDrawable 14399 */ 14400 protected int computeVerticalScrollExtent() { 14401 return getHeight(); 14402 } 14403 14404 /** 14405 * Check if this view can be scrolled horizontally in a certain direction. 14406 * 14407 * @param direction Negative to check scrolling left, positive to check scrolling right. 14408 * @return true if this view can be scrolled in the specified direction, false otherwise. 14409 */ 14410 public boolean canScrollHorizontally(int direction) { 14411 final int offset = computeHorizontalScrollOffset(); 14412 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14413 if (range == 0) return false; 14414 if (direction < 0) { 14415 return offset > 0; 14416 } else { 14417 return offset < range - 1; 14418 } 14419 } 14420 14421 /** 14422 * Check if this view can be scrolled vertically in a certain direction. 14423 * 14424 * @param direction Negative to check scrolling up, positive to check scrolling down. 14425 * @return true if this view can be scrolled in the specified direction, false otherwise. 14426 */ 14427 public boolean canScrollVertically(int direction) { 14428 final int offset = computeVerticalScrollOffset(); 14429 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14430 if (range == 0) return false; 14431 if (direction < 0) { 14432 return offset > 0; 14433 } else { 14434 return offset < range - 1; 14435 } 14436 } 14437 14438 void getScrollIndicatorBounds(@NonNull Rect out) { 14439 out.left = mScrollX; 14440 out.right = mScrollX + mRight - mLeft; 14441 out.top = mScrollY; 14442 out.bottom = mScrollY + mBottom - mTop; 14443 } 14444 14445 private void onDrawScrollIndicators(Canvas c) { 14446 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14447 // No scroll indicators enabled. 14448 return; 14449 } 14450 14451 final Drawable dr = mScrollIndicatorDrawable; 14452 if (dr == null) { 14453 // Scroll indicators aren't supported here. 14454 return; 14455 } 14456 14457 final int h = dr.getIntrinsicHeight(); 14458 final int w = dr.getIntrinsicWidth(); 14459 final Rect rect = mAttachInfo.mTmpInvalRect; 14460 getScrollIndicatorBounds(rect); 14461 14462 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14463 final boolean canScrollUp = canScrollVertically(-1); 14464 if (canScrollUp) { 14465 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14466 dr.draw(c); 14467 } 14468 } 14469 14470 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14471 final boolean canScrollDown = canScrollVertically(1); 14472 if (canScrollDown) { 14473 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14474 dr.draw(c); 14475 } 14476 } 14477 14478 final int leftRtl; 14479 final int rightRtl; 14480 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14481 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14482 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14483 } else { 14484 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14485 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14486 } 14487 14488 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14489 if ((mPrivateFlags3 & leftMask) != 0) { 14490 final boolean canScrollLeft = canScrollHorizontally(-1); 14491 if (canScrollLeft) { 14492 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14493 dr.draw(c); 14494 } 14495 } 14496 14497 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14498 if ((mPrivateFlags3 & rightMask) != 0) { 14499 final boolean canScrollRight = canScrollHorizontally(1); 14500 if (canScrollRight) { 14501 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14502 dr.draw(c); 14503 } 14504 } 14505 } 14506 14507 private void getHorizontalScrollBarBounds(Rect bounds) { 14508 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14509 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14510 && !isVerticalScrollBarHidden(); 14511 final int size = getHorizontalScrollbarHeight(); 14512 final int verticalScrollBarGap = drawVerticalScrollBar ? 14513 getVerticalScrollbarWidth() : 0; 14514 final int width = mRight - mLeft; 14515 final int height = mBottom - mTop; 14516 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14517 bounds.left = mScrollX + (mPaddingLeft & inside); 14518 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14519 bounds.bottom = bounds.top + size; 14520 } 14521 14522 private void getVerticalScrollBarBounds(Rect bounds) { 14523 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14524 final int size = getVerticalScrollbarWidth(); 14525 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14526 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14527 verticalScrollbarPosition = isLayoutRtl() ? 14528 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14529 } 14530 final int width = mRight - mLeft; 14531 final int height = mBottom - mTop; 14532 switch (verticalScrollbarPosition) { 14533 default: 14534 case SCROLLBAR_POSITION_RIGHT: 14535 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14536 break; 14537 case SCROLLBAR_POSITION_LEFT: 14538 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14539 break; 14540 } 14541 bounds.top = mScrollY + (mPaddingTop & inside); 14542 bounds.right = bounds.left + size; 14543 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14544 } 14545 14546 /** 14547 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14548 * scrollbars are painted only if they have been awakened first.</p> 14549 * 14550 * @param canvas the canvas on which to draw the scrollbars 14551 * 14552 * @see #awakenScrollBars(int) 14553 */ 14554 protected final void onDrawScrollBars(Canvas canvas) { 14555 // scrollbars are drawn only when the animation is running 14556 final ScrollabilityCache cache = mScrollCache; 14557 if (cache != null) { 14558 14559 int state = cache.state; 14560 14561 if (state == ScrollabilityCache.OFF) { 14562 return; 14563 } 14564 14565 boolean invalidate = false; 14566 14567 if (state == ScrollabilityCache.FADING) { 14568 // We're fading -- get our fade interpolation 14569 if (cache.interpolatorValues == null) { 14570 cache.interpolatorValues = new float[1]; 14571 } 14572 14573 float[] values = cache.interpolatorValues; 14574 14575 // Stops the animation if we're done 14576 if (cache.scrollBarInterpolator.timeToValues(values) == 14577 Interpolator.Result.FREEZE_END) { 14578 cache.state = ScrollabilityCache.OFF; 14579 } else { 14580 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14581 } 14582 14583 // This will make the scroll bars inval themselves after 14584 // drawing. We only want this when we're fading so that 14585 // we prevent excessive redraws 14586 invalidate = true; 14587 } else { 14588 // We're just on -- but we may have been fading before so 14589 // reset alpha 14590 cache.scrollBar.mutate().setAlpha(255); 14591 } 14592 14593 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14594 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14595 && !isVerticalScrollBarHidden(); 14596 14597 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14598 final ScrollBarDrawable scrollBar = cache.scrollBar; 14599 14600 if (drawHorizontalScrollBar) { 14601 scrollBar.setParameters(computeHorizontalScrollRange(), 14602 computeHorizontalScrollOffset(), 14603 computeHorizontalScrollExtent(), false); 14604 final Rect bounds = cache.mScrollBarBounds; 14605 getHorizontalScrollBarBounds(bounds); 14606 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14607 bounds.right, bounds.bottom); 14608 if (invalidate) { 14609 invalidate(bounds); 14610 } 14611 } 14612 14613 if (drawVerticalScrollBar) { 14614 scrollBar.setParameters(computeVerticalScrollRange(), 14615 computeVerticalScrollOffset(), 14616 computeVerticalScrollExtent(), true); 14617 final Rect bounds = cache.mScrollBarBounds; 14618 getVerticalScrollBarBounds(bounds); 14619 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14620 bounds.right, bounds.bottom); 14621 if (invalidate) { 14622 invalidate(bounds); 14623 } 14624 } 14625 } 14626 } 14627 } 14628 14629 /** 14630 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14631 * FastScroller is visible. 14632 * @return whether to temporarily hide the vertical scrollbar 14633 * @hide 14634 */ 14635 protected boolean isVerticalScrollBarHidden() { 14636 return false; 14637 } 14638 14639 /** 14640 * <p>Draw the horizontal scrollbar if 14641 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14642 * 14643 * @param canvas the canvas on which to draw the scrollbar 14644 * @param scrollBar the scrollbar's drawable 14645 * 14646 * @see #isHorizontalScrollBarEnabled() 14647 * @see #computeHorizontalScrollRange() 14648 * @see #computeHorizontalScrollExtent() 14649 * @see #computeHorizontalScrollOffset() 14650 * @see android.widget.ScrollBarDrawable 14651 * @hide 14652 */ 14653 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14654 int l, int t, int r, int b) { 14655 scrollBar.setBounds(l, t, r, b); 14656 scrollBar.draw(canvas); 14657 } 14658 14659 /** 14660 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14661 * returns true.</p> 14662 * 14663 * @param canvas the canvas on which to draw the scrollbar 14664 * @param scrollBar the scrollbar's drawable 14665 * 14666 * @see #isVerticalScrollBarEnabled() 14667 * @see #computeVerticalScrollRange() 14668 * @see #computeVerticalScrollExtent() 14669 * @see #computeVerticalScrollOffset() 14670 * @see android.widget.ScrollBarDrawable 14671 * @hide 14672 */ 14673 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14674 int l, int t, int r, int b) { 14675 scrollBar.setBounds(l, t, r, b); 14676 scrollBar.draw(canvas); 14677 } 14678 14679 /** 14680 * Implement this to do your drawing. 14681 * 14682 * @param canvas the canvas on which the background will be drawn 14683 */ 14684 protected void onDraw(Canvas canvas) { 14685 } 14686 14687 /* 14688 * Caller is responsible for calling requestLayout if necessary. 14689 * (This allows addViewInLayout to not request a new layout.) 14690 */ 14691 void assignParent(ViewParent parent) { 14692 if (mParent == null) { 14693 mParent = parent; 14694 } else if (parent == null) { 14695 mParent = null; 14696 } else { 14697 throw new RuntimeException("view " + this + " being added, but" 14698 + " it already has a parent"); 14699 } 14700 } 14701 14702 /** 14703 * This is called when the view is attached to a window. At this point it 14704 * has a Surface and will start drawing. Note that this function is 14705 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 14706 * however it may be called any time before the first onDraw -- including 14707 * before or after {@link #onMeasure(int, int)}. 14708 * 14709 * @see #onDetachedFromWindow() 14710 */ 14711 @CallSuper 14712 protected void onAttachedToWindow() { 14713 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 14714 mParent.requestTransparentRegion(this); 14715 } 14716 14717 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14718 14719 jumpDrawablesToCurrentState(); 14720 14721 resetSubtreeAccessibilityStateChanged(); 14722 14723 // rebuild, since Outline not maintained while View is detached 14724 rebuildOutline(); 14725 14726 if (isFocused()) { 14727 InputMethodManager imm = InputMethodManager.peekInstance(); 14728 if (imm != null) { 14729 imm.focusIn(this); 14730 } 14731 } 14732 } 14733 14734 /** 14735 * Resolve all RTL related properties. 14736 * 14737 * @return true if resolution of RTL properties has been done 14738 * 14739 * @hide 14740 */ 14741 public boolean resolveRtlPropertiesIfNeeded() { 14742 if (!needRtlPropertiesResolution()) return false; 14743 14744 // Order is important here: LayoutDirection MUST be resolved first 14745 if (!isLayoutDirectionResolved()) { 14746 resolveLayoutDirection(); 14747 resolveLayoutParams(); 14748 } 14749 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 14750 if (!isTextDirectionResolved()) { 14751 resolveTextDirection(); 14752 } 14753 if (!isTextAlignmentResolved()) { 14754 resolveTextAlignment(); 14755 } 14756 // Should resolve Drawables before Padding because we need the layout direction of the 14757 // Drawable to correctly resolve Padding. 14758 if (!areDrawablesResolved()) { 14759 resolveDrawables(); 14760 } 14761 if (!isPaddingResolved()) { 14762 resolvePadding(); 14763 } 14764 onRtlPropertiesChanged(getLayoutDirection()); 14765 return true; 14766 } 14767 14768 /** 14769 * Reset resolution of all RTL related properties. 14770 * 14771 * @hide 14772 */ 14773 public void resetRtlProperties() { 14774 resetResolvedLayoutDirection(); 14775 resetResolvedTextDirection(); 14776 resetResolvedTextAlignment(); 14777 resetResolvedPadding(); 14778 resetResolvedDrawables(); 14779 } 14780 14781 /** 14782 * @see #onScreenStateChanged(int) 14783 */ 14784 void dispatchScreenStateChanged(int screenState) { 14785 onScreenStateChanged(screenState); 14786 } 14787 14788 /** 14789 * This method is called whenever the state of the screen this view is 14790 * attached to changes. A state change will usually occurs when the screen 14791 * turns on or off (whether it happens automatically or the user does it 14792 * manually.) 14793 * 14794 * @param screenState The new state of the screen. Can be either 14795 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 14796 */ 14797 public void onScreenStateChanged(int screenState) { 14798 } 14799 14800 /** 14801 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 14802 */ 14803 private boolean hasRtlSupport() { 14804 return mContext.getApplicationInfo().hasRtlSupport(); 14805 } 14806 14807 /** 14808 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 14809 * RTL not supported) 14810 */ 14811 private boolean isRtlCompatibilityMode() { 14812 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 14813 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 14814 } 14815 14816 /** 14817 * @return true if RTL properties need resolution. 14818 * 14819 */ 14820 private boolean needRtlPropertiesResolution() { 14821 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 14822 } 14823 14824 /** 14825 * Called when any RTL property (layout direction or text direction or text alignment) has 14826 * been changed. 14827 * 14828 * Subclasses need to override this method to take care of cached information that depends on the 14829 * resolved layout direction, or to inform child views that inherit their layout direction. 14830 * 14831 * The default implementation does nothing. 14832 * 14833 * @param layoutDirection the direction of the layout 14834 * 14835 * @see #LAYOUT_DIRECTION_LTR 14836 * @see #LAYOUT_DIRECTION_RTL 14837 */ 14838 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 14839 } 14840 14841 /** 14842 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 14843 * that the parent directionality can and will be resolved before its children. 14844 * 14845 * @return true if resolution has been done, false otherwise. 14846 * 14847 * @hide 14848 */ 14849 public boolean resolveLayoutDirection() { 14850 // Clear any previous layout direction resolution 14851 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14852 14853 if (hasRtlSupport()) { 14854 // Set resolved depending on layout direction 14855 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 14856 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 14857 case LAYOUT_DIRECTION_INHERIT: 14858 // We cannot resolve yet. LTR is by default and let the resolution happen again 14859 // later to get the correct resolved value 14860 if (!canResolveLayoutDirection()) return false; 14861 14862 // Parent has not yet resolved, LTR is still the default 14863 try { 14864 if (!mParent.isLayoutDirectionResolved()) return false; 14865 14866 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14867 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14868 } 14869 } catch (AbstractMethodError e) { 14870 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14871 " does not fully implement ViewParent", e); 14872 } 14873 break; 14874 case LAYOUT_DIRECTION_RTL: 14875 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14876 break; 14877 case LAYOUT_DIRECTION_LOCALE: 14878 if((LAYOUT_DIRECTION_RTL == 14879 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 14880 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14881 } 14882 break; 14883 default: 14884 // Nothing to do, LTR by default 14885 } 14886 } 14887 14888 // Set to resolved 14889 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14890 return true; 14891 } 14892 14893 /** 14894 * Check if layout direction resolution can be done. 14895 * 14896 * @return true if layout direction resolution can be done otherwise return false. 14897 */ 14898 public boolean canResolveLayoutDirection() { 14899 switch (getRawLayoutDirection()) { 14900 case LAYOUT_DIRECTION_INHERIT: 14901 if (mParent != null) { 14902 try { 14903 return mParent.canResolveLayoutDirection(); 14904 } catch (AbstractMethodError e) { 14905 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14906 " does not fully implement ViewParent", e); 14907 } 14908 } 14909 return false; 14910 14911 default: 14912 return true; 14913 } 14914 } 14915 14916 /** 14917 * Reset the resolved layout direction. Layout direction will be resolved during a call to 14918 * {@link #onMeasure(int, int)}. 14919 * 14920 * @hide 14921 */ 14922 public void resetResolvedLayoutDirection() { 14923 // Reset the current resolved bits 14924 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14925 } 14926 14927 /** 14928 * @return true if the layout direction is inherited. 14929 * 14930 * @hide 14931 */ 14932 public boolean isLayoutDirectionInherited() { 14933 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 14934 } 14935 14936 /** 14937 * @return true if layout direction has been resolved. 14938 */ 14939 public boolean isLayoutDirectionResolved() { 14940 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14941 } 14942 14943 /** 14944 * Return if padding has been resolved 14945 * 14946 * @hide 14947 */ 14948 boolean isPaddingResolved() { 14949 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 14950 } 14951 14952 /** 14953 * Resolves padding depending on layout direction, if applicable, and 14954 * recomputes internal padding values to adjust for scroll bars. 14955 * 14956 * @hide 14957 */ 14958 public void resolvePadding() { 14959 final int resolvedLayoutDirection = getLayoutDirection(); 14960 14961 if (!isRtlCompatibilityMode()) { 14962 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 14963 // If start / end padding are defined, they will be resolved (hence overriding) to 14964 // left / right or right / left depending on the resolved layout direction. 14965 // If start / end padding are not defined, use the left / right ones. 14966 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 14967 Rect padding = sThreadLocal.get(); 14968 if (padding == null) { 14969 padding = new Rect(); 14970 sThreadLocal.set(padding); 14971 } 14972 mBackground.getPadding(padding); 14973 if (!mLeftPaddingDefined) { 14974 mUserPaddingLeftInitial = padding.left; 14975 } 14976 if (!mRightPaddingDefined) { 14977 mUserPaddingRightInitial = padding.right; 14978 } 14979 } 14980 switch (resolvedLayoutDirection) { 14981 case LAYOUT_DIRECTION_RTL: 14982 if (mUserPaddingStart != UNDEFINED_PADDING) { 14983 mUserPaddingRight = mUserPaddingStart; 14984 } else { 14985 mUserPaddingRight = mUserPaddingRightInitial; 14986 } 14987 if (mUserPaddingEnd != UNDEFINED_PADDING) { 14988 mUserPaddingLeft = mUserPaddingEnd; 14989 } else { 14990 mUserPaddingLeft = mUserPaddingLeftInitial; 14991 } 14992 break; 14993 case LAYOUT_DIRECTION_LTR: 14994 default: 14995 if (mUserPaddingStart != UNDEFINED_PADDING) { 14996 mUserPaddingLeft = mUserPaddingStart; 14997 } else { 14998 mUserPaddingLeft = mUserPaddingLeftInitial; 14999 } 15000 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15001 mUserPaddingRight = mUserPaddingEnd; 15002 } else { 15003 mUserPaddingRight = mUserPaddingRightInitial; 15004 } 15005 } 15006 15007 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15008 } 15009 15010 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15011 onRtlPropertiesChanged(resolvedLayoutDirection); 15012 15013 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15014 } 15015 15016 /** 15017 * Reset the resolved layout direction. 15018 * 15019 * @hide 15020 */ 15021 public void resetResolvedPadding() { 15022 resetResolvedPaddingInternal(); 15023 } 15024 15025 /** 15026 * Used when we only want to reset *this* view's padding and not trigger overrides 15027 * in ViewGroup that reset children too. 15028 */ 15029 void resetResolvedPaddingInternal() { 15030 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15031 } 15032 15033 /** 15034 * This is called when the view is detached from a window. At this point it 15035 * no longer has a surface for drawing. 15036 * 15037 * @see #onAttachedToWindow() 15038 */ 15039 @CallSuper 15040 protected void onDetachedFromWindow() { 15041 } 15042 15043 /** 15044 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15045 * after onDetachedFromWindow(). 15046 * 15047 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15048 * The super method should be called at the end of the overridden method to ensure 15049 * subclasses are destroyed first 15050 * 15051 * @hide 15052 */ 15053 @CallSuper 15054 protected void onDetachedFromWindowInternal() { 15055 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15056 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15057 15058 removeUnsetPressCallback(); 15059 removeLongPressCallback(); 15060 removePerformClickCallback(); 15061 removeSendViewScrolledAccessibilityEventCallback(); 15062 stopNestedScroll(); 15063 15064 // Anything that started animating right before detach should already 15065 // be in its final state when re-attached. 15066 jumpDrawablesToCurrentState(); 15067 15068 destroyDrawingCache(); 15069 15070 cleanupDraw(); 15071 releasePointerCapture(); 15072 mCurrentAnimation = null; 15073 } 15074 15075 private void cleanupDraw() { 15076 resetDisplayList(); 15077 if (mAttachInfo != null) { 15078 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15079 } 15080 } 15081 15082 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15083 } 15084 15085 /** 15086 * @return The number of times this view has been attached to a window 15087 */ 15088 protected int getWindowAttachCount() { 15089 return mWindowAttachCount; 15090 } 15091 15092 /** 15093 * Retrieve a unique token identifying the window this view is attached to. 15094 * @return Return the window's token for use in 15095 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15096 */ 15097 public IBinder getWindowToken() { 15098 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15099 } 15100 15101 /** 15102 * Retrieve the {@link WindowId} for the window this view is 15103 * currently attached to. 15104 */ 15105 public WindowId getWindowId() { 15106 if (mAttachInfo == null) { 15107 return null; 15108 } 15109 if (mAttachInfo.mWindowId == null) { 15110 try { 15111 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15112 mAttachInfo.mWindowToken); 15113 mAttachInfo.mWindowId = new WindowId( 15114 mAttachInfo.mIWindowId); 15115 } catch (RemoteException e) { 15116 } 15117 } 15118 return mAttachInfo.mWindowId; 15119 } 15120 15121 /** 15122 * Retrieve a unique token identifying the top-level "real" window of 15123 * the window that this view is attached to. That is, this is like 15124 * {@link #getWindowToken}, except if the window this view in is a panel 15125 * window (attached to another containing window), then the token of 15126 * the containing window is returned instead. 15127 * 15128 * @return Returns the associated window token, either 15129 * {@link #getWindowToken()} or the containing window's token. 15130 */ 15131 public IBinder getApplicationWindowToken() { 15132 AttachInfo ai = mAttachInfo; 15133 if (ai != null) { 15134 IBinder appWindowToken = ai.mPanelParentWindowToken; 15135 if (appWindowToken == null) { 15136 appWindowToken = ai.mWindowToken; 15137 } 15138 return appWindowToken; 15139 } 15140 return null; 15141 } 15142 15143 /** 15144 * Gets the logical display to which the view's window has been attached. 15145 * 15146 * @return The logical display, or null if the view is not currently attached to a window. 15147 */ 15148 public Display getDisplay() { 15149 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15150 } 15151 15152 /** 15153 * Retrieve private session object this view hierarchy is using to 15154 * communicate with the window manager. 15155 * @return the session object to communicate with the window manager 15156 */ 15157 /*package*/ IWindowSession getWindowSession() { 15158 return mAttachInfo != null ? mAttachInfo.mSession : null; 15159 } 15160 15161 /** 15162 * Return the visibility value of the least visible component passed. 15163 */ 15164 int combineVisibility(int vis1, int vis2) { 15165 // This works because VISIBLE < INVISIBLE < GONE. 15166 return Math.max(vis1, vis2); 15167 } 15168 15169 /** 15170 * @param info the {@link android.view.View.AttachInfo} to associated with 15171 * this view 15172 */ 15173 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15174 mAttachInfo = info; 15175 if (mOverlay != null) { 15176 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15177 } 15178 mWindowAttachCount++; 15179 // We will need to evaluate the drawable state at least once. 15180 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15181 if (mFloatingTreeObserver != null) { 15182 info.mTreeObserver.merge(mFloatingTreeObserver); 15183 mFloatingTreeObserver = null; 15184 } 15185 15186 registerPendingFrameMetricsObservers(); 15187 15188 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15189 mAttachInfo.mScrollContainers.add(this); 15190 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15191 } 15192 // Transfer all pending runnables. 15193 if (mRunQueue != null) { 15194 mRunQueue.executeActions(info.mHandler); 15195 mRunQueue = null; 15196 } 15197 performCollectViewAttributes(mAttachInfo, visibility); 15198 onAttachedToWindow(); 15199 15200 ListenerInfo li = mListenerInfo; 15201 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15202 li != null ? li.mOnAttachStateChangeListeners : null; 15203 if (listeners != null && listeners.size() > 0) { 15204 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15205 // perform the dispatching. The iterator is a safe guard against listeners that 15206 // could mutate the list by calling the various add/remove methods. This prevents 15207 // the array from being modified while we iterate it. 15208 for (OnAttachStateChangeListener listener : listeners) { 15209 listener.onViewAttachedToWindow(this); 15210 } 15211 } 15212 15213 int vis = info.mWindowVisibility; 15214 if (vis != GONE) { 15215 onWindowVisibilityChanged(vis); 15216 } 15217 15218 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15219 // As all views in the subtree will already receive dispatchAttachedToWindow 15220 // traversing the subtree again here is not desired. 15221 onVisibilityChanged(this, visibility); 15222 15223 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15224 // If nobody has evaluated the drawable state yet, then do it now. 15225 refreshDrawableState(); 15226 } 15227 needGlobalAttributesUpdate(false); 15228 } 15229 15230 void dispatchDetachedFromWindow() { 15231 AttachInfo info = mAttachInfo; 15232 if (info != null) { 15233 int vis = info.mWindowVisibility; 15234 if (vis != GONE) { 15235 onWindowVisibilityChanged(GONE); 15236 } 15237 } 15238 15239 onDetachedFromWindow(); 15240 onDetachedFromWindowInternal(); 15241 15242 InputMethodManager imm = InputMethodManager.peekInstance(); 15243 if (imm != null) { 15244 imm.onViewDetachedFromWindow(this); 15245 } 15246 15247 ListenerInfo li = mListenerInfo; 15248 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15249 li != null ? li.mOnAttachStateChangeListeners : null; 15250 if (listeners != null && listeners.size() > 0) { 15251 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15252 // perform the dispatching. The iterator is a safe guard against listeners that 15253 // could mutate the list by calling the various add/remove methods. This prevents 15254 // the array from being modified while we iterate it. 15255 for (OnAttachStateChangeListener listener : listeners) { 15256 listener.onViewDetachedFromWindow(this); 15257 } 15258 } 15259 15260 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15261 mAttachInfo.mScrollContainers.remove(this); 15262 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15263 } 15264 15265 mAttachInfo = null; 15266 if (mOverlay != null) { 15267 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15268 } 15269 } 15270 15271 /** 15272 * Cancel any deferred high-level input events that were previously posted to the event queue. 15273 * 15274 * <p>Many views post high-level events such as click handlers to the event queue 15275 * to run deferred in order to preserve a desired user experience - clearing visible 15276 * pressed states before executing, etc. This method will abort any events of this nature 15277 * that are currently in flight.</p> 15278 * 15279 * <p>Custom views that generate their own high-level deferred input events should override 15280 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15281 * 15282 * <p>This will also cancel pending input events for any child views.</p> 15283 * 15284 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15285 * This will not impact newer events posted after this call that may occur as a result of 15286 * lower-level input events still waiting in the queue. If you are trying to prevent 15287 * double-submitted events for the duration of some sort of asynchronous transaction 15288 * you should also take other steps to protect against unexpected double inputs e.g. calling 15289 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15290 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15291 */ 15292 public final void cancelPendingInputEvents() { 15293 dispatchCancelPendingInputEvents(); 15294 } 15295 15296 /** 15297 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15298 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15299 */ 15300 void dispatchCancelPendingInputEvents() { 15301 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15302 onCancelPendingInputEvents(); 15303 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15304 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15305 " did not call through to super.onCancelPendingInputEvents()"); 15306 } 15307 } 15308 15309 /** 15310 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15311 * a parent view. 15312 * 15313 * <p>This method is responsible for removing any pending high-level input events that were 15314 * posted to the event queue to run later. Custom view classes that post their own deferred 15315 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15316 * {@link android.os.Handler} should override this method, call 15317 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15318 * </p> 15319 */ 15320 public void onCancelPendingInputEvents() { 15321 removePerformClickCallback(); 15322 cancelLongPress(); 15323 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15324 } 15325 15326 /** 15327 * Store this view hierarchy's frozen state into the given container. 15328 * 15329 * @param container The SparseArray in which to save the view's state. 15330 * 15331 * @see #restoreHierarchyState(android.util.SparseArray) 15332 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15333 * @see #onSaveInstanceState() 15334 */ 15335 public void saveHierarchyState(SparseArray<Parcelable> container) { 15336 dispatchSaveInstanceState(container); 15337 } 15338 15339 /** 15340 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15341 * this view and its children. May be overridden to modify how freezing happens to a 15342 * view's children; for example, some views may want to not store state for their children. 15343 * 15344 * @param container The SparseArray in which to save the view's state. 15345 * 15346 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15347 * @see #saveHierarchyState(android.util.SparseArray) 15348 * @see #onSaveInstanceState() 15349 */ 15350 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15351 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15352 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15353 Parcelable state = onSaveInstanceState(); 15354 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15355 throw new IllegalStateException( 15356 "Derived class did not call super.onSaveInstanceState()"); 15357 } 15358 if (state != null) { 15359 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15360 // + ": " + state); 15361 container.put(mID, state); 15362 } 15363 } 15364 } 15365 15366 /** 15367 * Hook allowing a view to generate a representation of its internal state 15368 * that can later be used to create a new instance with that same state. 15369 * This state should only contain information that is not persistent or can 15370 * not be reconstructed later. For example, you will never store your 15371 * current position on screen because that will be computed again when a 15372 * new instance of the view is placed in its view hierarchy. 15373 * <p> 15374 * Some examples of things you may store here: the current cursor position 15375 * in a text view (but usually not the text itself since that is stored in a 15376 * content provider or other persistent storage), the currently selected 15377 * item in a list view. 15378 * 15379 * @return Returns a Parcelable object containing the view's current dynamic 15380 * state, or null if there is nothing interesting to save. The 15381 * default implementation returns null. 15382 * @see #onRestoreInstanceState(android.os.Parcelable) 15383 * @see #saveHierarchyState(android.util.SparseArray) 15384 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15385 * @see #setSaveEnabled(boolean) 15386 */ 15387 @CallSuper 15388 protected Parcelable onSaveInstanceState() { 15389 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15390 if (mStartActivityRequestWho != null) { 15391 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15392 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15393 return state; 15394 } 15395 return BaseSavedState.EMPTY_STATE; 15396 } 15397 15398 /** 15399 * Restore this view hierarchy's frozen state from the given container. 15400 * 15401 * @param container The SparseArray which holds previously frozen states. 15402 * 15403 * @see #saveHierarchyState(android.util.SparseArray) 15404 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15405 * @see #onRestoreInstanceState(android.os.Parcelable) 15406 */ 15407 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15408 dispatchRestoreInstanceState(container); 15409 } 15410 15411 /** 15412 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15413 * state for this view and its children. May be overridden to modify how restoring 15414 * happens to a view's children; for example, some views may want to not store state 15415 * for their children. 15416 * 15417 * @param container The SparseArray which holds previously saved state. 15418 * 15419 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15420 * @see #restoreHierarchyState(android.util.SparseArray) 15421 * @see #onRestoreInstanceState(android.os.Parcelable) 15422 */ 15423 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15424 if (mID != NO_ID) { 15425 Parcelable state = container.get(mID); 15426 if (state != null) { 15427 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15428 // + ": " + state); 15429 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15430 onRestoreInstanceState(state); 15431 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15432 throw new IllegalStateException( 15433 "Derived class did not call super.onRestoreInstanceState()"); 15434 } 15435 } 15436 } 15437 } 15438 15439 /** 15440 * Hook allowing a view to re-apply a representation of its internal state that had previously 15441 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15442 * null state. 15443 * 15444 * @param state The frozen state that had previously been returned by 15445 * {@link #onSaveInstanceState}. 15446 * 15447 * @see #onSaveInstanceState() 15448 * @see #restoreHierarchyState(android.util.SparseArray) 15449 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15450 */ 15451 @CallSuper 15452 protected void onRestoreInstanceState(Parcelable state) { 15453 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15454 if (state != null && !(state instanceof AbsSavedState)) { 15455 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15456 + "received " + state.getClass().toString() + " instead. This usually happens " 15457 + "when two views of different type have the same id in the same hierarchy. " 15458 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15459 + "other views do not use the same id."); 15460 } 15461 if (state != null && state instanceof BaseSavedState) { 15462 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15463 } 15464 } 15465 15466 /** 15467 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15468 * 15469 * @return the drawing start time in milliseconds 15470 */ 15471 public long getDrawingTime() { 15472 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15473 } 15474 15475 /** 15476 * <p>Enables or disables the duplication of the parent's state into this view. When 15477 * duplication is enabled, this view gets its drawable state from its parent rather 15478 * than from its own internal properties.</p> 15479 * 15480 * <p>Note: in the current implementation, setting this property to true after the 15481 * view was added to a ViewGroup might have no effect at all. This property should 15482 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15483 * 15484 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15485 * property is enabled, an exception will be thrown.</p> 15486 * 15487 * <p>Note: if the child view uses and updates additional states which are unknown to the 15488 * parent, these states should not be affected by this method.</p> 15489 * 15490 * @param enabled True to enable duplication of the parent's drawable state, false 15491 * to disable it. 15492 * 15493 * @see #getDrawableState() 15494 * @see #isDuplicateParentStateEnabled() 15495 */ 15496 public void setDuplicateParentStateEnabled(boolean enabled) { 15497 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15498 } 15499 15500 /** 15501 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15502 * 15503 * @return True if this view's drawable state is duplicated from the parent, 15504 * false otherwise 15505 * 15506 * @see #getDrawableState() 15507 * @see #setDuplicateParentStateEnabled(boolean) 15508 */ 15509 public boolean isDuplicateParentStateEnabled() { 15510 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15511 } 15512 15513 /** 15514 * <p>Specifies the type of layer backing this view. The layer can be 15515 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15516 * {@link #LAYER_TYPE_HARDWARE}.</p> 15517 * 15518 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15519 * instance that controls how the layer is composed on screen. The following 15520 * properties of the paint are taken into account when composing the layer:</p> 15521 * <ul> 15522 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15523 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15524 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15525 * </ul> 15526 * 15527 * <p>If this view has an alpha value set to < 1.0 by calling 15528 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15529 * by this view's alpha value.</p> 15530 * 15531 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15532 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15533 * for more information on when and how to use layers.</p> 15534 * 15535 * @param layerType The type of layer to use with this view, must be one of 15536 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15537 * {@link #LAYER_TYPE_HARDWARE} 15538 * @param paint The paint used to compose the layer. This argument is optional 15539 * and can be null. It is ignored when the layer type is 15540 * {@link #LAYER_TYPE_NONE} 15541 * 15542 * @see #getLayerType() 15543 * @see #LAYER_TYPE_NONE 15544 * @see #LAYER_TYPE_SOFTWARE 15545 * @see #LAYER_TYPE_HARDWARE 15546 * @see #setAlpha(float) 15547 * 15548 * @attr ref android.R.styleable#View_layerType 15549 */ 15550 public void setLayerType(int layerType, Paint paint) { 15551 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15552 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15553 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15554 } 15555 15556 boolean typeChanged = mRenderNode.setLayerType(layerType); 15557 15558 if (!typeChanged) { 15559 setLayerPaint(paint); 15560 return; 15561 } 15562 15563 // Destroy any previous software drawing cache if needed 15564 if (mLayerType == LAYER_TYPE_SOFTWARE) { 15565 destroyDrawingCache(); 15566 } 15567 15568 mLayerType = layerType; 15569 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 15570 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 15571 mRenderNode.setLayerPaint(mLayerPaint); 15572 15573 // draw() behaves differently if we are on a layer, so we need to 15574 // invalidate() here 15575 invalidateParentCaches(); 15576 invalidate(true); 15577 } 15578 15579 /** 15580 * Updates the {@link Paint} object used with the current layer (used only if the current 15581 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15582 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15583 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15584 * ensure that the view gets redrawn immediately. 15585 * 15586 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15587 * instance that controls how the layer is composed on screen. The following 15588 * properties of the paint are taken into account when composing the layer:</p> 15589 * <ul> 15590 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15591 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15592 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15593 * </ul> 15594 * 15595 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15596 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15597 * 15598 * @param paint The paint used to compose the layer. This argument is optional 15599 * and can be null. It is ignored when the layer type is 15600 * {@link #LAYER_TYPE_NONE} 15601 * 15602 * @see #setLayerType(int, android.graphics.Paint) 15603 */ 15604 public void setLayerPaint(Paint paint) { 15605 int layerType = getLayerType(); 15606 if (layerType != LAYER_TYPE_NONE) { 15607 mLayerPaint = paint == null ? new Paint() : paint; 15608 if (layerType == LAYER_TYPE_HARDWARE) { 15609 if (mRenderNode.setLayerPaint(mLayerPaint)) { 15610 invalidateViewProperty(false, false); 15611 } 15612 } else { 15613 invalidate(); 15614 } 15615 } 15616 } 15617 15618 /** 15619 * Indicates what type of layer is currently associated with this view. By default 15620 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15621 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15622 * for more information on the different types of layers. 15623 * 15624 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15625 * {@link #LAYER_TYPE_HARDWARE} 15626 * 15627 * @see #setLayerType(int, android.graphics.Paint) 15628 * @see #buildLayer() 15629 * @see #LAYER_TYPE_NONE 15630 * @see #LAYER_TYPE_SOFTWARE 15631 * @see #LAYER_TYPE_HARDWARE 15632 */ 15633 public int getLayerType() { 15634 return mLayerType; 15635 } 15636 15637 /** 15638 * Forces this view's layer to be created and this view to be rendered 15639 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15640 * invoking this method will have no effect. 15641 * 15642 * This method can for instance be used to render a view into its layer before 15643 * starting an animation. If this view is complex, rendering into the layer 15644 * before starting the animation will avoid skipping frames. 15645 * 15646 * @throws IllegalStateException If this view is not attached to a window 15647 * 15648 * @see #setLayerType(int, android.graphics.Paint) 15649 */ 15650 public void buildLayer() { 15651 if (mLayerType == LAYER_TYPE_NONE) return; 15652 15653 final AttachInfo attachInfo = mAttachInfo; 15654 if (attachInfo == null) { 15655 throw new IllegalStateException("This view must be attached to a window first"); 15656 } 15657 15658 if (getWidth() == 0 || getHeight() == 0) { 15659 return; 15660 } 15661 15662 switch (mLayerType) { 15663 case LAYER_TYPE_HARDWARE: 15664 updateDisplayListIfDirty(); 15665 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 15666 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 15667 } 15668 break; 15669 case LAYER_TYPE_SOFTWARE: 15670 buildDrawingCache(true); 15671 break; 15672 } 15673 } 15674 15675 /** 15676 * Destroys all hardware rendering resources. This method is invoked 15677 * when the system needs to reclaim resources. Upon execution of this 15678 * method, you should free any OpenGL resources created by the view. 15679 * 15680 * Note: you <strong>must</strong> call 15681 * <code>super.destroyHardwareResources()</code> when overriding 15682 * this method. 15683 * 15684 * @hide 15685 */ 15686 @CallSuper 15687 protected void destroyHardwareResources() { 15688 // Although the Layer will be destroyed by RenderNode, we want to release 15689 // the staging display list, which is also a signal to RenderNode that it's 15690 // safe to free its copy of the display list as it knows that we will 15691 // push an updated DisplayList if we try to draw again 15692 resetDisplayList(); 15693 } 15694 15695 /** 15696 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 15697 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 15698 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 15699 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 15700 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 15701 * null.</p> 15702 * 15703 * <p>Enabling the drawing cache is similar to 15704 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 15705 * acceleration is turned off. When hardware acceleration is turned on, enabling the 15706 * drawing cache has no effect on rendering because the system uses a different mechanism 15707 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 15708 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 15709 * for information on how to enable software and hardware layers.</p> 15710 * 15711 * <p>This API can be used to manually generate 15712 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 15713 * {@link #getDrawingCache()}.</p> 15714 * 15715 * @param enabled true to enable the drawing cache, false otherwise 15716 * 15717 * @see #isDrawingCacheEnabled() 15718 * @see #getDrawingCache() 15719 * @see #buildDrawingCache() 15720 * @see #setLayerType(int, android.graphics.Paint) 15721 */ 15722 public void setDrawingCacheEnabled(boolean enabled) { 15723 mCachingFailed = false; 15724 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 15725 } 15726 15727 /** 15728 * <p>Indicates whether the drawing cache is enabled for this view.</p> 15729 * 15730 * @return true if the drawing cache is enabled 15731 * 15732 * @see #setDrawingCacheEnabled(boolean) 15733 * @see #getDrawingCache() 15734 */ 15735 @ViewDebug.ExportedProperty(category = "drawing") 15736 public boolean isDrawingCacheEnabled() { 15737 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 15738 } 15739 15740 /** 15741 * Debugging utility which recursively outputs the dirty state of a view and its 15742 * descendants. 15743 * 15744 * @hide 15745 */ 15746 @SuppressWarnings({"UnusedDeclaration"}) 15747 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 15748 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 15749 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 15750 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 15751 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 15752 if (clear) { 15753 mPrivateFlags &= clearMask; 15754 } 15755 if (this instanceof ViewGroup) { 15756 ViewGroup parent = (ViewGroup) this; 15757 final int count = parent.getChildCount(); 15758 for (int i = 0; i < count; i++) { 15759 final View child = parent.getChildAt(i); 15760 child.outputDirtyFlags(indent + " ", clear, clearMask); 15761 } 15762 } 15763 } 15764 15765 /** 15766 * This method is used by ViewGroup to cause its children to restore or recreate their 15767 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 15768 * to recreate its own display list, which would happen if it went through the normal 15769 * draw/dispatchDraw mechanisms. 15770 * 15771 * @hide 15772 */ 15773 protected void dispatchGetDisplayList() {} 15774 15775 /** 15776 * A view that is not attached or hardware accelerated cannot create a display list. 15777 * This method checks these conditions and returns the appropriate result. 15778 * 15779 * @return true if view has the ability to create a display list, false otherwise. 15780 * 15781 * @hide 15782 */ 15783 public boolean canHaveDisplayList() { 15784 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 15785 } 15786 15787 /** 15788 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 15789 * @hide 15790 */ 15791 @NonNull 15792 public RenderNode updateDisplayListIfDirty() { 15793 final RenderNode renderNode = mRenderNode; 15794 if (!canHaveDisplayList()) { 15795 // can't populate RenderNode, don't try 15796 return renderNode; 15797 } 15798 15799 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 15800 || !renderNode.isValid() 15801 || (mRecreateDisplayList)) { 15802 // Don't need to recreate the display list, just need to tell our 15803 // children to restore/recreate theirs 15804 if (renderNode.isValid() 15805 && !mRecreateDisplayList) { 15806 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15807 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15808 dispatchGetDisplayList(); 15809 15810 return renderNode; // no work needed 15811 } 15812 15813 // If we got here, we're recreating it. Mark it as such to ensure that 15814 // we copy in child display lists into ours in drawChild() 15815 mRecreateDisplayList = true; 15816 15817 int width = mRight - mLeft; 15818 int height = mBottom - mTop; 15819 int layerType = getLayerType(); 15820 15821 final DisplayListCanvas canvas = renderNode.start(width, height); 15822 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 15823 15824 try { 15825 if (layerType == LAYER_TYPE_SOFTWARE) { 15826 buildDrawingCache(true); 15827 Bitmap cache = getDrawingCache(true); 15828 if (cache != null) { 15829 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 15830 } 15831 } else { 15832 computeScroll(); 15833 15834 canvas.translate(-mScrollX, -mScrollY); 15835 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15836 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15837 15838 // Fast path for layouts with no backgrounds 15839 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15840 dispatchDraw(canvas); 15841 if (mOverlay != null && !mOverlay.isEmpty()) { 15842 mOverlay.getOverlayView().draw(canvas); 15843 } 15844 } else { 15845 draw(canvas); 15846 } 15847 } 15848 } finally { 15849 renderNode.end(canvas); 15850 setDisplayListProperties(renderNode); 15851 } 15852 } else { 15853 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15854 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15855 } 15856 return renderNode; 15857 } 15858 15859 private void resetDisplayList() { 15860 if (mRenderNode.isValid()) { 15861 mRenderNode.discardDisplayList(); 15862 } 15863 15864 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 15865 mBackgroundRenderNode.discardDisplayList(); 15866 } 15867 } 15868 15869 /** 15870 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 15871 * 15872 * @return A non-scaled bitmap representing this view or null if cache is disabled. 15873 * 15874 * @see #getDrawingCache(boolean) 15875 */ 15876 public Bitmap getDrawingCache() { 15877 return getDrawingCache(false); 15878 } 15879 15880 /** 15881 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 15882 * is null when caching is disabled. If caching is enabled and the cache is not ready, 15883 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 15884 * draw from the cache when the cache is enabled. To benefit from the cache, you must 15885 * request the drawing cache by calling this method and draw it on screen if the 15886 * returned bitmap is not null.</p> 15887 * 15888 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15889 * this method will create a bitmap of the same size as this view. Because this bitmap 15890 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15891 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15892 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15893 * size than the view. This implies that your application must be able to handle this 15894 * size.</p> 15895 * 15896 * @param autoScale Indicates whether the generated bitmap should be scaled based on 15897 * the current density of the screen when the application is in compatibility 15898 * mode. 15899 * 15900 * @return A bitmap representing this view or null if cache is disabled. 15901 * 15902 * @see #setDrawingCacheEnabled(boolean) 15903 * @see #isDrawingCacheEnabled() 15904 * @see #buildDrawingCache(boolean) 15905 * @see #destroyDrawingCache() 15906 */ 15907 public Bitmap getDrawingCache(boolean autoScale) { 15908 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 15909 return null; 15910 } 15911 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 15912 buildDrawingCache(autoScale); 15913 } 15914 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 15915 } 15916 15917 /** 15918 * <p>Frees the resources used by the drawing cache. If you call 15919 * {@link #buildDrawingCache()} manually without calling 15920 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15921 * should cleanup the cache with this method afterwards.</p> 15922 * 15923 * @see #setDrawingCacheEnabled(boolean) 15924 * @see #buildDrawingCache() 15925 * @see #getDrawingCache() 15926 */ 15927 public void destroyDrawingCache() { 15928 if (mDrawingCache != null) { 15929 mDrawingCache.recycle(); 15930 mDrawingCache = null; 15931 } 15932 if (mUnscaledDrawingCache != null) { 15933 mUnscaledDrawingCache.recycle(); 15934 mUnscaledDrawingCache = null; 15935 } 15936 } 15937 15938 /** 15939 * Setting a solid background color for the drawing cache's bitmaps will improve 15940 * performance and memory usage. Note, though that this should only be used if this 15941 * view will always be drawn on top of a solid color. 15942 * 15943 * @param color The background color to use for the drawing cache's bitmap 15944 * 15945 * @see #setDrawingCacheEnabled(boolean) 15946 * @see #buildDrawingCache() 15947 * @see #getDrawingCache() 15948 */ 15949 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 15950 if (color != mDrawingCacheBackgroundColor) { 15951 mDrawingCacheBackgroundColor = color; 15952 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 15953 } 15954 } 15955 15956 /** 15957 * @see #setDrawingCacheBackgroundColor(int) 15958 * 15959 * @return The background color to used for the drawing cache's bitmap 15960 */ 15961 @ColorInt 15962 public int getDrawingCacheBackgroundColor() { 15963 return mDrawingCacheBackgroundColor; 15964 } 15965 15966 /** 15967 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 15968 * 15969 * @see #buildDrawingCache(boolean) 15970 */ 15971 public void buildDrawingCache() { 15972 buildDrawingCache(false); 15973 } 15974 15975 /** 15976 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 15977 * 15978 * <p>If you call {@link #buildDrawingCache()} manually without calling 15979 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15980 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 15981 * 15982 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15983 * this method will create a bitmap of the same size as this view. Because this bitmap 15984 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15985 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15986 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15987 * size than the view. This implies that your application must be able to handle this 15988 * size.</p> 15989 * 15990 * <p>You should avoid calling this method when hardware acceleration is enabled. If 15991 * you do not need the drawing cache bitmap, calling this method will increase memory 15992 * usage and cause the view to be rendered in software once, thus negatively impacting 15993 * performance.</p> 15994 * 15995 * @see #getDrawingCache() 15996 * @see #destroyDrawingCache() 15997 */ 15998 public void buildDrawingCache(boolean autoScale) { 15999 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16000 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16001 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16002 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16003 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16004 } 16005 try { 16006 buildDrawingCacheImpl(autoScale); 16007 } finally { 16008 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16009 } 16010 } 16011 } 16012 16013 /** 16014 * private, internal implementation of buildDrawingCache, used to enable tracing 16015 */ 16016 private void buildDrawingCacheImpl(boolean autoScale) { 16017 mCachingFailed = false; 16018 16019 int width = mRight - mLeft; 16020 int height = mBottom - mTop; 16021 16022 final AttachInfo attachInfo = mAttachInfo; 16023 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16024 16025 if (autoScale && scalingRequired) { 16026 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16027 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16028 } 16029 16030 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16031 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16032 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16033 16034 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16035 final long drawingCacheSize = 16036 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16037 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16038 if (width > 0 && height > 0) { 16039 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16040 + " too large to fit into a software layer (or drawing cache), needs " 16041 + projectedBitmapSize + " bytes, only " 16042 + drawingCacheSize + " available"); 16043 } 16044 destroyDrawingCache(); 16045 mCachingFailed = true; 16046 return; 16047 } 16048 16049 boolean clear = true; 16050 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16051 16052 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16053 Bitmap.Config quality; 16054 if (!opaque) { 16055 // Never pick ARGB_4444 because it looks awful 16056 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16057 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16058 case DRAWING_CACHE_QUALITY_AUTO: 16059 case DRAWING_CACHE_QUALITY_LOW: 16060 case DRAWING_CACHE_QUALITY_HIGH: 16061 default: 16062 quality = Bitmap.Config.ARGB_8888; 16063 break; 16064 } 16065 } else { 16066 // Optimization for translucent windows 16067 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16068 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16069 } 16070 16071 // Try to cleanup memory 16072 if (bitmap != null) bitmap.recycle(); 16073 16074 try { 16075 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16076 width, height, quality); 16077 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16078 if (autoScale) { 16079 mDrawingCache = bitmap; 16080 } else { 16081 mUnscaledDrawingCache = bitmap; 16082 } 16083 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16084 } catch (OutOfMemoryError e) { 16085 // If there is not enough memory to create the bitmap cache, just 16086 // ignore the issue as bitmap caches are not required to draw the 16087 // view hierarchy 16088 if (autoScale) { 16089 mDrawingCache = null; 16090 } else { 16091 mUnscaledDrawingCache = null; 16092 } 16093 mCachingFailed = true; 16094 return; 16095 } 16096 16097 clear = drawingCacheBackgroundColor != 0; 16098 } 16099 16100 Canvas canvas; 16101 if (attachInfo != null) { 16102 canvas = attachInfo.mCanvas; 16103 if (canvas == null) { 16104 canvas = new Canvas(); 16105 } 16106 canvas.setBitmap(bitmap); 16107 // Temporarily clobber the cached Canvas in case one of our children 16108 // is also using a drawing cache. Without this, the children would 16109 // steal the canvas by attaching their own bitmap to it and bad, bad 16110 // thing would happen (invisible views, corrupted drawings, etc.) 16111 attachInfo.mCanvas = null; 16112 } else { 16113 // This case should hopefully never or seldom happen 16114 canvas = new Canvas(bitmap); 16115 } 16116 16117 if (clear) { 16118 bitmap.eraseColor(drawingCacheBackgroundColor); 16119 } 16120 16121 computeScroll(); 16122 final int restoreCount = canvas.save(); 16123 16124 if (autoScale && scalingRequired) { 16125 final float scale = attachInfo.mApplicationScale; 16126 canvas.scale(scale, scale); 16127 } 16128 16129 canvas.translate(-mScrollX, -mScrollY); 16130 16131 mPrivateFlags |= PFLAG_DRAWN; 16132 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16133 mLayerType != LAYER_TYPE_NONE) { 16134 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16135 } 16136 16137 // Fast path for layouts with no backgrounds 16138 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16139 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16140 dispatchDraw(canvas); 16141 if (mOverlay != null && !mOverlay.isEmpty()) { 16142 mOverlay.getOverlayView().draw(canvas); 16143 } 16144 } else { 16145 draw(canvas); 16146 } 16147 16148 canvas.restoreToCount(restoreCount); 16149 canvas.setBitmap(null); 16150 16151 if (attachInfo != null) { 16152 // Restore the cached Canvas for our siblings 16153 attachInfo.mCanvas = canvas; 16154 } 16155 } 16156 16157 /** 16158 * Create a snapshot of the view into a bitmap. We should probably make 16159 * some form of this public, but should think about the API. 16160 */ 16161 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16162 int width = mRight - mLeft; 16163 int height = mBottom - mTop; 16164 16165 final AttachInfo attachInfo = mAttachInfo; 16166 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16167 width = (int) ((width * scale) + 0.5f); 16168 height = (int) ((height * scale) + 0.5f); 16169 16170 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16171 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16172 if (bitmap == null) { 16173 throw new OutOfMemoryError(); 16174 } 16175 16176 Resources resources = getResources(); 16177 if (resources != null) { 16178 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16179 } 16180 16181 Canvas canvas; 16182 if (attachInfo != null) { 16183 canvas = attachInfo.mCanvas; 16184 if (canvas == null) { 16185 canvas = new Canvas(); 16186 } 16187 canvas.setBitmap(bitmap); 16188 // Temporarily clobber the cached Canvas in case one of our children 16189 // is also using a drawing cache. Without this, the children would 16190 // steal the canvas by attaching their own bitmap to it and bad, bad 16191 // things would happen (invisible views, corrupted drawings, etc.) 16192 attachInfo.mCanvas = null; 16193 } else { 16194 // This case should hopefully never or seldom happen 16195 canvas = new Canvas(bitmap); 16196 } 16197 16198 if ((backgroundColor & 0xff000000) != 0) { 16199 bitmap.eraseColor(backgroundColor); 16200 } 16201 16202 computeScroll(); 16203 final int restoreCount = canvas.save(); 16204 canvas.scale(scale, scale); 16205 canvas.translate(-mScrollX, -mScrollY); 16206 16207 // Temporarily remove the dirty mask 16208 int flags = mPrivateFlags; 16209 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16210 16211 // Fast path for layouts with no backgrounds 16212 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16213 dispatchDraw(canvas); 16214 if (mOverlay != null && !mOverlay.isEmpty()) { 16215 mOverlay.getOverlayView().draw(canvas); 16216 } 16217 } else { 16218 draw(canvas); 16219 } 16220 16221 mPrivateFlags = flags; 16222 16223 canvas.restoreToCount(restoreCount); 16224 canvas.setBitmap(null); 16225 16226 if (attachInfo != null) { 16227 // Restore the cached Canvas for our siblings 16228 attachInfo.mCanvas = canvas; 16229 } 16230 16231 return bitmap; 16232 } 16233 16234 /** 16235 * Indicates whether this View is currently in edit mode. A View is usually 16236 * in edit mode when displayed within a developer tool. For instance, if 16237 * this View is being drawn by a visual user interface builder, this method 16238 * should return true. 16239 * 16240 * Subclasses should check the return value of this method to provide 16241 * different behaviors if their normal behavior might interfere with the 16242 * host environment. For instance: the class spawns a thread in its 16243 * constructor, the drawing code relies on device-specific features, etc. 16244 * 16245 * This method is usually checked in the drawing code of custom widgets. 16246 * 16247 * @return True if this View is in edit mode, false otherwise. 16248 */ 16249 public boolean isInEditMode() { 16250 return false; 16251 } 16252 16253 /** 16254 * If the View draws content inside its padding and enables fading edges, 16255 * it needs to support padding offsets. Padding offsets are added to the 16256 * fading edges to extend the length of the fade so that it covers pixels 16257 * drawn inside the padding. 16258 * 16259 * Subclasses of this class should override this method if they need 16260 * to draw content inside the padding. 16261 * 16262 * @return True if padding offset must be applied, false otherwise. 16263 * 16264 * @see #getLeftPaddingOffset() 16265 * @see #getRightPaddingOffset() 16266 * @see #getTopPaddingOffset() 16267 * @see #getBottomPaddingOffset() 16268 * 16269 * @since CURRENT 16270 */ 16271 protected boolean isPaddingOffsetRequired() { 16272 return false; 16273 } 16274 16275 /** 16276 * Amount by which to extend the left fading region. Called only when 16277 * {@link #isPaddingOffsetRequired()} returns true. 16278 * 16279 * @return The left padding offset in pixels. 16280 * 16281 * @see #isPaddingOffsetRequired() 16282 * 16283 * @since CURRENT 16284 */ 16285 protected int getLeftPaddingOffset() { 16286 return 0; 16287 } 16288 16289 /** 16290 * Amount by which to extend the right fading region. Called only when 16291 * {@link #isPaddingOffsetRequired()} returns true. 16292 * 16293 * @return The right padding offset in pixels. 16294 * 16295 * @see #isPaddingOffsetRequired() 16296 * 16297 * @since CURRENT 16298 */ 16299 protected int getRightPaddingOffset() { 16300 return 0; 16301 } 16302 16303 /** 16304 * Amount by which to extend the top fading region. Called only when 16305 * {@link #isPaddingOffsetRequired()} returns true. 16306 * 16307 * @return The top padding offset in pixels. 16308 * 16309 * @see #isPaddingOffsetRequired() 16310 * 16311 * @since CURRENT 16312 */ 16313 protected int getTopPaddingOffset() { 16314 return 0; 16315 } 16316 16317 /** 16318 * Amount by which to extend the bottom fading region. Called only when 16319 * {@link #isPaddingOffsetRequired()} returns true. 16320 * 16321 * @return The bottom padding offset in pixels. 16322 * 16323 * @see #isPaddingOffsetRequired() 16324 * 16325 * @since CURRENT 16326 */ 16327 protected int getBottomPaddingOffset() { 16328 return 0; 16329 } 16330 16331 /** 16332 * @hide 16333 * @param offsetRequired 16334 */ 16335 protected int getFadeTop(boolean offsetRequired) { 16336 int top = mPaddingTop; 16337 if (offsetRequired) top += getTopPaddingOffset(); 16338 return top; 16339 } 16340 16341 /** 16342 * @hide 16343 * @param offsetRequired 16344 */ 16345 protected int getFadeHeight(boolean offsetRequired) { 16346 int padding = mPaddingTop; 16347 if (offsetRequired) padding += getTopPaddingOffset(); 16348 return mBottom - mTop - mPaddingBottom - padding; 16349 } 16350 16351 /** 16352 * <p>Indicates whether this view is attached to a hardware accelerated 16353 * window or not.</p> 16354 * 16355 * <p>Even if this method returns true, it does not mean that every call 16356 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16357 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16358 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16359 * window is hardware accelerated, 16360 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16361 * return false, and this method will return true.</p> 16362 * 16363 * @return True if the view is attached to a window and the window is 16364 * hardware accelerated; false in any other case. 16365 */ 16366 @ViewDebug.ExportedProperty(category = "drawing") 16367 public boolean isHardwareAccelerated() { 16368 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16369 } 16370 16371 /** 16372 * Sets a rectangular area on this view to which the view will be clipped 16373 * when it is drawn. Setting the value to null will remove the clip bounds 16374 * and the view will draw normally, using its full bounds. 16375 * 16376 * @param clipBounds The rectangular area, in the local coordinates of 16377 * this view, to which future drawing operations will be clipped. 16378 */ 16379 public void setClipBounds(Rect clipBounds) { 16380 if (clipBounds == mClipBounds 16381 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16382 return; 16383 } 16384 if (clipBounds != null) { 16385 if (mClipBounds == null) { 16386 mClipBounds = new Rect(clipBounds); 16387 } else { 16388 mClipBounds.set(clipBounds); 16389 } 16390 } else { 16391 mClipBounds = null; 16392 } 16393 mRenderNode.setClipBounds(mClipBounds); 16394 invalidateViewProperty(false, false); 16395 } 16396 16397 /** 16398 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16399 * 16400 * @return A copy of the current clip bounds if clip bounds are set, 16401 * otherwise null. 16402 */ 16403 public Rect getClipBounds() { 16404 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16405 } 16406 16407 16408 /** 16409 * Populates an output rectangle with the clip bounds of the view, 16410 * returning {@code true} if successful or {@code false} if the view's 16411 * clip bounds are {@code null}. 16412 * 16413 * @param outRect rectangle in which to place the clip bounds of the view 16414 * @return {@code true} if successful or {@code false} if the view's 16415 * clip bounds are {@code null} 16416 */ 16417 public boolean getClipBounds(Rect outRect) { 16418 if (mClipBounds != null) { 16419 outRect.set(mClipBounds); 16420 return true; 16421 } 16422 return false; 16423 } 16424 16425 /** 16426 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16427 * case of an active Animation being run on the view. 16428 */ 16429 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16430 Animation a, boolean scalingRequired) { 16431 Transformation invalidationTransform; 16432 final int flags = parent.mGroupFlags; 16433 final boolean initialized = a.isInitialized(); 16434 if (!initialized) { 16435 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16436 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16437 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16438 onAnimationStart(); 16439 } 16440 16441 final Transformation t = parent.getChildTransformation(); 16442 boolean more = a.getTransformation(drawingTime, t, 1f); 16443 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16444 if (parent.mInvalidationTransformation == null) { 16445 parent.mInvalidationTransformation = new Transformation(); 16446 } 16447 invalidationTransform = parent.mInvalidationTransformation; 16448 a.getTransformation(drawingTime, invalidationTransform, 1f); 16449 } else { 16450 invalidationTransform = t; 16451 } 16452 16453 if (more) { 16454 if (!a.willChangeBounds()) { 16455 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16456 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16457 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16458 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16459 // The child need to draw an animation, potentially offscreen, so 16460 // make sure we do not cancel invalidate requests 16461 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16462 parent.invalidate(mLeft, mTop, mRight, mBottom); 16463 } 16464 } else { 16465 if (parent.mInvalidateRegion == null) { 16466 parent.mInvalidateRegion = new RectF(); 16467 } 16468 final RectF region = parent.mInvalidateRegion; 16469 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16470 invalidationTransform); 16471 16472 // The child need to draw an animation, potentially offscreen, so 16473 // make sure we do not cancel invalidate requests 16474 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16475 16476 final int left = mLeft + (int) region.left; 16477 final int top = mTop + (int) region.top; 16478 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16479 top + (int) (region.height() + .5f)); 16480 } 16481 } 16482 return more; 16483 } 16484 16485 /** 16486 * This method is called by getDisplayList() when a display list is recorded for a View. 16487 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16488 */ 16489 void setDisplayListProperties(RenderNode renderNode) { 16490 if (renderNode != null) { 16491 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 16492 renderNode.setClipToBounds(mParent instanceof ViewGroup 16493 && ((ViewGroup) mParent).getClipChildren()); 16494 16495 float alpha = 1; 16496 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16497 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16498 ViewGroup parentVG = (ViewGroup) mParent; 16499 final Transformation t = parentVG.getChildTransformation(); 16500 if (parentVG.getChildStaticTransformation(this, t)) { 16501 final int transformType = t.getTransformationType(); 16502 if (transformType != Transformation.TYPE_IDENTITY) { 16503 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16504 alpha = t.getAlpha(); 16505 } 16506 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16507 renderNode.setStaticMatrix(t.getMatrix()); 16508 } 16509 } 16510 } 16511 } 16512 if (mTransformationInfo != null) { 16513 alpha *= getFinalAlpha(); 16514 if (alpha < 1) { 16515 final int multipliedAlpha = (int) (255 * alpha); 16516 if (onSetAlpha(multipliedAlpha)) { 16517 alpha = 1; 16518 } 16519 } 16520 renderNode.setAlpha(alpha); 16521 } else if (alpha < 1) { 16522 renderNode.setAlpha(alpha); 16523 } 16524 } 16525 } 16526 16527 /** 16528 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16529 * 16530 * This is where the View specializes rendering behavior based on layer type, 16531 * and hardware acceleration. 16532 */ 16533 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16534 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16535 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16536 * 16537 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16538 * HW accelerated, it can't handle drawing RenderNodes. 16539 */ 16540 boolean drawingWithRenderNode = mAttachInfo != null 16541 && mAttachInfo.mHardwareAccelerated 16542 && hardwareAcceleratedCanvas; 16543 16544 boolean more = false; 16545 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16546 final int parentFlags = parent.mGroupFlags; 16547 16548 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16549 parent.getChildTransformation().clear(); 16550 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16551 } 16552 16553 Transformation transformToApply = null; 16554 boolean concatMatrix = false; 16555 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16556 final Animation a = getAnimation(); 16557 if (a != null) { 16558 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16559 concatMatrix = a.willChangeTransformationMatrix(); 16560 if (concatMatrix) { 16561 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16562 } 16563 transformToApply = parent.getChildTransformation(); 16564 } else { 16565 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16566 // No longer animating: clear out old animation matrix 16567 mRenderNode.setAnimationMatrix(null); 16568 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16569 } 16570 if (!drawingWithRenderNode 16571 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16572 final Transformation t = parent.getChildTransformation(); 16573 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16574 if (hasTransform) { 16575 final int transformType = t.getTransformationType(); 16576 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16577 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16578 } 16579 } 16580 } 16581 16582 concatMatrix |= !childHasIdentityMatrix; 16583 16584 // Sets the flag as early as possible to allow draw() implementations 16585 // to call invalidate() successfully when doing animations 16586 mPrivateFlags |= PFLAG_DRAWN; 16587 16588 if (!concatMatrix && 16589 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16590 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16591 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16592 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16593 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16594 return more; 16595 } 16596 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16597 16598 if (hardwareAcceleratedCanvas) { 16599 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16600 // retain the flag's value temporarily in the mRecreateDisplayList flag 16601 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16602 mPrivateFlags &= ~PFLAG_INVALIDATED; 16603 } 16604 16605 RenderNode renderNode = null; 16606 Bitmap cache = null; 16607 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16608 if (layerType == LAYER_TYPE_SOFTWARE 16609 || (!drawingWithRenderNode && layerType != LAYER_TYPE_NONE)) { 16610 // If not drawing with RenderNode, treat HW layers as SW 16611 layerType = LAYER_TYPE_SOFTWARE; 16612 buildDrawingCache(true); 16613 cache = getDrawingCache(true); 16614 } 16615 16616 if (drawingWithRenderNode) { 16617 // Delay getting the display list until animation-driven alpha values are 16618 // set up and possibly passed on to the view 16619 renderNode = updateDisplayListIfDirty(); 16620 if (!renderNode.isValid()) { 16621 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16622 // to getDisplayList(), the display list will be marked invalid and we should not 16623 // try to use it again. 16624 renderNode = null; 16625 drawingWithRenderNode = false; 16626 } 16627 } 16628 16629 int sx = 0; 16630 int sy = 0; 16631 if (!drawingWithRenderNode) { 16632 computeScroll(); 16633 sx = mScrollX; 16634 sy = mScrollY; 16635 } 16636 16637 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16638 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16639 16640 int restoreTo = -1; 16641 if (!drawingWithRenderNode || transformToApply != null) { 16642 restoreTo = canvas.save(); 16643 } 16644 if (offsetForScroll) { 16645 canvas.translate(mLeft - sx, mTop - sy); 16646 } else { 16647 if (!drawingWithRenderNode) { 16648 canvas.translate(mLeft, mTop); 16649 } 16650 if (scalingRequired) { 16651 if (drawingWithRenderNode) { 16652 // TODO: Might not need this if we put everything inside the DL 16653 restoreTo = canvas.save(); 16654 } 16655 // mAttachInfo cannot be null, otherwise scalingRequired == false 16656 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16657 canvas.scale(scale, scale); 16658 } 16659 } 16660 16661 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16662 if (transformToApply != null 16663 || alpha < 1 16664 || !hasIdentityMatrix() 16665 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16666 if (transformToApply != null || !childHasIdentityMatrix) { 16667 int transX = 0; 16668 int transY = 0; 16669 16670 if (offsetForScroll) { 16671 transX = -sx; 16672 transY = -sy; 16673 } 16674 16675 if (transformToApply != null) { 16676 if (concatMatrix) { 16677 if (drawingWithRenderNode) { 16678 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 16679 } else { 16680 // Undo the scroll translation, apply the transformation matrix, 16681 // then redo the scroll translate to get the correct result. 16682 canvas.translate(-transX, -transY); 16683 canvas.concat(transformToApply.getMatrix()); 16684 canvas.translate(transX, transY); 16685 } 16686 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16687 } 16688 16689 float transformAlpha = transformToApply.getAlpha(); 16690 if (transformAlpha < 1) { 16691 alpha *= transformAlpha; 16692 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16693 } 16694 } 16695 16696 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 16697 canvas.translate(-transX, -transY); 16698 canvas.concat(getMatrix()); 16699 canvas.translate(transX, transY); 16700 } 16701 } 16702 16703 // Deal with alpha if it is or used to be <1 16704 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16705 if (alpha < 1) { 16706 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16707 } else { 16708 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16709 } 16710 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16711 if (!drawingWithDrawingCache) { 16712 final int multipliedAlpha = (int) (255 * alpha); 16713 if (!onSetAlpha(multipliedAlpha)) { 16714 if (drawingWithRenderNode) { 16715 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 16716 } else if (layerType == LAYER_TYPE_NONE) { 16717 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 16718 multipliedAlpha); 16719 } 16720 } else { 16721 // Alpha is handled by the child directly, clobber the layer's alpha 16722 mPrivateFlags |= PFLAG_ALPHA_SET; 16723 } 16724 } 16725 } 16726 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16727 onSetAlpha(255); 16728 mPrivateFlags &= ~PFLAG_ALPHA_SET; 16729 } 16730 16731 if (!drawingWithRenderNode) { 16732 // apply clips directly, since RenderNode won't do it for this draw 16733 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 16734 if (offsetForScroll) { 16735 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 16736 } else { 16737 if (!scalingRequired || cache == null) { 16738 canvas.clipRect(0, 0, getWidth(), getHeight()); 16739 } else { 16740 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 16741 } 16742 } 16743 } 16744 16745 if (mClipBounds != null) { 16746 // clip bounds ignore scroll 16747 canvas.clipRect(mClipBounds); 16748 } 16749 } 16750 16751 if (!drawingWithDrawingCache) { 16752 if (drawingWithRenderNode) { 16753 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16754 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16755 } else { 16756 // Fast path for layouts with no backgrounds 16757 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16758 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16759 dispatchDraw(canvas); 16760 } else { 16761 draw(canvas); 16762 } 16763 } 16764 } else if (cache != null) { 16765 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16766 if (layerType == LAYER_TYPE_NONE) { 16767 // no layer paint, use temporary paint to draw bitmap 16768 Paint cachePaint = parent.mCachePaint; 16769 if (cachePaint == null) { 16770 cachePaint = new Paint(); 16771 cachePaint.setDither(false); 16772 parent.mCachePaint = cachePaint; 16773 } 16774 cachePaint.setAlpha((int) (alpha * 255)); 16775 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 16776 } else { 16777 // use layer paint to draw the bitmap, merging the two alphas, but also restore 16778 int layerPaintAlpha = mLayerPaint.getAlpha(); 16779 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 16780 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 16781 mLayerPaint.setAlpha(layerPaintAlpha); 16782 } 16783 } 16784 16785 if (restoreTo >= 0) { 16786 canvas.restoreToCount(restoreTo); 16787 } 16788 16789 if (a != null && !more) { 16790 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 16791 onSetAlpha(255); 16792 } 16793 parent.finishAnimatingView(this, a); 16794 } 16795 16796 if (more && hardwareAcceleratedCanvas) { 16797 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16798 // alpha animations should cause the child to recreate its display list 16799 invalidate(true); 16800 } 16801 } 16802 16803 mRecreateDisplayList = false; 16804 16805 return more; 16806 } 16807 16808 /** 16809 * Manually render this view (and all of its children) to the given Canvas. 16810 * The view must have already done a full layout before this function is 16811 * called. When implementing a view, implement 16812 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 16813 * If you do need to override this method, call the superclass version. 16814 * 16815 * @param canvas The Canvas to which the View is rendered. 16816 */ 16817 @CallSuper 16818 public void draw(Canvas canvas) { 16819 final int privateFlags = mPrivateFlags; 16820 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 16821 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 16822 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 16823 16824 /* 16825 * Draw traversal performs several drawing steps which must be executed 16826 * in the appropriate order: 16827 * 16828 * 1. Draw the background 16829 * 2. If necessary, save the canvas' layers to prepare for fading 16830 * 3. Draw view's content 16831 * 4. Draw children 16832 * 5. If necessary, draw the fading edges and restore layers 16833 * 6. Draw decorations (scrollbars for instance) 16834 */ 16835 16836 // Step 1, draw the background, if needed 16837 int saveCount; 16838 16839 if (!dirtyOpaque) { 16840 drawBackground(canvas); 16841 } 16842 16843 // skip step 2 & 5 if possible (common case) 16844 final int viewFlags = mViewFlags; 16845 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 16846 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 16847 if (!verticalEdges && !horizontalEdges) { 16848 // Step 3, draw the content 16849 if (!dirtyOpaque) onDraw(canvas); 16850 16851 // Step 4, draw the children 16852 dispatchDraw(canvas); 16853 16854 // Overlay is part of the content and draws beneath Foreground 16855 if (mOverlay != null && !mOverlay.isEmpty()) { 16856 mOverlay.getOverlayView().dispatchDraw(canvas); 16857 } 16858 16859 // Step 6, draw decorations (foreground, scrollbars) 16860 onDrawForeground(canvas); 16861 16862 // we're done... 16863 return; 16864 } 16865 16866 /* 16867 * Here we do the full fledged routine... 16868 * (this is an uncommon case where speed matters less, 16869 * this is why we repeat some of the tests that have been 16870 * done above) 16871 */ 16872 16873 boolean drawTop = false; 16874 boolean drawBottom = false; 16875 boolean drawLeft = false; 16876 boolean drawRight = false; 16877 16878 float topFadeStrength = 0.0f; 16879 float bottomFadeStrength = 0.0f; 16880 float leftFadeStrength = 0.0f; 16881 float rightFadeStrength = 0.0f; 16882 16883 // Step 2, save the canvas' layers 16884 int paddingLeft = mPaddingLeft; 16885 16886 final boolean offsetRequired = isPaddingOffsetRequired(); 16887 if (offsetRequired) { 16888 paddingLeft += getLeftPaddingOffset(); 16889 } 16890 16891 int left = mScrollX + paddingLeft; 16892 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 16893 int top = mScrollY + getFadeTop(offsetRequired); 16894 int bottom = top + getFadeHeight(offsetRequired); 16895 16896 if (offsetRequired) { 16897 right += getRightPaddingOffset(); 16898 bottom += getBottomPaddingOffset(); 16899 } 16900 16901 final ScrollabilityCache scrollabilityCache = mScrollCache; 16902 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 16903 int length = (int) fadeHeight; 16904 16905 // clip the fade length if top and bottom fades overlap 16906 // overlapping fades produce odd-looking artifacts 16907 if (verticalEdges && (top + length > bottom - length)) { 16908 length = (bottom - top) / 2; 16909 } 16910 16911 // also clip horizontal fades if necessary 16912 if (horizontalEdges && (left + length > right - length)) { 16913 length = (right - left) / 2; 16914 } 16915 16916 if (verticalEdges) { 16917 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 16918 drawTop = topFadeStrength * fadeHeight > 1.0f; 16919 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 16920 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 16921 } 16922 16923 if (horizontalEdges) { 16924 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 16925 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 16926 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 16927 drawRight = rightFadeStrength * fadeHeight > 1.0f; 16928 } 16929 16930 saveCount = canvas.getSaveCount(); 16931 16932 int solidColor = getSolidColor(); 16933 if (solidColor == 0) { 16934 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 16935 16936 if (drawTop) { 16937 canvas.saveLayer(left, top, right, top + length, null, flags); 16938 } 16939 16940 if (drawBottom) { 16941 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 16942 } 16943 16944 if (drawLeft) { 16945 canvas.saveLayer(left, top, left + length, bottom, null, flags); 16946 } 16947 16948 if (drawRight) { 16949 canvas.saveLayer(right - length, top, right, bottom, null, flags); 16950 } 16951 } else { 16952 scrollabilityCache.setFadeColor(solidColor); 16953 } 16954 16955 // Step 3, draw the content 16956 if (!dirtyOpaque) onDraw(canvas); 16957 16958 // Step 4, draw the children 16959 dispatchDraw(canvas); 16960 16961 // Step 5, draw the fade effect and restore layers 16962 final Paint p = scrollabilityCache.paint; 16963 final Matrix matrix = scrollabilityCache.matrix; 16964 final Shader fade = scrollabilityCache.shader; 16965 16966 if (drawTop) { 16967 matrix.setScale(1, fadeHeight * topFadeStrength); 16968 matrix.postTranslate(left, top); 16969 fade.setLocalMatrix(matrix); 16970 p.setShader(fade); 16971 canvas.drawRect(left, top, right, top + length, p); 16972 } 16973 16974 if (drawBottom) { 16975 matrix.setScale(1, fadeHeight * bottomFadeStrength); 16976 matrix.postRotate(180); 16977 matrix.postTranslate(left, bottom); 16978 fade.setLocalMatrix(matrix); 16979 p.setShader(fade); 16980 canvas.drawRect(left, bottom - length, right, bottom, p); 16981 } 16982 16983 if (drawLeft) { 16984 matrix.setScale(1, fadeHeight * leftFadeStrength); 16985 matrix.postRotate(-90); 16986 matrix.postTranslate(left, top); 16987 fade.setLocalMatrix(matrix); 16988 p.setShader(fade); 16989 canvas.drawRect(left, top, left + length, bottom, p); 16990 } 16991 16992 if (drawRight) { 16993 matrix.setScale(1, fadeHeight * rightFadeStrength); 16994 matrix.postRotate(90); 16995 matrix.postTranslate(right, top); 16996 fade.setLocalMatrix(matrix); 16997 p.setShader(fade); 16998 canvas.drawRect(right - length, top, right, bottom, p); 16999 } 17000 17001 canvas.restoreToCount(saveCount); 17002 17003 // Overlay is part of the content and draws beneath Foreground 17004 if (mOverlay != null && !mOverlay.isEmpty()) { 17005 mOverlay.getOverlayView().dispatchDraw(canvas); 17006 } 17007 17008 // Step 6, draw decorations (foreground, scrollbars) 17009 onDrawForeground(canvas); 17010 } 17011 17012 /** 17013 * Draws the background onto the specified canvas. 17014 * 17015 * @param canvas Canvas on which to draw the background 17016 */ 17017 private void drawBackground(Canvas canvas) { 17018 final Drawable background = mBackground; 17019 if (background == null) { 17020 return; 17021 } 17022 17023 setBackgroundBounds(); 17024 17025 // Attempt to use a display list if requested. 17026 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17027 && mAttachInfo.mHardwareRenderer != null) { 17028 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17029 17030 final RenderNode renderNode = mBackgroundRenderNode; 17031 if (renderNode != null && renderNode.isValid()) { 17032 setBackgroundRenderNodeProperties(renderNode); 17033 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17034 return; 17035 } 17036 } 17037 17038 final int scrollX = mScrollX; 17039 final int scrollY = mScrollY; 17040 if ((scrollX | scrollY) == 0) { 17041 background.draw(canvas); 17042 } else { 17043 canvas.translate(scrollX, scrollY); 17044 background.draw(canvas); 17045 canvas.translate(-scrollX, -scrollY); 17046 } 17047 } 17048 17049 /** 17050 * Sets the correct background bounds and rebuilds the outline, if needed. 17051 * <p/> 17052 * This is called by LayoutLib. 17053 */ 17054 void setBackgroundBounds() { 17055 if (mBackgroundSizeChanged && mBackground != null) { 17056 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17057 mBackgroundSizeChanged = false; 17058 rebuildOutline(); 17059 } 17060 } 17061 17062 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17063 renderNode.setTranslationX(mScrollX); 17064 renderNode.setTranslationY(mScrollY); 17065 } 17066 17067 /** 17068 * Creates a new display list or updates the existing display list for the 17069 * specified Drawable. 17070 * 17071 * @param drawable Drawable for which to create a display list 17072 * @param renderNode Existing RenderNode, or {@code null} 17073 * @return A valid display list for the specified drawable 17074 */ 17075 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17076 if (renderNode == null) { 17077 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17078 } 17079 17080 final Rect bounds = drawable.getBounds(); 17081 final int width = bounds.width(); 17082 final int height = bounds.height(); 17083 final DisplayListCanvas canvas = renderNode.start(width, height); 17084 17085 // Reverse left/top translation done by drawable canvas, which will 17086 // instead be applied by rendernode's LTRB bounds below. This way, the 17087 // drawable's bounds match with its rendernode bounds and its content 17088 // will lie within those bounds in the rendernode tree. 17089 canvas.translate(-bounds.left, -bounds.top); 17090 17091 try { 17092 drawable.draw(canvas); 17093 } finally { 17094 renderNode.end(canvas); 17095 } 17096 17097 // Set up drawable properties that are view-independent. 17098 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17099 renderNode.setProjectBackwards(drawable.isProjected()); 17100 renderNode.setProjectionReceiver(true); 17101 renderNode.setClipToBounds(false); 17102 return renderNode; 17103 } 17104 17105 /** 17106 * Returns the overlay for this view, creating it if it does not yet exist. 17107 * Adding drawables to the overlay will cause them to be displayed whenever 17108 * the view itself is redrawn. Objects in the overlay should be actively 17109 * managed: remove them when they should not be displayed anymore. The 17110 * overlay will always have the same size as its host view. 17111 * 17112 * <p>Note: Overlays do not currently work correctly with {@link 17113 * SurfaceView} or {@link TextureView}; contents in overlays for these 17114 * types of views may not display correctly.</p> 17115 * 17116 * @return The ViewOverlay object for this view. 17117 * @see ViewOverlay 17118 */ 17119 public ViewOverlay getOverlay() { 17120 if (mOverlay == null) { 17121 mOverlay = new ViewOverlay(mContext, this); 17122 } 17123 return mOverlay; 17124 } 17125 17126 /** 17127 * Override this if your view is known to always be drawn on top of a solid color background, 17128 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17129 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17130 * should be set to 0xFF. 17131 * 17132 * @see #setVerticalFadingEdgeEnabled(boolean) 17133 * @see #setHorizontalFadingEdgeEnabled(boolean) 17134 * 17135 * @return The known solid color background for this view, or 0 if the color may vary 17136 */ 17137 @ViewDebug.ExportedProperty(category = "drawing") 17138 @ColorInt 17139 public int getSolidColor() { 17140 return 0; 17141 } 17142 17143 /** 17144 * Build a human readable string representation of the specified view flags. 17145 * 17146 * @param flags the view flags to convert to a string 17147 * @return a String representing the supplied flags 17148 */ 17149 private static String printFlags(int flags) { 17150 String output = ""; 17151 int numFlags = 0; 17152 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17153 output += "TAKES_FOCUS"; 17154 numFlags++; 17155 } 17156 17157 switch (flags & VISIBILITY_MASK) { 17158 case INVISIBLE: 17159 if (numFlags > 0) { 17160 output += " "; 17161 } 17162 output += "INVISIBLE"; 17163 // USELESS HERE numFlags++; 17164 break; 17165 case GONE: 17166 if (numFlags > 0) { 17167 output += " "; 17168 } 17169 output += "GONE"; 17170 // USELESS HERE numFlags++; 17171 break; 17172 default: 17173 break; 17174 } 17175 return output; 17176 } 17177 17178 /** 17179 * Build a human readable string representation of the specified private 17180 * view flags. 17181 * 17182 * @param privateFlags the private view flags to convert to a string 17183 * @return a String representing the supplied flags 17184 */ 17185 private static String printPrivateFlags(int privateFlags) { 17186 String output = ""; 17187 int numFlags = 0; 17188 17189 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17190 output += "WANTS_FOCUS"; 17191 numFlags++; 17192 } 17193 17194 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17195 if (numFlags > 0) { 17196 output += " "; 17197 } 17198 output += "FOCUSED"; 17199 numFlags++; 17200 } 17201 17202 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17203 if (numFlags > 0) { 17204 output += " "; 17205 } 17206 output += "SELECTED"; 17207 numFlags++; 17208 } 17209 17210 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17211 if (numFlags > 0) { 17212 output += " "; 17213 } 17214 output += "IS_ROOT_NAMESPACE"; 17215 numFlags++; 17216 } 17217 17218 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17219 if (numFlags > 0) { 17220 output += " "; 17221 } 17222 output += "HAS_BOUNDS"; 17223 numFlags++; 17224 } 17225 17226 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17227 if (numFlags > 0) { 17228 output += " "; 17229 } 17230 output += "DRAWN"; 17231 // USELESS HERE numFlags++; 17232 } 17233 return output; 17234 } 17235 17236 /** 17237 * <p>Indicates whether or not this view's layout will be requested during 17238 * the next hierarchy layout pass.</p> 17239 * 17240 * @return true if the layout will be forced during next layout pass 17241 */ 17242 public boolean isLayoutRequested() { 17243 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17244 } 17245 17246 /** 17247 * Return true if o is a ViewGroup that is laying out using optical bounds. 17248 * @hide 17249 */ 17250 public static boolean isLayoutModeOptical(Object o) { 17251 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17252 } 17253 17254 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17255 Insets parentInsets = mParent instanceof View ? 17256 ((View) mParent).getOpticalInsets() : Insets.NONE; 17257 Insets childInsets = getOpticalInsets(); 17258 return setFrame( 17259 left + parentInsets.left - childInsets.left, 17260 top + parentInsets.top - childInsets.top, 17261 right + parentInsets.left + childInsets.right, 17262 bottom + parentInsets.top + childInsets.bottom); 17263 } 17264 17265 /** 17266 * Assign a size and position to a view and all of its 17267 * descendants 17268 * 17269 * <p>This is the second phase of the layout mechanism. 17270 * (The first is measuring). In this phase, each parent calls 17271 * layout on all of its children to position them. 17272 * This is typically done using the child measurements 17273 * that were stored in the measure pass().</p> 17274 * 17275 * <p>Derived classes should not override this method. 17276 * Derived classes with children should override 17277 * onLayout. In that method, they should 17278 * call layout on each of their children.</p> 17279 * 17280 * @param l Left position, relative to parent 17281 * @param t Top position, relative to parent 17282 * @param r Right position, relative to parent 17283 * @param b Bottom position, relative to parent 17284 */ 17285 @SuppressWarnings({"unchecked"}) 17286 public void layout(int l, int t, int r, int b) { 17287 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17288 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17289 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17290 } 17291 17292 int oldL = mLeft; 17293 int oldT = mTop; 17294 int oldB = mBottom; 17295 int oldR = mRight; 17296 17297 boolean changed = isLayoutModeOptical(mParent) ? 17298 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17299 17300 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17301 onLayout(changed, l, t, r, b); 17302 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17303 17304 ListenerInfo li = mListenerInfo; 17305 if (li != null && li.mOnLayoutChangeListeners != null) { 17306 ArrayList<OnLayoutChangeListener> listenersCopy = 17307 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17308 int numListeners = listenersCopy.size(); 17309 for (int i = 0; i < numListeners; ++i) { 17310 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17311 } 17312 } 17313 } 17314 17315 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17316 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17317 } 17318 17319 /** 17320 * Called from layout when this view should 17321 * assign a size and position to each of its children. 17322 * 17323 * Derived classes with children should override 17324 * this method and call layout on each of 17325 * their children. 17326 * @param changed This is a new size or position for this view 17327 * @param left Left position, relative to parent 17328 * @param top Top position, relative to parent 17329 * @param right Right position, relative to parent 17330 * @param bottom Bottom position, relative to parent 17331 */ 17332 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17333 } 17334 17335 /** 17336 * Assign a size and position to this view. 17337 * 17338 * This is called from layout. 17339 * 17340 * @param left Left position, relative to parent 17341 * @param top Top position, relative to parent 17342 * @param right Right position, relative to parent 17343 * @param bottom Bottom position, relative to parent 17344 * @return true if the new size and position are different than the 17345 * previous ones 17346 * {@hide} 17347 */ 17348 protected boolean setFrame(int left, int top, int right, int bottom) { 17349 boolean changed = false; 17350 17351 if (DBG) { 17352 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17353 + right + "," + bottom + ")"); 17354 } 17355 17356 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17357 changed = true; 17358 17359 // Remember our drawn bit 17360 int drawn = mPrivateFlags & PFLAG_DRAWN; 17361 17362 int oldWidth = mRight - mLeft; 17363 int oldHeight = mBottom - mTop; 17364 int newWidth = right - left; 17365 int newHeight = bottom - top; 17366 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17367 17368 // Invalidate our old position 17369 invalidate(sizeChanged); 17370 17371 mLeft = left; 17372 mTop = top; 17373 mRight = right; 17374 mBottom = bottom; 17375 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17376 17377 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17378 17379 17380 if (sizeChanged) { 17381 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17382 } 17383 17384 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17385 // If we are visible, force the DRAWN bit to on so that 17386 // this invalidate will go through (at least to our parent). 17387 // This is because someone may have invalidated this view 17388 // before this call to setFrame came in, thereby clearing 17389 // the DRAWN bit. 17390 mPrivateFlags |= PFLAG_DRAWN; 17391 invalidate(sizeChanged); 17392 // parent display list may need to be recreated based on a change in the bounds 17393 // of any child 17394 invalidateParentCaches(); 17395 } 17396 17397 // Reset drawn bit to original value (invalidate turns it off) 17398 mPrivateFlags |= drawn; 17399 17400 mBackgroundSizeChanged = true; 17401 if (mForegroundInfo != null) { 17402 mForegroundInfo.mBoundsChanged = true; 17403 } 17404 17405 notifySubtreeAccessibilityStateChangedIfNeeded(); 17406 } 17407 return changed; 17408 } 17409 17410 /** 17411 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17412 * @hide 17413 */ 17414 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17415 setFrame(left, top, right, bottom); 17416 } 17417 17418 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17419 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17420 if (mOverlay != null) { 17421 mOverlay.getOverlayView().setRight(newWidth); 17422 mOverlay.getOverlayView().setBottom(newHeight); 17423 } 17424 rebuildOutline(); 17425 } 17426 17427 /** 17428 * Finalize inflating a view from XML. This is called as the last phase 17429 * of inflation, after all child views have been added. 17430 * 17431 * <p>Even if the subclass overrides onFinishInflate, they should always be 17432 * sure to call the super method, so that we get called. 17433 */ 17434 @CallSuper 17435 protected void onFinishInflate() { 17436 } 17437 17438 /** 17439 * Returns the resources associated with this view. 17440 * 17441 * @return Resources object. 17442 */ 17443 public Resources getResources() { 17444 return mResources; 17445 } 17446 17447 /** 17448 * Invalidates the specified Drawable. 17449 * 17450 * @param drawable the drawable to invalidate 17451 */ 17452 @Override 17453 public void invalidateDrawable(@NonNull Drawable drawable) { 17454 if (verifyDrawable(drawable)) { 17455 final Rect dirty = drawable.getDirtyBounds(); 17456 final int scrollX = mScrollX; 17457 final int scrollY = mScrollY; 17458 17459 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17460 dirty.right + scrollX, dirty.bottom + scrollY); 17461 rebuildOutline(); 17462 } 17463 } 17464 17465 /** 17466 * Schedules an action on a drawable to occur at a specified time. 17467 * 17468 * @param who the recipient of the action 17469 * @param what the action to run on the drawable 17470 * @param when the time at which the action must occur. Uses the 17471 * {@link SystemClock#uptimeMillis} timebase. 17472 */ 17473 @Override 17474 public void scheduleDrawable(Drawable who, Runnable what, long when) { 17475 if (verifyDrawable(who) && what != null) { 17476 final long delay = when - SystemClock.uptimeMillis(); 17477 if (mAttachInfo != null) { 17478 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17479 Choreographer.CALLBACK_ANIMATION, what, who, 17480 Choreographer.subtractFrameDelay(delay)); 17481 } else { 17482 // Postpone the runnable until we know 17483 // on which thread it needs to run. 17484 getRunQueue().postDelayed(what, delay); 17485 } 17486 } 17487 } 17488 17489 /** 17490 * Cancels a scheduled action on a drawable. 17491 * 17492 * @param who the recipient of the action 17493 * @param what the action to cancel 17494 */ 17495 @Override 17496 public void unscheduleDrawable(Drawable who, Runnable what) { 17497 if (verifyDrawable(who) && what != null) { 17498 if (mAttachInfo != null) { 17499 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17500 Choreographer.CALLBACK_ANIMATION, what, who); 17501 } 17502 getRunQueue().removeCallbacks(what); 17503 } 17504 } 17505 17506 /** 17507 * Unschedule any events associated with the given Drawable. This can be 17508 * used when selecting a new Drawable into a view, so that the previous 17509 * one is completely unscheduled. 17510 * 17511 * @param who The Drawable to unschedule. 17512 * 17513 * @see #drawableStateChanged 17514 */ 17515 public void unscheduleDrawable(Drawable who) { 17516 if (mAttachInfo != null && who != null) { 17517 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17518 Choreographer.CALLBACK_ANIMATION, null, who); 17519 } 17520 } 17521 17522 /** 17523 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17524 * that the View directionality can and will be resolved before its Drawables. 17525 * 17526 * Will call {@link View#onResolveDrawables} when resolution is done. 17527 * 17528 * @hide 17529 */ 17530 protected void resolveDrawables() { 17531 // Drawables resolution may need to happen before resolving the layout direction (which is 17532 // done only during the measure() call). 17533 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17534 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17535 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17536 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17537 // direction to be resolved as its resolved value will be the same as its raw value. 17538 if (!isLayoutDirectionResolved() && 17539 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17540 return; 17541 } 17542 17543 final int layoutDirection = isLayoutDirectionResolved() ? 17544 getLayoutDirection() : getRawLayoutDirection(); 17545 17546 if (mBackground != null) { 17547 mBackground.setLayoutDirection(layoutDirection); 17548 } 17549 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17550 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17551 } 17552 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17553 onResolveDrawables(layoutDirection); 17554 } 17555 17556 boolean areDrawablesResolved() { 17557 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17558 } 17559 17560 /** 17561 * Called when layout direction has been resolved. 17562 * 17563 * The default implementation does nothing. 17564 * 17565 * @param layoutDirection The resolved layout direction. 17566 * 17567 * @see #LAYOUT_DIRECTION_LTR 17568 * @see #LAYOUT_DIRECTION_RTL 17569 * 17570 * @hide 17571 */ 17572 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17573 } 17574 17575 /** 17576 * @hide 17577 */ 17578 protected void resetResolvedDrawables() { 17579 resetResolvedDrawablesInternal(); 17580 } 17581 17582 void resetResolvedDrawablesInternal() { 17583 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17584 } 17585 17586 /** 17587 * If your view subclass is displaying its own Drawable objects, it should 17588 * override this function and return true for any Drawable it is 17589 * displaying. This allows animations for those drawables to be 17590 * scheduled. 17591 * 17592 * <p>Be sure to call through to the super class when overriding this 17593 * function. 17594 * 17595 * @param who The Drawable to verify. Return true if it is one you are 17596 * displaying, else return the result of calling through to the 17597 * super class. 17598 * 17599 * @return boolean If true than the Drawable is being displayed in the 17600 * view; else false and it is not allowed to animate. 17601 * 17602 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17603 * @see #drawableStateChanged() 17604 */ 17605 @CallSuper 17606 protected boolean verifyDrawable(Drawable who) { 17607 // Avoid verifying the scroll bar drawable so that we don't end up in 17608 // an invalidation loop. This effectively prevents the scroll bar 17609 // drawable from triggering invalidations and scheduling runnables. 17610 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17611 } 17612 17613 /** 17614 * This function is called whenever the state of the view changes in such 17615 * a way that it impacts the state of drawables being shown. 17616 * <p> 17617 * If the View has a StateListAnimator, it will also be called to run necessary state 17618 * change animations. 17619 * <p> 17620 * Be sure to call through to the superclass when overriding this function. 17621 * 17622 * @see Drawable#setState(int[]) 17623 */ 17624 @CallSuper 17625 protected void drawableStateChanged() { 17626 final int[] state = getDrawableState(); 17627 boolean changed = false; 17628 17629 final Drawable bg = mBackground; 17630 if (bg != null && bg.isStateful()) { 17631 changed |= bg.setState(state); 17632 } 17633 17634 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17635 if (fg != null && fg.isStateful()) { 17636 changed |= fg.setState(state); 17637 } 17638 17639 if (mScrollCache != null) { 17640 final Drawable scrollBar = mScrollCache.scrollBar; 17641 if (scrollBar != null && scrollBar.isStateful()) { 17642 changed |= scrollBar.setState(state) 17643 && mScrollCache.state != ScrollabilityCache.OFF; 17644 } 17645 } 17646 17647 if (mStateListAnimator != null) { 17648 mStateListAnimator.setState(state); 17649 } 17650 17651 if (changed) { 17652 invalidate(); 17653 } 17654 } 17655 17656 /** 17657 * This function is called whenever the view hotspot changes and needs to 17658 * be propagated to drawables or child views managed by the view. 17659 * <p> 17660 * Dispatching to child views is handled by 17661 * {@link #dispatchDrawableHotspotChanged(float, float)}. 17662 * <p> 17663 * Be sure to call through to the superclass when overriding this function. 17664 * 17665 * @param x hotspot x coordinate 17666 * @param y hotspot y coordinate 17667 */ 17668 @CallSuper 17669 public void drawableHotspotChanged(float x, float y) { 17670 if (mBackground != null) { 17671 mBackground.setHotspot(x, y); 17672 } 17673 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17674 mForegroundInfo.mDrawable.setHotspot(x, y); 17675 } 17676 17677 dispatchDrawableHotspotChanged(x, y); 17678 } 17679 17680 /** 17681 * Dispatches drawableHotspotChanged to all of this View's children. 17682 * 17683 * @param x hotspot x coordinate 17684 * @param y hotspot y coordinate 17685 * @see #drawableHotspotChanged(float, float) 17686 */ 17687 public void dispatchDrawableHotspotChanged(float x, float y) { 17688 } 17689 17690 /** 17691 * Call this to force a view to update its drawable state. This will cause 17692 * drawableStateChanged to be called on this view. Views that are interested 17693 * in the new state should call getDrawableState. 17694 * 17695 * @see #drawableStateChanged 17696 * @see #getDrawableState 17697 */ 17698 public void refreshDrawableState() { 17699 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 17700 drawableStateChanged(); 17701 17702 ViewParent parent = mParent; 17703 if (parent != null) { 17704 parent.childDrawableStateChanged(this); 17705 } 17706 } 17707 17708 /** 17709 * Return an array of resource IDs of the drawable states representing the 17710 * current state of the view. 17711 * 17712 * @return The current drawable state 17713 * 17714 * @see Drawable#setState(int[]) 17715 * @see #drawableStateChanged() 17716 * @see #onCreateDrawableState(int) 17717 */ 17718 public final int[] getDrawableState() { 17719 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 17720 return mDrawableState; 17721 } else { 17722 mDrawableState = onCreateDrawableState(0); 17723 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 17724 return mDrawableState; 17725 } 17726 } 17727 17728 /** 17729 * Generate the new {@link android.graphics.drawable.Drawable} state for 17730 * this view. This is called by the view 17731 * system when the cached Drawable state is determined to be invalid. To 17732 * retrieve the current state, you should use {@link #getDrawableState}. 17733 * 17734 * @param extraSpace if non-zero, this is the number of extra entries you 17735 * would like in the returned array in which you can place your own 17736 * states. 17737 * 17738 * @return Returns an array holding the current {@link Drawable} state of 17739 * the view. 17740 * 17741 * @see #mergeDrawableStates(int[], int[]) 17742 */ 17743 protected int[] onCreateDrawableState(int extraSpace) { 17744 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 17745 mParent instanceof View) { 17746 return ((View) mParent).onCreateDrawableState(extraSpace); 17747 } 17748 17749 int[] drawableState; 17750 17751 int privateFlags = mPrivateFlags; 17752 17753 int viewStateIndex = 0; 17754 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 17755 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 17756 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 17757 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 17758 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 17759 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 17760 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 17761 ThreadedRenderer.isAvailable()) { 17762 // This is set if HW acceleration is requested, even if the current 17763 // process doesn't allow it. This is just to allow app preview 17764 // windows to better match their app. 17765 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 17766 } 17767 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 17768 17769 final int privateFlags2 = mPrivateFlags2; 17770 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 17771 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 17772 } 17773 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 17774 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 17775 } 17776 17777 drawableState = StateSet.get(viewStateIndex); 17778 17779 //noinspection ConstantIfStatement 17780 if (false) { 17781 Log.i("View", "drawableStateIndex=" + viewStateIndex); 17782 Log.i("View", toString() 17783 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 17784 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 17785 + " fo=" + hasFocus() 17786 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 17787 + " wf=" + hasWindowFocus() 17788 + ": " + Arrays.toString(drawableState)); 17789 } 17790 17791 if (extraSpace == 0) { 17792 return drawableState; 17793 } 17794 17795 final int[] fullState; 17796 if (drawableState != null) { 17797 fullState = new int[drawableState.length + extraSpace]; 17798 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 17799 } else { 17800 fullState = new int[extraSpace]; 17801 } 17802 17803 return fullState; 17804 } 17805 17806 /** 17807 * Merge your own state values in <var>additionalState</var> into the base 17808 * state values <var>baseState</var> that were returned by 17809 * {@link #onCreateDrawableState(int)}. 17810 * 17811 * @param baseState The base state values returned by 17812 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 17813 * own additional state values. 17814 * 17815 * @param additionalState The additional state values you would like 17816 * added to <var>baseState</var>; this array is not modified. 17817 * 17818 * @return As a convenience, the <var>baseState</var> array you originally 17819 * passed into the function is returned. 17820 * 17821 * @see #onCreateDrawableState(int) 17822 */ 17823 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 17824 final int N = baseState.length; 17825 int i = N - 1; 17826 while (i >= 0 && baseState[i] == 0) { 17827 i--; 17828 } 17829 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 17830 return baseState; 17831 } 17832 17833 /** 17834 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 17835 * on all Drawable objects associated with this view. 17836 * <p> 17837 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 17838 * attached to this view. 17839 */ 17840 @CallSuper 17841 public void jumpDrawablesToCurrentState() { 17842 if (mBackground != null) { 17843 mBackground.jumpToCurrentState(); 17844 } 17845 if (mStateListAnimator != null) { 17846 mStateListAnimator.jumpToCurrentState(); 17847 } 17848 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17849 mForegroundInfo.mDrawable.jumpToCurrentState(); 17850 } 17851 } 17852 17853 /** 17854 * Sets the background color for this view. 17855 * @param color the color of the background 17856 */ 17857 @RemotableViewMethod 17858 public void setBackgroundColor(@ColorInt int color) { 17859 if (mBackground instanceof ColorDrawable) { 17860 ((ColorDrawable) mBackground.mutate()).setColor(color); 17861 computeOpaqueFlags(); 17862 mBackgroundResource = 0; 17863 } else { 17864 setBackground(new ColorDrawable(color)); 17865 } 17866 } 17867 17868 /** 17869 * Set the background to a given resource. The resource should refer to 17870 * a Drawable object or 0 to remove the background. 17871 * @param resid The identifier of the resource. 17872 * 17873 * @attr ref android.R.styleable#View_background 17874 */ 17875 @RemotableViewMethod 17876 public void setBackgroundResource(@DrawableRes int resid) { 17877 if (resid != 0 && resid == mBackgroundResource) { 17878 return; 17879 } 17880 17881 Drawable d = null; 17882 if (resid != 0) { 17883 d = mContext.getDrawable(resid); 17884 } 17885 setBackground(d); 17886 17887 mBackgroundResource = resid; 17888 } 17889 17890 /** 17891 * Set the background to a given Drawable, or remove the background. If the 17892 * background has padding, this View's padding is set to the background's 17893 * padding. However, when a background is removed, this View's padding isn't 17894 * touched. If setting the padding is desired, please use 17895 * {@link #setPadding(int, int, int, int)}. 17896 * 17897 * @param background The Drawable to use as the background, or null to remove the 17898 * background 17899 */ 17900 public void setBackground(Drawable background) { 17901 //noinspection deprecation 17902 setBackgroundDrawable(background); 17903 } 17904 17905 /** 17906 * @deprecated use {@link #setBackground(Drawable)} instead 17907 */ 17908 @Deprecated 17909 public void setBackgroundDrawable(Drawable background) { 17910 computeOpaqueFlags(); 17911 17912 if (background == mBackground) { 17913 return; 17914 } 17915 17916 boolean requestLayout = false; 17917 17918 mBackgroundResource = 0; 17919 17920 /* 17921 * Regardless of whether we're setting a new background or not, we want 17922 * to clear the previous drawable. 17923 */ 17924 if (mBackground != null) { 17925 mBackground.setCallback(null); 17926 unscheduleDrawable(mBackground); 17927 } 17928 17929 if (background != null) { 17930 Rect padding = sThreadLocal.get(); 17931 if (padding == null) { 17932 padding = new Rect(); 17933 sThreadLocal.set(padding); 17934 } 17935 resetResolvedDrawablesInternal(); 17936 background.setLayoutDirection(getLayoutDirection()); 17937 if (background.getPadding(padding)) { 17938 resetResolvedPaddingInternal(); 17939 switch (background.getLayoutDirection()) { 17940 case LAYOUT_DIRECTION_RTL: 17941 mUserPaddingLeftInitial = padding.right; 17942 mUserPaddingRightInitial = padding.left; 17943 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 17944 break; 17945 case LAYOUT_DIRECTION_LTR: 17946 default: 17947 mUserPaddingLeftInitial = padding.left; 17948 mUserPaddingRightInitial = padding.right; 17949 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 17950 } 17951 mLeftPaddingDefined = false; 17952 mRightPaddingDefined = false; 17953 } 17954 17955 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 17956 // if it has a different minimum size, we should layout again 17957 if (mBackground == null 17958 || mBackground.getMinimumHeight() != background.getMinimumHeight() 17959 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 17960 requestLayout = true; 17961 } 17962 17963 background.setCallback(this); 17964 if (background.isStateful()) { 17965 background.setState(getDrawableState()); 17966 } 17967 background.setVisible(getVisibility() == VISIBLE, false); 17968 mBackground = background; 17969 17970 applyBackgroundTint(); 17971 17972 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 17973 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 17974 requestLayout = true; 17975 } 17976 } else { 17977 /* Remove the background */ 17978 mBackground = null; 17979 if ((mViewFlags & WILL_NOT_DRAW) != 0 17980 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 17981 mPrivateFlags |= PFLAG_SKIP_DRAW; 17982 } 17983 17984 /* 17985 * When the background is set, we try to apply its padding to this 17986 * View. When the background is removed, we don't touch this View's 17987 * padding. This is noted in the Javadocs. Hence, we don't need to 17988 * requestLayout(), the invalidate() below is sufficient. 17989 */ 17990 17991 // The old background's minimum size could have affected this 17992 // View's layout, so let's requestLayout 17993 requestLayout = true; 17994 } 17995 17996 computeOpaqueFlags(); 17997 17998 if (requestLayout) { 17999 requestLayout(); 18000 } 18001 18002 mBackgroundSizeChanged = true; 18003 invalidate(true); 18004 } 18005 18006 /** 18007 * Gets the background drawable 18008 * 18009 * @return The drawable used as the background for this view, if any. 18010 * 18011 * @see #setBackground(Drawable) 18012 * 18013 * @attr ref android.R.styleable#View_background 18014 */ 18015 public Drawable getBackground() { 18016 return mBackground; 18017 } 18018 18019 /** 18020 * Applies a tint to the background drawable. Does not modify the current tint 18021 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18022 * <p> 18023 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18024 * mutate the drawable and apply the specified tint and tint mode using 18025 * {@link Drawable#setTintList(ColorStateList)}. 18026 * 18027 * @param tint the tint to apply, may be {@code null} to clear tint 18028 * 18029 * @attr ref android.R.styleable#View_backgroundTint 18030 * @see #getBackgroundTintList() 18031 * @see Drawable#setTintList(ColorStateList) 18032 */ 18033 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18034 if (mBackgroundTint == null) { 18035 mBackgroundTint = new TintInfo(); 18036 } 18037 mBackgroundTint.mTintList = tint; 18038 mBackgroundTint.mHasTintList = true; 18039 18040 applyBackgroundTint(); 18041 } 18042 18043 /** 18044 * Return the tint applied to the background drawable, if specified. 18045 * 18046 * @return the tint applied to the background drawable 18047 * @attr ref android.R.styleable#View_backgroundTint 18048 * @see #setBackgroundTintList(ColorStateList) 18049 */ 18050 @Nullable 18051 public ColorStateList getBackgroundTintList() { 18052 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18053 } 18054 18055 /** 18056 * Specifies the blending mode used to apply the tint specified by 18057 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18058 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18059 * 18060 * @param tintMode the blending mode used to apply the tint, may be 18061 * {@code null} to clear tint 18062 * @attr ref android.R.styleable#View_backgroundTintMode 18063 * @see #getBackgroundTintMode() 18064 * @see Drawable#setTintMode(PorterDuff.Mode) 18065 */ 18066 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18067 if (mBackgroundTint == null) { 18068 mBackgroundTint = new TintInfo(); 18069 } 18070 mBackgroundTint.mTintMode = tintMode; 18071 mBackgroundTint.mHasTintMode = true; 18072 18073 applyBackgroundTint(); 18074 } 18075 18076 /** 18077 * Return the blending mode used to apply the tint to the background 18078 * drawable, if specified. 18079 * 18080 * @return the blending mode used to apply the tint to the background 18081 * drawable 18082 * @attr ref android.R.styleable#View_backgroundTintMode 18083 * @see #setBackgroundTintMode(PorterDuff.Mode) 18084 */ 18085 @Nullable 18086 public PorterDuff.Mode getBackgroundTintMode() { 18087 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18088 } 18089 18090 private void applyBackgroundTint() { 18091 if (mBackground != null && mBackgroundTint != null) { 18092 final TintInfo tintInfo = mBackgroundTint; 18093 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18094 mBackground = mBackground.mutate(); 18095 18096 if (tintInfo.mHasTintList) { 18097 mBackground.setTintList(tintInfo.mTintList); 18098 } 18099 18100 if (tintInfo.mHasTintMode) { 18101 mBackground.setTintMode(tintInfo.mTintMode); 18102 } 18103 18104 // The drawable (or one of its children) may not have been 18105 // stateful before applying the tint, so let's try again. 18106 if (mBackground.isStateful()) { 18107 mBackground.setState(getDrawableState()); 18108 } 18109 } 18110 } 18111 } 18112 18113 /** 18114 * Returns the drawable used as the foreground of this View. The 18115 * foreground drawable, if non-null, is always drawn on top of the view's content. 18116 * 18117 * @return a Drawable or null if no foreground was set 18118 * 18119 * @see #onDrawForeground(Canvas) 18120 */ 18121 public Drawable getForeground() { 18122 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18123 } 18124 18125 /** 18126 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18127 * 18128 * @param foreground the Drawable to be drawn on top of the children 18129 * 18130 * @attr ref android.R.styleable#View_foreground 18131 */ 18132 public void setForeground(Drawable foreground) { 18133 if (mForegroundInfo == null) { 18134 if (foreground == null) { 18135 // Nothing to do. 18136 return; 18137 } 18138 mForegroundInfo = new ForegroundInfo(); 18139 } 18140 18141 if (foreground == mForegroundInfo.mDrawable) { 18142 // Nothing to do 18143 return; 18144 } 18145 18146 if (mForegroundInfo.mDrawable != null) { 18147 mForegroundInfo.mDrawable.setCallback(null); 18148 unscheduleDrawable(mForegroundInfo.mDrawable); 18149 } 18150 18151 mForegroundInfo.mDrawable = foreground; 18152 mForegroundInfo.mBoundsChanged = true; 18153 if (foreground != null) { 18154 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18155 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18156 } 18157 foreground.setCallback(this); 18158 foreground.setLayoutDirection(getLayoutDirection()); 18159 if (foreground.isStateful()) { 18160 foreground.setState(getDrawableState()); 18161 } 18162 applyForegroundTint(); 18163 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18164 mPrivateFlags |= PFLAG_SKIP_DRAW; 18165 } 18166 requestLayout(); 18167 invalidate(); 18168 } 18169 18170 /** 18171 * Magic bit used to support features of framework-internal window decor implementation details. 18172 * This used to live exclusively in FrameLayout. 18173 * 18174 * @return true if the foreground should draw inside the padding region or false 18175 * if it should draw inset by the view's padding 18176 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18177 */ 18178 public boolean isForegroundInsidePadding() { 18179 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18180 } 18181 18182 /** 18183 * Describes how the foreground is positioned. 18184 * 18185 * @return foreground gravity. 18186 * 18187 * @see #setForegroundGravity(int) 18188 * 18189 * @attr ref android.R.styleable#View_foregroundGravity 18190 */ 18191 public int getForegroundGravity() { 18192 return mForegroundInfo != null ? mForegroundInfo.mGravity 18193 : Gravity.START | Gravity.TOP; 18194 } 18195 18196 /** 18197 * Describes how the foreground is positioned. Defaults to START and TOP. 18198 * 18199 * @param gravity see {@link android.view.Gravity} 18200 * 18201 * @see #getForegroundGravity() 18202 * 18203 * @attr ref android.R.styleable#View_foregroundGravity 18204 */ 18205 public void setForegroundGravity(int gravity) { 18206 if (mForegroundInfo == null) { 18207 mForegroundInfo = new ForegroundInfo(); 18208 } 18209 18210 if (mForegroundInfo.mGravity != gravity) { 18211 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18212 gravity |= Gravity.START; 18213 } 18214 18215 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18216 gravity |= Gravity.TOP; 18217 } 18218 18219 mForegroundInfo.mGravity = gravity; 18220 requestLayout(); 18221 } 18222 } 18223 18224 /** 18225 * Applies a tint to the foreground drawable. Does not modify the current tint 18226 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18227 * <p> 18228 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18229 * mutate the drawable and apply the specified tint and tint mode using 18230 * {@link Drawable#setTintList(ColorStateList)}. 18231 * 18232 * @param tint the tint to apply, may be {@code null} to clear tint 18233 * 18234 * @attr ref android.R.styleable#View_foregroundTint 18235 * @see #getForegroundTintList() 18236 * @see Drawable#setTintList(ColorStateList) 18237 */ 18238 public void setForegroundTintList(@Nullable ColorStateList tint) { 18239 if (mForegroundInfo == null) { 18240 mForegroundInfo = new ForegroundInfo(); 18241 } 18242 if (mForegroundInfo.mTintInfo == null) { 18243 mForegroundInfo.mTintInfo = new TintInfo(); 18244 } 18245 mForegroundInfo.mTintInfo.mTintList = tint; 18246 mForegroundInfo.mTintInfo.mHasTintList = true; 18247 18248 applyForegroundTint(); 18249 } 18250 18251 /** 18252 * Return the tint applied to the foreground drawable, if specified. 18253 * 18254 * @return the tint applied to the foreground drawable 18255 * @attr ref android.R.styleable#View_foregroundTint 18256 * @see #setForegroundTintList(ColorStateList) 18257 */ 18258 @Nullable 18259 public ColorStateList getForegroundTintList() { 18260 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18261 ? mForegroundInfo.mTintInfo.mTintList : null; 18262 } 18263 18264 /** 18265 * Specifies the blending mode used to apply the tint specified by 18266 * {@link #setForegroundTintList(ColorStateList)}} to the background 18267 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18268 * 18269 * @param tintMode the blending mode used to apply the tint, may be 18270 * {@code null} to clear tint 18271 * @attr ref android.R.styleable#View_foregroundTintMode 18272 * @see #getForegroundTintMode() 18273 * @see Drawable#setTintMode(PorterDuff.Mode) 18274 */ 18275 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18276 if (mForegroundInfo == null) { 18277 mForegroundInfo = new ForegroundInfo(); 18278 } 18279 if (mForegroundInfo.mTintInfo == null) { 18280 mForegroundInfo.mTintInfo = new TintInfo(); 18281 } 18282 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18283 mForegroundInfo.mTintInfo.mHasTintMode = true; 18284 18285 applyForegroundTint(); 18286 } 18287 18288 /** 18289 * Return the blending mode used to apply the tint to the foreground 18290 * drawable, if specified. 18291 * 18292 * @return the blending mode used to apply the tint to the foreground 18293 * drawable 18294 * @attr ref android.R.styleable#View_foregroundTintMode 18295 * @see #setForegroundTintMode(PorterDuff.Mode) 18296 */ 18297 @Nullable 18298 public PorterDuff.Mode getForegroundTintMode() { 18299 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18300 ? mForegroundInfo.mTintInfo.mTintMode : null; 18301 } 18302 18303 private void applyForegroundTint() { 18304 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18305 && mForegroundInfo.mTintInfo != null) { 18306 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18307 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18308 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18309 18310 if (tintInfo.mHasTintList) { 18311 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18312 } 18313 18314 if (tintInfo.mHasTintMode) { 18315 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18316 } 18317 18318 // The drawable (or one of its children) may not have been 18319 // stateful before applying the tint, so let's try again. 18320 if (mForegroundInfo.mDrawable.isStateful()) { 18321 mForegroundInfo.mDrawable.setState(getDrawableState()); 18322 } 18323 } 18324 } 18325 } 18326 18327 /** 18328 * Draw any foreground content for this view. 18329 * 18330 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18331 * drawable or other view-specific decorations. The foreground is drawn on top of the 18332 * primary view content.</p> 18333 * 18334 * @param canvas canvas to draw into 18335 */ 18336 public void onDrawForeground(Canvas canvas) { 18337 onDrawScrollIndicators(canvas); 18338 onDrawScrollBars(canvas); 18339 18340 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18341 if (foreground != null) { 18342 if (mForegroundInfo.mBoundsChanged) { 18343 mForegroundInfo.mBoundsChanged = false; 18344 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18345 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18346 18347 if (mForegroundInfo.mInsidePadding) { 18348 selfBounds.set(0, 0, getWidth(), getHeight()); 18349 } else { 18350 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18351 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18352 } 18353 18354 final int ld = getLayoutDirection(); 18355 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18356 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18357 foreground.setBounds(overlayBounds); 18358 } 18359 18360 foreground.draw(canvas); 18361 } 18362 } 18363 18364 /** 18365 * Sets the padding. The view may add on the space required to display 18366 * the scrollbars, depending on the style and visibility of the scrollbars. 18367 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18368 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18369 * from the values set in this call. 18370 * 18371 * @attr ref android.R.styleable#View_padding 18372 * @attr ref android.R.styleable#View_paddingBottom 18373 * @attr ref android.R.styleable#View_paddingLeft 18374 * @attr ref android.R.styleable#View_paddingRight 18375 * @attr ref android.R.styleable#View_paddingTop 18376 * @param left the left padding in pixels 18377 * @param top the top padding in pixels 18378 * @param right the right padding in pixels 18379 * @param bottom the bottom padding in pixels 18380 */ 18381 public void setPadding(int left, int top, int right, int bottom) { 18382 resetResolvedPaddingInternal(); 18383 18384 mUserPaddingStart = UNDEFINED_PADDING; 18385 mUserPaddingEnd = UNDEFINED_PADDING; 18386 18387 mUserPaddingLeftInitial = left; 18388 mUserPaddingRightInitial = right; 18389 18390 mLeftPaddingDefined = true; 18391 mRightPaddingDefined = true; 18392 18393 internalSetPadding(left, top, right, bottom); 18394 } 18395 18396 /** 18397 * @hide 18398 */ 18399 protected void internalSetPadding(int left, int top, int right, int bottom) { 18400 mUserPaddingLeft = left; 18401 mUserPaddingRight = right; 18402 mUserPaddingBottom = bottom; 18403 18404 final int viewFlags = mViewFlags; 18405 boolean changed = false; 18406 18407 // Common case is there are no scroll bars. 18408 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18409 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18410 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18411 ? 0 : getVerticalScrollbarWidth(); 18412 switch (mVerticalScrollbarPosition) { 18413 case SCROLLBAR_POSITION_DEFAULT: 18414 if (isLayoutRtl()) { 18415 left += offset; 18416 } else { 18417 right += offset; 18418 } 18419 break; 18420 case SCROLLBAR_POSITION_RIGHT: 18421 right += offset; 18422 break; 18423 case SCROLLBAR_POSITION_LEFT: 18424 left += offset; 18425 break; 18426 } 18427 } 18428 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18429 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18430 ? 0 : getHorizontalScrollbarHeight(); 18431 } 18432 } 18433 18434 if (mPaddingLeft != left) { 18435 changed = true; 18436 mPaddingLeft = left; 18437 } 18438 if (mPaddingTop != top) { 18439 changed = true; 18440 mPaddingTop = top; 18441 } 18442 if (mPaddingRight != right) { 18443 changed = true; 18444 mPaddingRight = right; 18445 } 18446 if (mPaddingBottom != bottom) { 18447 changed = true; 18448 mPaddingBottom = bottom; 18449 } 18450 18451 if (changed) { 18452 requestLayout(); 18453 invalidateOutline(); 18454 } 18455 } 18456 18457 /** 18458 * Sets the relative padding. The view may add on the space required to display 18459 * the scrollbars, depending on the style and visibility of the scrollbars. 18460 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18461 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18462 * from the values set in this call. 18463 * 18464 * @attr ref android.R.styleable#View_padding 18465 * @attr ref android.R.styleable#View_paddingBottom 18466 * @attr ref android.R.styleable#View_paddingStart 18467 * @attr ref android.R.styleable#View_paddingEnd 18468 * @attr ref android.R.styleable#View_paddingTop 18469 * @param start the start padding in pixels 18470 * @param top the top padding in pixels 18471 * @param end the end padding in pixels 18472 * @param bottom the bottom padding in pixels 18473 */ 18474 public void setPaddingRelative(int start, int top, int end, int bottom) { 18475 resetResolvedPaddingInternal(); 18476 18477 mUserPaddingStart = start; 18478 mUserPaddingEnd = end; 18479 mLeftPaddingDefined = true; 18480 mRightPaddingDefined = true; 18481 18482 switch(getLayoutDirection()) { 18483 case LAYOUT_DIRECTION_RTL: 18484 mUserPaddingLeftInitial = end; 18485 mUserPaddingRightInitial = start; 18486 internalSetPadding(end, top, start, bottom); 18487 break; 18488 case LAYOUT_DIRECTION_LTR: 18489 default: 18490 mUserPaddingLeftInitial = start; 18491 mUserPaddingRightInitial = end; 18492 internalSetPadding(start, top, end, bottom); 18493 } 18494 } 18495 18496 /** 18497 * Returns the top padding of this view. 18498 * 18499 * @return the top padding in pixels 18500 */ 18501 public int getPaddingTop() { 18502 return mPaddingTop; 18503 } 18504 18505 /** 18506 * Returns the bottom padding of this view. If there are inset and enabled 18507 * scrollbars, this value may include the space required to display the 18508 * scrollbars as well. 18509 * 18510 * @return the bottom padding in pixels 18511 */ 18512 public int getPaddingBottom() { 18513 return mPaddingBottom; 18514 } 18515 18516 /** 18517 * Returns the left padding of this view. If there are inset and enabled 18518 * scrollbars, this value may include the space required to display the 18519 * scrollbars as well. 18520 * 18521 * @return the left padding in pixels 18522 */ 18523 public int getPaddingLeft() { 18524 if (!isPaddingResolved()) { 18525 resolvePadding(); 18526 } 18527 return mPaddingLeft; 18528 } 18529 18530 /** 18531 * Returns the start padding of this view depending on its resolved layout direction. 18532 * If there are inset and enabled scrollbars, this value may include the space 18533 * required to display the scrollbars as well. 18534 * 18535 * @return the start padding in pixels 18536 */ 18537 public int getPaddingStart() { 18538 if (!isPaddingResolved()) { 18539 resolvePadding(); 18540 } 18541 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18542 mPaddingRight : mPaddingLeft; 18543 } 18544 18545 /** 18546 * Returns the right padding of this view. If there are inset and enabled 18547 * scrollbars, this value may include the space required to display the 18548 * scrollbars as well. 18549 * 18550 * @return the right padding in pixels 18551 */ 18552 public int getPaddingRight() { 18553 if (!isPaddingResolved()) { 18554 resolvePadding(); 18555 } 18556 return mPaddingRight; 18557 } 18558 18559 /** 18560 * Returns the end padding of this view depending on its resolved layout direction. 18561 * If there are inset and enabled scrollbars, this value may include the space 18562 * required to display the scrollbars as well. 18563 * 18564 * @return the end padding in pixels 18565 */ 18566 public int getPaddingEnd() { 18567 if (!isPaddingResolved()) { 18568 resolvePadding(); 18569 } 18570 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18571 mPaddingLeft : mPaddingRight; 18572 } 18573 18574 /** 18575 * Return if the padding has been set through relative values 18576 * {@link #setPaddingRelative(int, int, int, int)} or through 18577 * @attr ref android.R.styleable#View_paddingStart or 18578 * @attr ref android.R.styleable#View_paddingEnd 18579 * 18580 * @return true if the padding is relative or false if it is not. 18581 */ 18582 public boolean isPaddingRelative() { 18583 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18584 } 18585 18586 Insets computeOpticalInsets() { 18587 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18588 } 18589 18590 /** 18591 * @hide 18592 */ 18593 public void resetPaddingToInitialValues() { 18594 if (isRtlCompatibilityMode()) { 18595 mPaddingLeft = mUserPaddingLeftInitial; 18596 mPaddingRight = mUserPaddingRightInitial; 18597 return; 18598 } 18599 if (isLayoutRtl()) { 18600 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 18601 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 18602 } else { 18603 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 18604 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 18605 } 18606 } 18607 18608 /** 18609 * @hide 18610 */ 18611 public Insets getOpticalInsets() { 18612 if (mLayoutInsets == null) { 18613 mLayoutInsets = computeOpticalInsets(); 18614 } 18615 return mLayoutInsets; 18616 } 18617 18618 /** 18619 * Set this view's optical insets. 18620 * 18621 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 18622 * property. Views that compute their own optical insets should call it as part of measurement. 18623 * This method does not request layout. If you are setting optical insets outside of 18624 * measure/layout itself you will want to call requestLayout() yourself. 18625 * </p> 18626 * @hide 18627 */ 18628 public void setOpticalInsets(Insets insets) { 18629 mLayoutInsets = insets; 18630 } 18631 18632 /** 18633 * Changes the selection state of this view. A view can be selected or not. 18634 * Note that selection is not the same as focus. Views are typically 18635 * selected in the context of an AdapterView like ListView or GridView; 18636 * the selected view is the view that is highlighted. 18637 * 18638 * @param selected true if the view must be selected, false otherwise 18639 */ 18640 public void setSelected(boolean selected) { 18641 //noinspection DoubleNegation 18642 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 18643 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 18644 if (!selected) resetPressedState(); 18645 invalidate(true); 18646 refreshDrawableState(); 18647 dispatchSetSelected(selected); 18648 if (selected) { 18649 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 18650 } else { 18651 notifyViewAccessibilityStateChangedIfNeeded( 18652 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 18653 } 18654 } 18655 } 18656 18657 /** 18658 * Dispatch setSelected to all of this View's children. 18659 * 18660 * @see #setSelected(boolean) 18661 * 18662 * @param selected The new selected state 18663 */ 18664 protected void dispatchSetSelected(boolean selected) { 18665 } 18666 18667 /** 18668 * Indicates the selection state of this view. 18669 * 18670 * @return true if the view is selected, false otherwise 18671 */ 18672 @ViewDebug.ExportedProperty 18673 public boolean isSelected() { 18674 return (mPrivateFlags & PFLAG_SELECTED) != 0; 18675 } 18676 18677 /** 18678 * Changes the activated state of this view. A view can be activated or not. 18679 * Note that activation is not the same as selection. Selection is 18680 * a transient property, representing the view (hierarchy) the user is 18681 * currently interacting with. Activation is a longer-term state that the 18682 * user can move views in and out of. For example, in a list view with 18683 * single or multiple selection enabled, the views in the current selection 18684 * set are activated. (Um, yeah, we are deeply sorry about the terminology 18685 * here.) The activated state is propagated down to children of the view it 18686 * is set on. 18687 * 18688 * @param activated true if the view must be activated, false otherwise 18689 */ 18690 public void setActivated(boolean activated) { 18691 //noinspection DoubleNegation 18692 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 18693 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 18694 invalidate(true); 18695 refreshDrawableState(); 18696 dispatchSetActivated(activated); 18697 } 18698 } 18699 18700 /** 18701 * Dispatch setActivated to all of this View's children. 18702 * 18703 * @see #setActivated(boolean) 18704 * 18705 * @param activated The new activated state 18706 */ 18707 protected void dispatchSetActivated(boolean activated) { 18708 } 18709 18710 /** 18711 * Indicates the activation state of this view. 18712 * 18713 * @return true if the view is activated, false otherwise 18714 */ 18715 @ViewDebug.ExportedProperty 18716 public boolean isActivated() { 18717 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 18718 } 18719 18720 /** 18721 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 18722 * observer can be used to get notifications when global events, like 18723 * layout, happen. 18724 * 18725 * The returned ViewTreeObserver observer is not guaranteed to remain 18726 * valid for the lifetime of this View. If the caller of this method keeps 18727 * a long-lived reference to ViewTreeObserver, it should always check for 18728 * the return value of {@link ViewTreeObserver#isAlive()}. 18729 * 18730 * @return The ViewTreeObserver for this view's hierarchy. 18731 */ 18732 public ViewTreeObserver getViewTreeObserver() { 18733 if (mAttachInfo != null) { 18734 return mAttachInfo.mTreeObserver; 18735 } 18736 if (mFloatingTreeObserver == null) { 18737 mFloatingTreeObserver = new ViewTreeObserver(); 18738 } 18739 return mFloatingTreeObserver; 18740 } 18741 18742 /** 18743 * <p>Finds the topmost view in the current view hierarchy.</p> 18744 * 18745 * @return the topmost view containing this view 18746 */ 18747 public View getRootView() { 18748 if (mAttachInfo != null) { 18749 final View v = mAttachInfo.mRootView; 18750 if (v != null) { 18751 return v; 18752 } 18753 } 18754 18755 View parent = this; 18756 18757 while (parent.mParent != null && parent.mParent instanceof View) { 18758 parent = (View) parent.mParent; 18759 } 18760 18761 return parent; 18762 } 18763 18764 /** 18765 * Transforms a motion event from view-local coordinates to on-screen 18766 * coordinates. 18767 * 18768 * @param ev the view-local motion event 18769 * @return false if the transformation could not be applied 18770 * @hide 18771 */ 18772 public boolean toGlobalMotionEvent(MotionEvent ev) { 18773 final AttachInfo info = mAttachInfo; 18774 if (info == null) { 18775 return false; 18776 } 18777 18778 final Matrix m = info.mTmpMatrix; 18779 m.set(Matrix.IDENTITY_MATRIX); 18780 transformMatrixToGlobal(m); 18781 ev.transform(m); 18782 return true; 18783 } 18784 18785 /** 18786 * Transforms a motion event from on-screen coordinates to view-local 18787 * coordinates. 18788 * 18789 * @param ev the on-screen motion event 18790 * @return false if the transformation could not be applied 18791 * @hide 18792 */ 18793 public boolean toLocalMotionEvent(MotionEvent ev) { 18794 final AttachInfo info = mAttachInfo; 18795 if (info == null) { 18796 return false; 18797 } 18798 18799 final Matrix m = info.mTmpMatrix; 18800 m.set(Matrix.IDENTITY_MATRIX); 18801 transformMatrixToLocal(m); 18802 ev.transform(m); 18803 return true; 18804 } 18805 18806 /** 18807 * Modifies the input matrix such that it maps view-local coordinates to 18808 * on-screen coordinates. 18809 * 18810 * @param m input matrix to modify 18811 * @hide 18812 */ 18813 public void transformMatrixToGlobal(Matrix m) { 18814 final ViewParent parent = mParent; 18815 if (parent instanceof View) { 18816 final View vp = (View) parent; 18817 vp.transformMatrixToGlobal(m); 18818 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 18819 } else if (parent instanceof ViewRootImpl) { 18820 final ViewRootImpl vr = (ViewRootImpl) parent; 18821 vr.transformMatrixToGlobal(m); 18822 m.preTranslate(0, -vr.mCurScrollY); 18823 } 18824 18825 m.preTranslate(mLeft, mTop); 18826 18827 if (!hasIdentityMatrix()) { 18828 m.preConcat(getMatrix()); 18829 } 18830 } 18831 18832 /** 18833 * Modifies the input matrix such that it maps on-screen coordinates to 18834 * view-local coordinates. 18835 * 18836 * @param m input matrix to modify 18837 * @hide 18838 */ 18839 public void transformMatrixToLocal(Matrix m) { 18840 final ViewParent parent = mParent; 18841 if (parent instanceof View) { 18842 final View vp = (View) parent; 18843 vp.transformMatrixToLocal(m); 18844 m.postTranslate(vp.mScrollX, vp.mScrollY); 18845 } else if (parent instanceof ViewRootImpl) { 18846 final ViewRootImpl vr = (ViewRootImpl) parent; 18847 vr.transformMatrixToLocal(m); 18848 m.postTranslate(0, vr.mCurScrollY); 18849 } 18850 18851 m.postTranslate(-mLeft, -mTop); 18852 18853 if (!hasIdentityMatrix()) { 18854 m.postConcat(getInverseMatrix()); 18855 } 18856 } 18857 18858 /** 18859 * @hide 18860 */ 18861 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 18862 @ViewDebug.IntToString(from = 0, to = "x"), 18863 @ViewDebug.IntToString(from = 1, to = "y") 18864 }) 18865 public int[] getLocationOnScreen() { 18866 int[] location = new int[2]; 18867 getLocationOnScreen(location); 18868 return location; 18869 } 18870 18871 /** 18872 * <p>Computes the coordinates of this view on the screen. The argument 18873 * must be an array of two integers. After the method returns, the array 18874 * contains the x and y location in that order.</p> 18875 * 18876 * @param outLocation an array of two integers in which to hold the coordinates 18877 */ 18878 public void getLocationOnScreen(@Size(2) int[] outLocation) { 18879 getLocationInWindow(outLocation); 18880 18881 final AttachInfo info = mAttachInfo; 18882 if (info != null) { 18883 outLocation[0] += info.mWindowLeft; 18884 outLocation[1] += info.mWindowTop; 18885 } 18886 } 18887 18888 /** 18889 * <p>Computes the coordinates of this view in its window. The argument 18890 * must be an array of two integers. After the method returns, the array 18891 * contains the x and y location in that order.</p> 18892 * 18893 * @param outLocation an array of two integers in which to hold the coordinates 18894 */ 18895 public void getLocationInWindow(@Size(2) int[] outLocation) { 18896 if (outLocation == null || outLocation.length < 2) { 18897 throw new IllegalArgumentException("outLocation must be an array of two integers"); 18898 } 18899 18900 outLocation[0] = 0; 18901 outLocation[1] = 0; 18902 18903 transformFromViewToWindowSpace(outLocation); 18904 } 18905 18906 void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 18907 if (inOutLocation == null || inOutLocation.length < 2) { 18908 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 18909 } 18910 18911 if (mAttachInfo == null) { 18912 // When the view is not attached to a window, this method does not make sense 18913 inOutLocation[0] = inOutLocation[1] = 0; 18914 return; 18915 } 18916 18917 float position[] = mAttachInfo.mTmpTransformLocation; 18918 position[0] = inOutLocation[0]; 18919 position[1] = inOutLocation[1]; 18920 18921 if (!hasIdentityMatrix()) { 18922 getMatrix().mapPoints(position); 18923 } 18924 18925 position[0] += mLeft; 18926 position[1] += mTop; 18927 18928 ViewParent viewParent = mParent; 18929 while (viewParent instanceof View) { 18930 final View view = (View) viewParent; 18931 18932 position[0] -= view.mScrollX; 18933 position[1] -= view.mScrollY; 18934 18935 if (!view.hasIdentityMatrix()) { 18936 view.getMatrix().mapPoints(position); 18937 } 18938 18939 position[0] += view.mLeft; 18940 position[1] += view.mTop; 18941 18942 viewParent = view.mParent; 18943 } 18944 18945 if (viewParent instanceof ViewRootImpl) { 18946 // *cough* 18947 final ViewRootImpl vr = (ViewRootImpl) viewParent; 18948 position[1] -= vr.mCurScrollY; 18949 } 18950 18951 inOutLocation[0] = Math.round(position[0]); 18952 inOutLocation[1] = Math.round(position[1]); 18953 } 18954 18955 /** 18956 * {@hide} 18957 * @param id the id of the view to be found 18958 * @return the view of the specified id, null if cannot be found 18959 */ 18960 protected View findViewTraversal(@IdRes int id) { 18961 if (id == mID) { 18962 return this; 18963 } 18964 return null; 18965 } 18966 18967 /** 18968 * {@hide} 18969 * @param tag the tag of the view to be found 18970 * @return the view of specified tag, null if cannot be found 18971 */ 18972 protected View findViewWithTagTraversal(Object tag) { 18973 if (tag != null && tag.equals(mTag)) { 18974 return this; 18975 } 18976 return null; 18977 } 18978 18979 /** 18980 * {@hide} 18981 * @param predicate The predicate to evaluate. 18982 * @param childToSkip If not null, ignores this child during the recursive traversal. 18983 * @return The first view that matches the predicate or null. 18984 */ 18985 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 18986 if (predicate.apply(this)) { 18987 return this; 18988 } 18989 return null; 18990 } 18991 18992 /** 18993 * Look for a child view with the given id. If this view has the given 18994 * id, return this view. 18995 * 18996 * @param id The id to search for. 18997 * @return The view that has the given id in the hierarchy or null 18998 */ 18999 @Nullable 19000 public final View findViewById(@IdRes int id) { 19001 if (id < 0) { 19002 return null; 19003 } 19004 return findViewTraversal(id); 19005 } 19006 19007 /** 19008 * Finds a view by its unuque and stable accessibility id. 19009 * 19010 * @param accessibilityId The searched accessibility id. 19011 * @return The found view. 19012 */ 19013 final View findViewByAccessibilityId(int accessibilityId) { 19014 if (accessibilityId < 0) { 19015 return null; 19016 } 19017 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19018 if (view != null) { 19019 return view.includeForAccessibility() ? view : null; 19020 } 19021 return null; 19022 } 19023 19024 /** 19025 * Performs the traversal to find a view by its unuque and stable accessibility id. 19026 * 19027 * <strong>Note:</strong>This method does not stop at the root namespace 19028 * boundary since the user can touch the screen at an arbitrary location 19029 * potentially crossing the root namespace bounday which will send an 19030 * accessibility event to accessibility services and they should be able 19031 * to obtain the event source. Also accessibility ids are guaranteed to be 19032 * unique in the window. 19033 * 19034 * @param accessibilityId The accessibility id. 19035 * @return The found view. 19036 * 19037 * @hide 19038 */ 19039 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19040 if (getAccessibilityViewId() == accessibilityId) { 19041 return this; 19042 } 19043 return null; 19044 } 19045 19046 /** 19047 * Look for a child view with the given tag. If this view has the given 19048 * tag, return this view. 19049 * 19050 * @param tag The tag to search for, using "tag.equals(getTag())". 19051 * @return The View that has the given tag in the hierarchy or null 19052 */ 19053 public final View findViewWithTag(Object tag) { 19054 if (tag == null) { 19055 return null; 19056 } 19057 return findViewWithTagTraversal(tag); 19058 } 19059 19060 /** 19061 * {@hide} 19062 * Look for a child view that matches the specified predicate. 19063 * If this view matches the predicate, return this view. 19064 * 19065 * @param predicate The predicate to evaluate. 19066 * @return The first view that matches the predicate or null. 19067 */ 19068 public final View findViewByPredicate(Predicate<View> predicate) { 19069 return findViewByPredicateTraversal(predicate, null); 19070 } 19071 19072 /** 19073 * {@hide} 19074 * Look for a child view that matches the specified predicate, 19075 * starting with the specified view and its descendents and then 19076 * recusively searching the ancestors and siblings of that view 19077 * until this view is reached. 19078 * 19079 * This method is useful in cases where the predicate does not match 19080 * a single unique view (perhaps multiple views use the same id) 19081 * and we are trying to find the view that is "closest" in scope to the 19082 * starting view. 19083 * 19084 * @param start The view to start from. 19085 * @param predicate The predicate to evaluate. 19086 * @return The first view that matches the predicate or null. 19087 */ 19088 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19089 View childToSkip = null; 19090 for (;;) { 19091 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19092 if (view != null || start == this) { 19093 return view; 19094 } 19095 19096 ViewParent parent = start.getParent(); 19097 if (parent == null || !(parent instanceof View)) { 19098 return null; 19099 } 19100 19101 childToSkip = start; 19102 start = (View) parent; 19103 } 19104 } 19105 19106 /** 19107 * Sets the identifier for this view. The identifier does not have to be 19108 * unique in this view's hierarchy. The identifier should be a positive 19109 * number. 19110 * 19111 * @see #NO_ID 19112 * @see #getId() 19113 * @see #findViewById(int) 19114 * 19115 * @param id a number used to identify the view 19116 * 19117 * @attr ref android.R.styleable#View_id 19118 */ 19119 public void setId(@IdRes int id) { 19120 mID = id; 19121 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19122 mID = generateViewId(); 19123 } 19124 } 19125 19126 /** 19127 * {@hide} 19128 * 19129 * @param isRoot true if the view belongs to the root namespace, false 19130 * otherwise 19131 */ 19132 public void setIsRootNamespace(boolean isRoot) { 19133 if (isRoot) { 19134 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19135 } else { 19136 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19137 } 19138 } 19139 19140 /** 19141 * {@hide} 19142 * 19143 * @return true if the view belongs to the root namespace, false otherwise 19144 */ 19145 public boolean isRootNamespace() { 19146 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19147 } 19148 19149 /** 19150 * Returns this view's identifier. 19151 * 19152 * @return a positive integer used to identify the view or {@link #NO_ID} 19153 * if the view has no ID 19154 * 19155 * @see #setId(int) 19156 * @see #findViewById(int) 19157 * @attr ref android.R.styleable#View_id 19158 */ 19159 @IdRes 19160 @ViewDebug.CapturedViewProperty 19161 public int getId() { 19162 return mID; 19163 } 19164 19165 /** 19166 * Returns this view's tag. 19167 * 19168 * @return the Object stored in this view as a tag, or {@code null} if not 19169 * set 19170 * 19171 * @see #setTag(Object) 19172 * @see #getTag(int) 19173 */ 19174 @ViewDebug.ExportedProperty 19175 public Object getTag() { 19176 return mTag; 19177 } 19178 19179 /** 19180 * Sets the tag associated with this view. A tag can be used to mark 19181 * a view in its hierarchy and does not have to be unique within the 19182 * hierarchy. Tags can also be used to store data within a view without 19183 * resorting to another data structure. 19184 * 19185 * @param tag an Object to tag the view with 19186 * 19187 * @see #getTag() 19188 * @see #setTag(int, Object) 19189 */ 19190 public void setTag(final Object tag) { 19191 mTag = tag; 19192 } 19193 19194 /** 19195 * Returns the tag associated with this view and the specified key. 19196 * 19197 * @param key The key identifying the tag 19198 * 19199 * @return the Object stored in this view as a tag, or {@code null} if not 19200 * set 19201 * 19202 * @see #setTag(int, Object) 19203 * @see #getTag() 19204 */ 19205 public Object getTag(int key) { 19206 if (mKeyedTags != null) return mKeyedTags.get(key); 19207 return null; 19208 } 19209 19210 /** 19211 * Sets a tag associated with this view and a key. A tag can be used 19212 * to mark a view in its hierarchy and does not have to be unique within 19213 * the hierarchy. Tags can also be used to store data within a view 19214 * without resorting to another data structure. 19215 * 19216 * The specified key should be an id declared in the resources of the 19217 * application to ensure it is unique (see the <a 19218 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19219 * Keys identified as belonging to 19220 * the Android framework or not associated with any package will cause 19221 * an {@link IllegalArgumentException} to be thrown. 19222 * 19223 * @param key The key identifying the tag 19224 * @param tag An Object to tag the view with 19225 * 19226 * @throws IllegalArgumentException If they specified key is not valid 19227 * 19228 * @see #setTag(Object) 19229 * @see #getTag(int) 19230 */ 19231 public void setTag(int key, final Object tag) { 19232 // If the package id is 0x00 or 0x01, it's either an undefined package 19233 // or a framework id 19234 if ((key >>> 24) < 2) { 19235 throw new IllegalArgumentException("The key must be an application-specific " 19236 + "resource id."); 19237 } 19238 19239 setKeyedTag(key, tag); 19240 } 19241 19242 /** 19243 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19244 * framework id. 19245 * 19246 * @hide 19247 */ 19248 public void setTagInternal(int key, Object tag) { 19249 if ((key >>> 24) != 0x1) { 19250 throw new IllegalArgumentException("The key must be a framework-specific " 19251 + "resource id."); 19252 } 19253 19254 setKeyedTag(key, tag); 19255 } 19256 19257 private void setKeyedTag(int key, Object tag) { 19258 if (mKeyedTags == null) { 19259 mKeyedTags = new SparseArray<Object>(2); 19260 } 19261 19262 mKeyedTags.put(key, tag); 19263 } 19264 19265 /** 19266 * Prints information about this view in the log output, with the tag 19267 * {@link #VIEW_LOG_TAG}. 19268 * 19269 * @hide 19270 */ 19271 public void debug() { 19272 debug(0); 19273 } 19274 19275 /** 19276 * Prints information about this view in the log output, with the tag 19277 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19278 * indentation defined by the <code>depth</code>. 19279 * 19280 * @param depth the indentation level 19281 * 19282 * @hide 19283 */ 19284 protected void debug(int depth) { 19285 String output = debugIndent(depth - 1); 19286 19287 output += "+ " + this; 19288 int id = getId(); 19289 if (id != -1) { 19290 output += " (id=" + id + ")"; 19291 } 19292 Object tag = getTag(); 19293 if (tag != null) { 19294 output += " (tag=" + tag + ")"; 19295 } 19296 Log.d(VIEW_LOG_TAG, output); 19297 19298 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19299 output = debugIndent(depth) + " FOCUSED"; 19300 Log.d(VIEW_LOG_TAG, output); 19301 } 19302 19303 output = debugIndent(depth); 19304 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19305 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19306 + "} "; 19307 Log.d(VIEW_LOG_TAG, output); 19308 19309 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19310 || mPaddingBottom != 0) { 19311 output = debugIndent(depth); 19312 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19313 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19314 Log.d(VIEW_LOG_TAG, output); 19315 } 19316 19317 output = debugIndent(depth); 19318 output += "mMeasureWidth=" + mMeasuredWidth + 19319 " mMeasureHeight=" + mMeasuredHeight; 19320 Log.d(VIEW_LOG_TAG, output); 19321 19322 output = debugIndent(depth); 19323 if (mLayoutParams == null) { 19324 output += "BAD! no layout params"; 19325 } else { 19326 output = mLayoutParams.debug(output); 19327 } 19328 Log.d(VIEW_LOG_TAG, output); 19329 19330 output = debugIndent(depth); 19331 output += "flags={"; 19332 output += View.printFlags(mViewFlags); 19333 output += "}"; 19334 Log.d(VIEW_LOG_TAG, output); 19335 19336 output = debugIndent(depth); 19337 output += "privateFlags={"; 19338 output += View.printPrivateFlags(mPrivateFlags); 19339 output += "}"; 19340 Log.d(VIEW_LOG_TAG, output); 19341 } 19342 19343 /** 19344 * Creates a string of whitespaces used for indentation. 19345 * 19346 * @param depth the indentation level 19347 * @return a String containing (depth * 2 + 3) * 2 white spaces 19348 * 19349 * @hide 19350 */ 19351 protected static String debugIndent(int depth) { 19352 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19353 for (int i = 0; i < (depth * 2) + 3; i++) { 19354 spaces.append(' ').append(' '); 19355 } 19356 return spaces.toString(); 19357 } 19358 19359 /** 19360 * <p>Return the offset of the widget's text baseline from the widget's top 19361 * boundary. If this widget does not support baseline alignment, this 19362 * method returns -1. </p> 19363 * 19364 * @return the offset of the baseline within the widget's bounds or -1 19365 * if baseline alignment is not supported 19366 */ 19367 @ViewDebug.ExportedProperty(category = "layout") 19368 public int getBaseline() { 19369 return -1; 19370 } 19371 19372 /** 19373 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19374 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19375 * a layout pass. 19376 * 19377 * @return whether the view hierarchy is currently undergoing a layout pass 19378 */ 19379 public boolean isInLayout() { 19380 ViewRootImpl viewRoot = getViewRootImpl(); 19381 return (viewRoot != null && viewRoot.isInLayout()); 19382 } 19383 19384 /** 19385 * Call this when something has changed which has invalidated the 19386 * layout of this view. This will schedule a layout pass of the view 19387 * tree. This should not be called while the view hierarchy is currently in a layout 19388 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19389 * end of the current layout pass (and then layout will run again) or after the current 19390 * frame is drawn and the next layout occurs. 19391 * 19392 * <p>Subclasses which override this method should call the superclass method to 19393 * handle possible request-during-layout errors correctly.</p> 19394 */ 19395 @CallSuper 19396 public void requestLayout() { 19397 if (mMeasureCache != null) mMeasureCache.clear(); 19398 19399 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19400 // Only trigger request-during-layout logic if this is the view requesting it, 19401 // not the views in its parent hierarchy 19402 ViewRootImpl viewRoot = getViewRootImpl(); 19403 if (viewRoot != null && viewRoot.isInLayout()) { 19404 if (!viewRoot.requestLayoutDuringLayout(this)) { 19405 return; 19406 } 19407 } 19408 mAttachInfo.mViewRequestingLayout = this; 19409 } 19410 19411 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19412 mPrivateFlags |= PFLAG_INVALIDATED; 19413 19414 if (mParent != null && !mParent.isLayoutRequested()) { 19415 mParent.requestLayout(); 19416 } 19417 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19418 mAttachInfo.mViewRequestingLayout = null; 19419 } 19420 } 19421 19422 /** 19423 * Forces this view to be laid out during the next layout pass. 19424 * This method does not call requestLayout() or forceLayout() 19425 * on the parent. 19426 */ 19427 public void forceLayout() { 19428 if (mMeasureCache != null) mMeasureCache.clear(); 19429 19430 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19431 mPrivateFlags |= PFLAG_INVALIDATED; 19432 } 19433 19434 /** 19435 * <p> 19436 * This is called to find out how big a view should be. The parent 19437 * supplies constraint information in the width and height parameters. 19438 * </p> 19439 * 19440 * <p> 19441 * The actual measurement work of a view is performed in 19442 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19443 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19444 * </p> 19445 * 19446 * 19447 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19448 * parent 19449 * @param heightMeasureSpec Vertical space requirements as imposed by the 19450 * parent 19451 * 19452 * @see #onMeasure(int, int) 19453 */ 19454 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19455 boolean optical = isLayoutModeOptical(this); 19456 if (optical != isLayoutModeOptical(mParent)) { 19457 Insets insets = getOpticalInsets(); 19458 int oWidth = insets.left + insets.right; 19459 int oHeight = insets.top + insets.bottom; 19460 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19461 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19462 } 19463 19464 // Suppress sign extension for the low bytes 19465 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19466 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19467 19468 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19469 19470 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19471 // already measured as the correct size. In API 23 and below, this 19472 // extra pass is required to make LinearLayout re-distribute weight. 19473 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19474 || heightMeasureSpec != mOldHeightMeasureSpec; 19475 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19476 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19477 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19478 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19479 final boolean needsLayout = specChanged 19480 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19481 19482 if (forceLayout || needsLayout) { 19483 // first clears the measured dimension flag 19484 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19485 19486 resolveRtlPropertiesIfNeeded(); 19487 19488 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19489 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19490 // measure ourselves, this should set the measured dimension flag back 19491 onMeasure(widthMeasureSpec, heightMeasureSpec); 19492 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19493 } else { 19494 long value = mMeasureCache.valueAt(cacheIndex); 19495 // Casting a long to int drops the high 32 bits, no mask needed 19496 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19497 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19498 } 19499 19500 // flag not set, setMeasuredDimension() was not invoked, we raise 19501 // an exception to warn the developer 19502 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19503 throw new IllegalStateException("View with id " + getId() + ": " 19504 + getClass().getName() + "#onMeasure() did not set the" 19505 + " measured dimension by calling" 19506 + " setMeasuredDimension()"); 19507 } 19508 19509 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19510 } 19511 19512 mOldWidthMeasureSpec = widthMeasureSpec; 19513 mOldHeightMeasureSpec = heightMeasureSpec; 19514 19515 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19516 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19517 } 19518 19519 /** 19520 * <p> 19521 * Measure the view and its content to determine the measured width and the 19522 * measured height. This method is invoked by {@link #measure(int, int)} and 19523 * should be overridden by subclasses to provide accurate and efficient 19524 * measurement of their contents. 19525 * </p> 19526 * 19527 * <p> 19528 * <strong>CONTRACT:</strong> When overriding this method, you 19529 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19530 * measured width and height of this view. Failure to do so will trigger an 19531 * <code>IllegalStateException</code>, thrown by 19532 * {@link #measure(int, int)}. Calling the superclass' 19533 * {@link #onMeasure(int, int)} is a valid use. 19534 * </p> 19535 * 19536 * <p> 19537 * The base class implementation of measure defaults to the background size, 19538 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19539 * override {@link #onMeasure(int, int)} to provide better measurements of 19540 * their content. 19541 * </p> 19542 * 19543 * <p> 19544 * If this method is overridden, it is the subclass's responsibility to make 19545 * sure the measured height and width are at least the view's minimum height 19546 * and width ({@link #getSuggestedMinimumHeight()} and 19547 * {@link #getSuggestedMinimumWidth()}). 19548 * </p> 19549 * 19550 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19551 * The requirements are encoded with 19552 * {@link android.view.View.MeasureSpec}. 19553 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19554 * The requirements are encoded with 19555 * {@link android.view.View.MeasureSpec}. 19556 * 19557 * @see #getMeasuredWidth() 19558 * @see #getMeasuredHeight() 19559 * @see #setMeasuredDimension(int, int) 19560 * @see #getSuggestedMinimumHeight() 19561 * @see #getSuggestedMinimumWidth() 19562 * @see android.view.View.MeasureSpec#getMode(int) 19563 * @see android.view.View.MeasureSpec#getSize(int) 19564 */ 19565 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19566 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19567 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19568 } 19569 19570 /** 19571 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19572 * measured width and measured height. Failing to do so will trigger an 19573 * exception at measurement time.</p> 19574 * 19575 * @param measuredWidth The measured width of this view. May be a complex 19576 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19577 * {@link #MEASURED_STATE_TOO_SMALL}. 19578 * @param measuredHeight The measured height of this view. May be a complex 19579 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19580 * {@link #MEASURED_STATE_TOO_SMALL}. 19581 */ 19582 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19583 boolean optical = isLayoutModeOptical(this); 19584 if (optical != isLayoutModeOptical(mParent)) { 19585 Insets insets = getOpticalInsets(); 19586 int opticalWidth = insets.left + insets.right; 19587 int opticalHeight = insets.top + insets.bottom; 19588 19589 measuredWidth += optical ? opticalWidth : -opticalWidth; 19590 measuredHeight += optical ? opticalHeight : -opticalHeight; 19591 } 19592 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 19593 } 19594 19595 /** 19596 * Sets the measured dimension without extra processing for things like optical bounds. 19597 * Useful for reapplying consistent values that have already been cooked with adjustments 19598 * for optical bounds, etc. such as those from the measurement cache. 19599 * 19600 * @param measuredWidth The measured width of this view. May be a complex 19601 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19602 * {@link #MEASURED_STATE_TOO_SMALL}. 19603 * @param measuredHeight The measured height of this view. May be a complex 19604 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19605 * {@link #MEASURED_STATE_TOO_SMALL}. 19606 */ 19607 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 19608 mMeasuredWidth = measuredWidth; 19609 mMeasuredHeight = measuredHeight; 19610 19611 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 19612 } 19613 19614 /** 19615 * Merge two states as returned by {@link #getMeasuredState()}. 19616 * @param curState The current state as returned from a view or the result 19617 * of combining multiple views. 19618 * @param newState The new view state to combine. 19619 * @return Returns a new integer reflecting the combination of the two 19620 * states. 19621 */ 19622 public static int combineMeasuredStates(int curState, int newState) { 19623 return curState | newState; 19624 } 19625 19626 /** 19627 * Version of {@link #resolveSizeAndState(int, int, int)} 19628 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 19629 */ 19630 public static int resolveSize(int size, int measureSpec) { 19631 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 19632 } 19633 19634 /** 19635 * Utility to reconcile a desired size and state, with constraints imposed 19636 * by a MeasureSpec. Will take the desired size, unless a different size 19637 * is imposed by the constraints. The returned value is a compound integer, 19638 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 19639 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 19640 * resulting size is smaller than the size the view wants to be. 19641 * 19642 * @param size How big the view wants to be. 19643 * @param measureSpec Constraints imposed by the parent. 19644 * @param childMeasuredState Size information bit mask for the view's 19645 * children. 19646 * @return Size information bit mask as defined by 19647 * {@link #MEASURED_SIZE_MASK} and 19648 * {@link #MEASURED_STATE_TOO_SMALL}. 19649 */ 19650 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 19651 final int specMode = MeasureSpec.getMode(measureSpec); 19652 final int specSize = MeasureSpec.getSize(measureSpec); 19653 final int result; 19654 switch (specMode) { 19655 case MeasureSpec.AT_MOST: 19656 if (specSize < size) { 19657 result = specSize | MEASURED_STATE_TOO_SMALL; 19658 } else { 19659 result = size; 19660 } 19661 break; 19662 case MeasureSpec.EXACTLY: 19663 result = specSize; 19664 break; 19665 case MeasureSpec.UNSPECIFIED: 19666 default: 19667 result = size; 19668 } 19669 return result | (childMeasuredState & MEASURED_STATE_MASK); 19670 } 19671 19672 /** 19673 * Utility to return a default size. Uses the supplied size if the 19674 * MeasureSpec imposed no constraints. Will get larger if allowed 19675 * by the MeasureSpec. 19676 * 19677 * @param size Default size for this view 19678 * @param measureSpec Constraints imposed by the parent 19679 * @return The size this view should be. 19680 */ 19681 public static int getDefaultSize(int size, int measureSpec) { 19682 int result = size; 19683 int specMode = MeasureSpec.getMode(measureSpec); 19684 int specSize = MeasureSpec.getSize(measureSpec); 19685 19686 switch (specMode) { 19687 case MeasureSpec.UNSPECIFIED: 19688 result = size; 19689 break; 19690 case MeasureSpec.AT_MOST: 19691 case MeasureSpec.EXACTLY: 19692 result = specSize; 19693 break; 19694 } 19695 return result; 19696 } 19697 19698 /** 19699 * Returns the suggested minimum height that the view should use. This 19700 * returns the maximum of the view's minimum height 19701 * and the background's minimum height 19702 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 19703 * <p> 19704 * When being used in {@link #onMeasure(int, int)}, the caller should still 19705 * ensure the returned height is within the requirements of the parent. 19706 * 19707 * @return The suggested minimum height of the view. 19708 */ 19709 protected int getSuggestedMinimumHeight() { 19710 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 19711 19712 } 19713 19714 /** 19715 * Returns the suggested minimum width that the view should use. This 19716 * returns the maximum of the view's minimum width 19717 * and the background's minimum width 19718 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 19719 * <p> 19720 * When being used in {@link #onMeasure(int, int)}, the caller should still 19721 * ensure the returned width is within the requirements of the parent. 19722 * 19723 * @return The suggested minimum width of the view. 19724 */ 19725 protected int getSuggestedMinimumWidth() { 19726 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 19727 } 19728 19729 /** 19730 * Returns the minimum height of the view. 19731 * 19732 * @return the minimum height the view will try to be. 19733 * 19734 * @see #setMinimumHeight(int) 19735 * 19736 * @attr ref android.R.styleable#View_minHeight 19737 */ 19738 public int getMinimumHeight() { 19739 return mMinHeight; 19740 } 19741 19742 /** 19743 * Sets the minimum height of the view. It is not guaranteed the view will 19744 * be able to achieve this minimum height (for example, if its parent layout 19745 * constrains it with less available height). 19746 * 19747 * @param minHeight The minimum height the view will try to be. 19748 * 19749 * @see #getMinimumHeight() 19750 * 19751 * @attr ref android.R.styleable#View_minHeight 19752 */ 19753 @RemotableViewMethod 19754 public void setMinimumHeight(int minHeight) { 19755 mMinHeight = minHeight; 19756 requestLayout(); 19757 } 19758 19759 /** 19760 * Returns the minimum width of the view. 19761 * 19762 * @return the minimum width the view will try to be. 19763 * 19764 * @see #setMinimumWidth(int) 19765 * 19766 * @attr ref android.R.styleable#View_minWidth 19767 */ 19768 public int getMinimumWidth() { 19769 return mMinWidth; 19770 } 19771 19772 /** 19773 * Sets the minimum width of the view. It is not guaranteed the view will 19774 * be able to achieve this minimum width (for example, if its parent layout 19775 * constrains it with less available width). 19776 * 19777 * @param minWidth The minimum width the view will try to be. 19778 * 19779 * @see #getMinimumWidth() 19780 * 19781 * @attr ref android.R.styleable#View_minWidth 19782 */ 19783 public void setMinimumWidth(int minWidth) { 19784 mMinWidth = minWidth; 19785 requestLayout(); 19786 19787 } 19788 19789 /** 19790 * Get the animation currently associated with this view. 19791 * 19792 * @return The animation that is currently playing or 19793 * scheduled to play for this view. 19794 */ 19795 public Animation getAnimation() { 19796 return mCurrentAnimation; 19797 } 19798 19799 /** 19800 * Start the specified animation now. 19801 * 19802 * @param animation the animation to start now 19803 */ 19804 public void startAnimation(Animation animation) { 19805 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 19806 setAnimation(animation); 19807 invalidateParentCaches(); 19808 invalidate(true); 19809 } 19810 19811 /** 19812 * Cancels any animations for this view. 19813 */ 19814 public void clearAnimation() { 19815 if (mCurrentAnimation != null) { 19816 mCurrentAnimation.detach(); 19817 } 19818 mCurrentAnimation = null; 19819 invalidateParentIfNeeded(); 19820 } 19821 19822 /** 19823 * Sets the next animation to play for this view. 19824 * If you want the animation to play immediately, use 19825 * {@link #startAnimation(android.view.animation.Animation)} instead. 19826 * This method provides allows fine-grained 19827 * control over the start time and invalidation, but you 19828 * must make sure that 1) the animation has a start time set, and 19829 * 2) the view's parent (which controls animations on its children) 19830 * will be invalidated when the animation is supposed to 19831 * start. 19832 * 19833 * @param animation The next animation, or null. 19834 */ 19835 public void setAnimation(Animation animation) { 19836 mCurrentAnimation = animation; 19837 19838 if (animation != null) { 19839 // If the screen is off assume the animation start time is now instead of 19840 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 19841 // would cause the animation to start when the screen turns back on 19842 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 19843 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 19844 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 19845 } 19846 animation.reset(); 19847 } 19848 } 19849 19850 /** 19851 * Invoked by a parent ViewGroup to notify the start of the animation 19852 * currently associated with this view. If you override this method, 19853 * always call super.onAnimationStart(); 19854 * 19855 * @see #setAnimation(android.view.animation.Animation) 19856 * @see #getAnimation() 19857 */ 19858 @CallSuper 19859 protected void onAnimationStart() { 19860 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 19861 } 19862 19863 /** 19864 * Invoked by a parent ViewGroup to notify the end of the animation 19865 * currently associated with this view. If you override this method, 19866 * always call super.onAnimationEnd(); 19867 * 19868 * @see #setAnimation(android.view.animation.Animation) 19869 * @see #getAnimation() 19870 */ 19871 @CallSuper 19872 protected void onAnimationEnd() { 19873 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 19874 } 19875 19876 /** 19877 * Invoked if there is a Transform that involves alpha. Subclass that can 19878 * draw themselves with the specified alpha should return true, and then 19879 * respect that alpha when their onDraw() is called. If this returns false 19880 * then the view may be redirected to draw into an offscreen buffer to 19881 * fulfill the request, which will look fine, but may be slower than if the 19882 * subclass handles it internally. The default implementation returns false. 19883 * 19884 * @param alpha The alpha (0..255) to apply to the view's drawing 19885 * @return true if the view can draw with the specified alpha. 19886 */ 19887 protected boolean onSetAlpha(int alpha) { 19888 return false; 19889 } 19890 19891 /** 19892 * This is used by the RootView to perform an optimization when 19893 * the view hierarchy contains one or several SurfaceView. 19894 * SurfaceView is always considered transparent, but its children are not, 19895 * therefore all View objects remove themselves from the global transparent 19896 * region (passed as a parameter to this function). 19897 * 19898 * @param region The transparent region for this ViewAncestor (window). 19899 * 19900 * @return Returns true if the effective visibility of the view at this 19901 * point is opaque, regardless of the transparent region; returns false 19902 * if it is possible for underlying windows to be seen behind the view. 19903 * 19904 * {@hide} 19905 */ 19906 public boolean gatherTransparentRegion(Region region) { 19907 final AttachInfo attachInfo = mAttachInfo; 19908 if (region != null && attachInfo != null) { 19909 final int pflags = mPrivateFlags; 19910 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 19911 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 19912 // remove it from the transparent region. 19913 final int[] location = attachInfo.mTransparentLocation; 19914 getLocationInWindow(location); 19915 region.op(location[0], location[1], location[0] + mRight - mLeft, 19916 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 19917 } else { 19918 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 19919 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 19920 // the background drawable's non-transparent parts from this transparent region. 19921 applyDrawableToTransparentRegion(mBackground, region); 19922 } 19923 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 19924 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 19925 // Similarly, we remove the foreground drawable's non-transparent parts. 19926 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 19927 } 19928 } 19929 } 19930 return true; 19931 } 19932 19933 /** 19934 * Play a sound effect for this view. 19935 * 19936 * <p>The framework will play sound effects for some built in actions, such as 19937 * clicking, but you may wish to play these effects in your widget, 19938 * for instance, for internal navigation. 19939 * 19940 * <p>The sound effect will only be played if sound effects are enabled by the user, and 19941 * {@link #isSoundEffectsEnabled()} is true. 19942 * 19943 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 19944 */ 19945 public void playSoundEffect(int soundConstant) { 19946 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 19947 return; 19948 } 19949 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 19950 } 19951 19952 /** 19953 * BZZZTT!!1! 19954 * 19955 * <p>Provide haptic feedback to the user for this view. 19956 * 19957 * <p>The framework will provide haptic feedback for some built in actions, 19958 * such as long presses, but you may wish to provide feedback for your 19959 * own widget. 19960 * 19961 * <p>The feedback will only be performed if 19962 * {@link #isHapticFeedbackEnabled()} is true. 19963 * 19964 * @param feedbackConstant One of the constants defined in 19965 * {@link HapticFeedbackConstants} 19966 */ 19967 public boolean performHapticFeedback(int feedbackConstant) { 19968 return performHapticFeedback(feedbackConstant, 0); 19969 } 19970 19971 /** 19972 * BZZZTT!!1! 19973 * 19974 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 19975 * 19976 * @param feedbackConstant One of the constants defined in 19977 * {@link HapticFeedbackConstants} 19978 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 19979 */ 19980 public boolean performHapticFeedback(int feedbackConstant, int flags) { 19981 if (mAttachInfo == null) { 19982 return false; 19983 } 19984 //noinspection SimplifiableIfStatement 19985 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 19986 && !isHapticFeedbackEnabled()) { 19987 return false; 19988 } 19989 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 19990 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 19991 } 19992 19993 /** 19994 * Request that the visibility of the status bar or other screen/window 19995 * decorations be changed. 19996 * 19997 * <p>This method is used to put the over device UI into temporary modes 19998 * where the user's attention is focused more on the application content, 19999 * by dimming or hiding surrounding system affordances. This is typically 20000 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20001 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20002 * to be placed behind the action bar (and with these flags other system 20003 * affordances) so that smooth transitions between hiding and showing them 20004 * can be done. 20005 * 20006 * <p>Two representative examples of the use of system UI visibility is 20007 * implementing a content browsing application (like a magazine reader) 20008 * and a video playing application. 20009 * 20010 * <p>The first code shows a typical implementation of a View in a content 20011 * browsing application. In this implementation, the application goes 20012 * into a content-oriented mode by hiding the status bar and action bar, 20013 * and putting the navigation elements into lights out mode. The user can 20014 * then interact with content while in this mode. Such an application should 20015 * provide an easy way for the user to toggle out of the mode (such as to 20016 * check information in the status bar or access notifications). In the 20017 * implementation here, this is done simply by tapping on the content. 20018 * 20019 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20020 * content} 20021 * 20022 * <p>This second code sample shows a typical implementation of a View 20023 * in a video playing application. In this situation, while the video is 20024 * playing the application would like to go into a complete full-screen mode, 20025 * to use as much of the display as possible for the video. When in this state 20026 * the user can not interact with the application; the system intercepts 20027 * touching on the screen to pop the UI out of full screen mode. See 20028 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20029 * 20030 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20031 * content} 20032 * 20033 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20034 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20035 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20036 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20037 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20038 */ 20039 public void setSystemUiVisibility(int visibility) { 20040 if (visibility != mSystemUiVisibility) { 20041 mSystemUiVisibility = visibility; 20042 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20043 mParent.recomputeViewAttributes(this); 20044 } 20045 } 20046 } 20047 20048 /** 20049 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20050 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20051 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20052 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20053 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20054 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20055 */ 20056 public int getSystemUiVisibility() { 20057 return mSystemUiVisibility; 20058 } 20059 20060 /** 20061 * Returns the current system UI visibility that is currently set for 20062 * the entire window. This is the combination of the 20063 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20064 * views in the window. 20065 */ 20066 public int getWindowSystemUiVisibility() { 20067 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20068 } 20069 20070 /** 20071 * Override to find out when the window's requested system UI visibility 20072 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20073 * This is different from the callbacks received through 20074 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20075 * in that this is only telling you about the local request of the window, 20076 * not the actual values applied by the system. 20077 */ 20078 public void onWindowSystemUiVisibilityChanged(int visible) { 20079 } 20080 20081 /** 20082 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20083 * the view hierarchy. 20084 */ 20085 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20086 onWindowSystemUiVisibilityChanged(visible); 20087 } 20088 20089 /** 20090 * Set a listener to receive callbacks when the visibility of the system bar changes. 20091 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20092 */ 20093 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20094 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20095 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20096 mParent.recomputeViewAttributes(this); 20097 } 20098 } 20099 20100 /** 20101 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20102 * the view hierarchy. 20103 */ 20104 public void dispatchSystemUiVisibilityChanged(int visibility) { 20105 ListenerInfo li = mListenerInfo; 20106 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20107 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20108 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20109 } 20110 } 20111 20112 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20113 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20114 if (val != mSystemUiVisibility) { 20115 setSystemUiVisibility(val); 20116 return true; 20117 } 20118 return false; 20119 } 20120 20121 /** @hide */ 20122 public void setDisabledSystemUiVisibility(int flags) { 20123 if (mAttachInfo != null) { 20124 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20125 mAttachInfo.mDisabledSystemUiVisibility = flags; 20126 if (mParent != null) { 20127 mParent.recomputeViewAttributes(this); 20128 } 20129 } 20130 } 20131 } 20132 20133 /** 20134 * Creates an image that the system displays during the drag and drop 20135 * operation. This is called a "drag shadow". The default implementation 20136 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20137 * appearance as the given View. The default also positions the center of the drag shadow 20138 * directly under the touch point. If no View is provided (the constructor with no parameters 20139 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20140 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20141 * default is an invisible drag shadow. 20142 * <p> 20143 * You are not required to use the View you provide to the constructor as the basis of the 20144 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20145 * anything you want as the drag shadow. 20146 * </p> 20147 * <p> 20148 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20149 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20150 * size and position of the drag shadow. It uses this data to construct a 20151 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20152 * so that your application can draw the shadow image in the Canvas. 20153 * </p> 20154 * 20155 * <div class="special reference"> 20156 * <h3>Developer Guides</h3> 20157 * <p>For a guide to implementing drag and drop features, read the 20158 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20159 * </div> 20160 */ 20161 public static class DragShadowBuilder { 20162 private final WeakReference<View> mView; 20163 20164 /** 20165 * Constructs a shadow image builder based on a View. By default, the resulting drag 20166 * shadow will have the same appearance and dimensions as the View, with the touch point 20167 * over the center of the View. 20168 * @param view A View. Any View in scope can be used. 20169 */ 20170 public DragShadowBuilder(View view) { 20171 mView = new WeakReference<View>(view); 20172 } 20173 20174 /** 20175 * Construct a shadow builder object with no associated View. This 20176 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20177 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20178 * to supply the drag shadow's dimensions and appearance without 20179 * reference to any View object. If they are not overridden, then the result is an 20180 * invisible drag shadow. 20181 */ 20182 public DragShadowBuilder() { 20183 mView = new WeakReference<View>(null); 20184 } 20185 20186 /** 20187 * Returns the View object that had been passed to the 20188 * {@link #View.DragShadowBuilder(View)} 20189 * constructor. If that View parameter was {@code null} or if the 20190 * {@link #View.DragShadowBuilder()} 20191 * constructor was used to instantiate the builder object, this method will return 20192 * null. 20193 * 20194 * @return The View object associate with this builder object. 20195 */ 20196 @SuppressWarnings({"JavadocReference"}) 20197 final public View getView() { 20198 return mView.get(); 20199 } 20200 20201 /** 20202 * Provides the metrics for the shadow image. These include the dimensions of 20203 * the shadow image, and the point within that shadow that should 20204 * be centered under the touch location while dragging. 20205 * <p> 20206 * The default implementation sets the dimensions of the shadow to be the 20207 * same as the dimensions of the View itself and centers the shadow under 20208 * the touch point. 20209 * </p> 20210 * 20211 * @param shadowSize A {@link android.graphics.Point} containing the width and height 20212 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20213 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20214 * image. 20215 * 20216 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 20217 * shadow image that should be underneath the touch point during the drag and drop 20218 * operation. Your application must set {@link android.graphics.Point#x} to the 20219 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20220 */ 20221 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 20222 final View view = mView.get(); 20223 if (view != null) { 20224 shadowSize.set(view.getWidth(), view.getHeight()); 20225 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 20226 } else { 20227 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20228 } 20229 } 20230 20231 /** 20232 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20233 * based on the dimensions it received from the 20234 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20235 * 20236 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20237 */ 20238 public void onDrawShadow(Canvas canvas) { 20239 final View view = mView.get(); 20240 if (view != null) { 20241 view.draw(canvas); 20242 } else { 20243 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20244 } 20245 } 20246 } 20247 20248 /** 20249 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20250 * startDragAndDrop()} for newer platform versions. 20251 */ 20252 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20253 Object myLocalState, int flags) { 20254 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20255 } 20256 20257 /** 20258 * Starts a drag and drop operation. When your application calls this method, it passes a 20259 * {@link android.view.View.DragShadowBuilder} object to the system. The 20260 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20261 * to get metrics for the drag shadow, and then calls the object's 20262 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20263 * <p> 20264 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20265 * drag events to all the View objects in your application that are currently visible. It does 20266 * this either by calling the View object's drag listener (an implementation of 20267 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20268 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20269 * Both are passed a {@link android.view.DragEvent} object that has a 20270 * {@link android.view.DragEvent#getAction()} value of 20271 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20272 * </p> 20273 * <p> 20274 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20275 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20276 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20277 * to the View the user selected for dragging. 20278 * </p> 20279 * @param data A {@link android.content.ClipData} object pointing to the data to be 20280 * transferred by the drag and drop operation. 20281 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20282 * drag shadow. 20283 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20284 * drop operation. This Object is put into every DragEvent object sent by the system during the 20285 * current drag. 20286 * <p> 20287 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20288 * to the target Views. For example, it can contain flags that differentiate between a 20289 * a copy operation and a move operation. 20290 * </p> 20291 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 20292 * so the parameter should be set to 0. 20293 * @return {@code true} if the method completes successfully, or 20294 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20295 * do a drag, and so no drag operation is in progress. 20296 */ 20297 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20298 Object myLocalState, int flags) { 20299 if (ViewDebug.DEBUG_DRAG) { 20300 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20301 } 20302 boolean okay = false; 20303 20304 Point shadowSize = new Point(); 20305 Point shadowTouchPoint = new Point(); 20306 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20307 20308 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20309 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20310 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20311 } 20312 20313 if (ViewDebug.DEBUG_DRAG) { 20314 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20315 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20316 } 20317 if (mAttachInfo.mDragSurface != null) { 20318 mAttachInfo.mDragSurface.release(); 20319 } 20320 mAttachInfo.mDragSurface = new Surface(); 20321 try { 20322 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20323 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20324 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20325 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20326 if (mAttachInfo.mDragToken != null) { 20327 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20328 try { 20329 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20330 shadowBuilder.onDrawShadow(canvas); 20331 } finally { 20332 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20333 } 20334 20335 final ViewRootImpl root = getViewRootImpl(); 20336 20337 // Cache the local state object for delivery with DragEvents 20338 root.setLocalDragState(myLocalState); 20339 20340 // repurpose 'shadowSize' for the last touch point 20341 root.getLastTouchPoint(shadowSize); 20342 20343 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20344 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20345 shadowTouchPoint.x, shadowTouchPoint.y, data); 20346 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20347 } 20348 } catch (Exception e) { 20349 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20350 mAttachInfo.mDragSurface.destroy(); 20351 mAttachInfo.mDragSurface = null; 20352 } 20353 20354 return okay; 20355 } 20356 20357 /** 20358 * Cancels an ongoing drag and drop operation. 20359 * <p> 20360 * A {@link android.view.DragEvent} object with 20361 * {@link android.view.DragEvent#getAction()} value of 20362 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20363 * {@link android.view.DragEvent#getResult()} value of {@code false} 20364 * will be sent to every 20365 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20366 * even if they are not currently visible. 20367 * </p> 20368 * <p> 20369 * This method can be called on any View in the same window as the View on which 20370 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20371 * was called. 20372 * </p> 20373 */ 20374 public final void cancelDragAndDrop() { 20375 if (ViewDebug.DEBUG_DRAG) { 20376 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20377 } 20378 if (mAttachInfo.mDragToken != null) { 20379 try { 20380 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20381 } catch (Exception e) { 20382 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20383 } 20384 mAttachInfo.mDragToken = null; 20385 } else { 20386 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20387 } 20388 } 20389 20390 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20391 if (ViewDebug.DEBUG_DRAG) { 20392 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20393 } 20394 if (mAttachInfo.mDragToken != null) { 20395 try { 20396 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20397 try { 20398 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20399 shadowBuilder.onDrawShadow(canvas); 20400 } finally { 20401 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20402 } 20403 } catch (Exception e) { 20404 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20405 } 20406 } else { 20407 Log.e(VIEW_LOG_TAG, "No active drag"); 20408 } 20409 } 20410 20411 /** 20412 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20413 * between {startX, startY} and the new cursor positon. 20414 * @param startX horizontal coordinate where the move started. 20415 * @param startY vertical coordinate where the move started. 20416 * @return whether moving was started successfully. 20417 * @hide 20418 */ 20419 public final boolean startMovingTask(float startX, float startY) { 20420 if (ViewDebug.DEBUG_POSITIONING) { 20421 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20422 } 20423 try { 20424 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20425 } catch (RemoteException e) { 20426 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20427 } 20428 return false; 20429 } 20430 20431 /** 20432 * Handles drag events sent by the system following a call to 20433 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20434 * startDragAndDrop()}. 20435 *<p> 20436 * When the system calls this method, it passes a 20437 * {@link android.view.DragEvent} object. A call to 20438 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20439 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20440 * operation. 20441 * @param event The {@link android.view.DragEvent} sent by the system. 20442 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20443 * in DragEvent, indicating the type of drag event represented by this object. 20444 * @return {@code true} if the method was successful, otherwise {@code false}. 20445 * <p> 20446 * The method should return {@code true} in response to an action type of 20447 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20448 * operation. 20449 * </p> 20450 * <p> 20451 * The method should also return {@code true} in response to an action type of 20452 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20453 * {@code false} if it didn't. 20454 * </p> 20455 */ 20456 public boolean onDragEvent(DragEvent event) { 20457 return false; 20458 } 20459 20460 /** 20461 * Detects if this View is enabled and has a drag event listener. 20462 * If both are true, then it calls the drag event listener with the 20463 * {@link android.view.DragEvent} it received. If the drag event listener returns 20464 * {@code true}, then dispatchDragEvent() returns {@code true}. 20465 * <p> 20466 * For all other cases, the method calls the 20467 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20468 * method and returns its result. 20469 * </p> 20470 * <p> 20471 * This ensures that a drag event is always consumed, even if the View does not have a drag 20472 * event listener. However, if the View has a listener and the listener returns true, then 20473 * onDragEvent() is not called. 20474 * </p> 20475 */ 20476 public boolean dispatchDragEvent(DragEvent event) { 20477 ListenerInfo li = mListenerInfo; 20478 //noinspection SimplifiableIfStatement 20479 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20480 && li.mOnDragListener.onDrag(this, event)) { 20481 return true; 20482 } 20483 return onDragEvent(event); 20484 } 20485 20486 boolean canAcceptDrag() { 20487 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20488 } 20489 20490 /** 20491 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20492 * it is ever exposed at all. 20493 * @hide 20494 */ 20495 public void onCloseSystemDialogs(String reason) { 20496 } 20497 20498 /** 20499 * Given a Drawable whose bounds have been set to draw into this view, 20500 * update a Region being computed for 20501 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20502 * that any non-transparent parts of the Drawable are removed from the 20503 * given transparent region. 20504 * 20505 * @param dr The Drawable whose transparency is to be applied to the region. 20506 * @param region A Region holding the current transparency information, 20507 * where any parts of the region that are set are considered to be 20508 * transparent. On return, this region will be modified to have the 20509 * transparency information reduced by the corresponding parts of the 20510 * Drawable that are not transparent. 20511 * {@hide} 20512 */ 20513 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 20514 if (DBG) { 20515 Log.i("View", "Getting transparent region for: " + this); 20516 } 20517 final Region r = dr.getTransparentRegion(); 20518 final Rect db = dr.getBounds(); 20519 final AttachInfo attachInfo = mAttachInfo; 20520 if (r != null && attachInfo != null) { 20521 final int w = getRight()-getLeft(); 20522 final int h = getBottom()-getTop(); 20523 if (db.left > 0) { 20524 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 20525 r.op(0, 0, db.left, h, Region.Op.UNION); 20526 } 20527 if (db.right < w) { 20528 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 20529 r.op(db.right, 0, w, h, Region.Op.UNION); 20530 } 20531 if (db.top > 0) { 20532 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 20533 r.op(0, 0, w, db.top, Region.Op.UNION); 20534 } 20535 if (db.bottom < h) { 20536 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 20537 r.op(0, db.bottom, w, h, Region.Op.UNION); 20538 } 20539 final int[] location = attachInfo.mTransparentLocation; 20540 getLocationInWindow(location); 20541 r.translate(location[0], location[1]); 20542 region.op(r, Region.Op.INTERSECT); 20543 } else { 20544 region.op(db, Region.Op.DIFFERENCE); 20545 } 20546 } 20547 20548 private void checkForLongClick(int delayOffset, float x, float y) { 20549 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 20550 mHasPerformedLongPress = false; 20551 20552 if (mPendingCheckForLongPress == null) { 20553 mPendingCheckForLongPress = new CheckForLongPress(); 20554 } 20555 mPendingCheckForLongPress.setAnchor(x, y); 20556 mPendingCheckForLongPress.rememberWindowAttachCount(); 20557 postDelayed(mPendingCheckForLongPress, 20558 ViewConfiguration.getLongPressTimeout() - delayOffset); 20559 } 20560 } 20561 20562 /** 20563 * Inflate a view from an XML resource. This convenience method wraps the {@link 20564 * LayoutInflater} class, which provides a full range of options for view inflation. 20565 * 20566 * @param context The Context object for your activity or application. 20567 * @param resource The resource ID to inflate 20568 * @param root A view group that will be the parent. Used to properly inflate the 20569 * layout_* parameters. 20570 * @see LayoutInflater 20571 */ 20572 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 20573 LayoutInflater factory = LayoutInflater.from(context); 20574 return factory.inflate(resource, root); 20575 } 20576 20577 /** 20578 * Scroll the view with standard behavior for scrolling beyond the normal 20579 * content boundaries. Views that call this method should override 20580 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 20581 * results of an over-scroll operation. 20582 * 20583 * Views can use this method to handle any touch or fling-based scrolling. 20584 * 20585 * @param deltaX Change in X in pixels 20586 * @param deltaY Change in Y in pixels 20587 * @param scrollX Current X scroll value in pixels before applying deltaX 20588 * @param scrollY Current Y scroll value in pixels before applying deltaY 20589 * @param scrollRangeX Maximum content scroll range along the X axis 20590 * @param scrollRangeY Maximum content scroll range along the Y axis 20591 * @param maxOverScrollX Number of pixels to overscroll by in either direction 20592 * along the X axis. 20593 * @param maxOverScrollY Number of pixels to overscroll by in either direction 20594 * along the Y axis. 20595 * @param isTouchEvent true if this scroll operation is the result of a touch event. 20596 * @return true if scrolling was clamped to an over-scroll boundary along either 20597 * axis, false otherwise. 20598 */ 20599 @SuppressWarnings({"UnusedParameters"}) 20600 protected boolean overScrollBy(int deltaX, int deltaY, 20601 int scrollX, int scrollY, 20602 int scrollRangeX, int scrollRangeY, 20603 int maxOverScrollX, int maxOverScrollY, 20604 boolean isTouchEvent) { 20605 final int overScrollMode = mOverScrollMode; 20606 final boolean canScrollHorizontal = 20607 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 20608 final boolean canScrollVertical = 20609 computeVerticalScrollRange() > computeVerticalScrollExtent(); 20610 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 20611 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 20612 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 20613 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 20614 20615 int newScrollX = scrollX + deltaX; 20616 if (!overScrollHorizontal) { 20617 maxOverScrollX = 0; 20618 } 20619 20620 int newScrollY = scrollY + deltaY; 20621 if (!overScrollVertical) { 20622 maxOverScrollY = 0; 20623 } 20624 20625 // Clamp values if at the limits and record 20626 final int left = -maxOverScrollX; 20627 final int right = maxOverScrollX + scrollRangeX; 20628 final int top = -maxOverScrollY; 20629 final int bottom = maxOverScrollY + scrollRangeY; 20630 20631 boolean clampedX = false; 20632 if (newScrollX > right) { 20633 newScrollX = right; 20634 clampedX = true; 20635 } else if (newScrollX < left) { 20636 newScrollX = left; 20637 clampedX = true; 20638 } 20639 20640 boolean clampedY = false; 20641 if (newScrollY > bottom) { 20642 newScrollY = bottom; 20643 clampedY = true; 20644 } else if (newScrollY < top) { 20645 newScrollY = top; 20646 clampedY = true; 20647 } 20648 20649 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 20650 20651 return clampedX || clampedY; 20652 } 20653 20654 /** 20655 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 20656 * respond to the results of an over-scroll operation. 20657 * 20658 * @param scrollX New X scroll value in pixels 20659 * @param scrollY New Y scroll value in pixels 20660 * @param clampedX True if scrollX was clamped to an over-scroll boundary 20661 * @param clampedY True if scrollY was clamped to an over-scroll boundary 20662 */ 20663 protected void onOverScrolled(int scrollX, int scrollY, 20664 boolean clampedX, boolean clampedY) { 20665 // Intentionally empty. 20666 } 20667 20668 /** 20669 * Returns the over-scroll mode for this view. The result will be 20670 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20671 * (allow over-scrolling only if the view content is larger than the container), 20672 * or {@link #OVER_SCROLL_NEVER}. 20673 * 20674 * @return This view's over-scroll mode. 20675 */ 20676 public int getOverScrollMode() { 20677 return mOverScrollMode; 20678 } 20679 20680 /** 20681 * Set the over-scroll mode for this view. Valid over-scroll modes are 20682 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20683 * (allow over-scrolling only if the view content is larger than the container), 20684 * or {@link #OVER_SCROLL_NEVER}. 20685 * 20686 * Setting the over-scroll mode of a view will have an effect only if the 20687 * view is capable of scrolling. 20688 * 20689 * @param overScrollMode The new over-scroll mode for this view. 20690 */ 20691 public void setOverScrollMode(int overScrollMode) { 20692 if (overScrollMode != OVER_SCROLL_ALWAYS && 20693 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 20694 overScrollMode != OVER_SCROLL_NEVER) { 20695 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 20696 } 20697 mOverScrollMode = overScrollMode; 20698 } 20699 20700 /** 20701 * Enable or disable nested scrolling for this view. 20702 * 20703 * <p>If this property is set to true the view will be permitted to initiate nested 20704 * scrolling operations with a compatible parent view in the current hierarchy. If this 20705 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 20706 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 20707 * the nested scroll.</p> 20708 * 20709 * @param enabled true to enable nested scrolling, false to disable 20710 * 20711 * @see #isNestedScrollingEnabled() 20712 */ 20713 public void setNestedScrollingEnabled(boolean enabled) { 20714 if (enabled) { 20715 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 20716 } else { 20717 stopNestedScroll(); 20718 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 20719 } 20720 } 20721 20722 /** 20723 * Returns true if nested scrolling is enabled for this view. 20724 * 20725 * <p>If nested scrolling is enabled and this View class implementation supports it, 20726 * this view will act as a nested scrolling child view when applicable, forwarding data 20727 * about the scroll operation in progress to a compatible and cooperating nested scrolling 20728 * parent.</p> 20729 * 20730 * @return true if nested scrolling is enabled 20731 * 20732 * @see #setNestedScrollingEnabled(boolean) 20733 */ 20734 public boolean isNestedScrollingEnabled() { 20735 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 20736 PFLAG3_NESTED_SCROLLING_ENABLED; 20737 } 20738 20739 /** 20740 * Begin a nestable scroll operation along the given axes. 20741 * 20742 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 20743 * 20744 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 20745 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 20746 * In the case of touch scrolling the nested scroll will be terminated automatically in 20747 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 20748 * In the event of programmatic scrolling the caller must explicitly call 20749 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 20750 * 20751 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 20752 * If it returns false the caller may ignore the rest of this contract until the next scroll. 20753 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 20754 * 20755 * <p>At each incremental step of the scroll the caller should invoke 20756 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 20757 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 20758 * parent at least partially consumed the scroll and the caller should adjust the amount it 20759 * scrolls by.</p> 20760 * 20761 * <p>After applying the remainder of the scroll delta the caller should invoke 20762 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 20763 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 20764 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 20765 * </p> 20766 * 20767 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 20768 * {@link #SCROLL_AXIS_VERTICAL}. 20769 * @return true if a cooperative parent was found and nested scrolling has been enabled for 20770 * the current gesture. 20771 * 20772 * @see #stopNestedScroll() 20773 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 20774 * @see #dispatchNestedScroll(int, int, int, int, int[]) 20775 */ 20776 public boolean startNestedScroll(int axes) { 20777 if (hasNestedScrollingParent()) { 20778 // Already in progress 20779 return true; 20780 } 20781 if (isNestedScrollingEnabled()) { 20782 ViewParent p = getParent(); 20783 View child = this; 20784 while (p != null) { 20785 try { 20786 if (p.onStartNestedScroll(child, this, axes)) { 20787 mNestedScrollingParent = p; 20788 p.onNestedScrollAccepted(child, this, axes); 20789 return true; 20790 } 20791 } catch (AbstractMethodError e) { 20792 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 20793 "method onStartNestedScroll", e); 20794 // Allow the search upward to continue 20795 } 20796 if (p instanceof View) { 20797 child = (View) p; 20798 } 20799 p = p.getParent(); 20800 } 20801 } 20802 return false; 20803 } 20804 20805 /** 20806 * Stop a nested scroll in progress. 20807 * 20808 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 20809 * 20810 * @see #startNestedScroll(int) 20811 */ 20812 public void stopNestedScroll() { 20813 if (mNestedScrollingParent != null) { 20814 mNestedScrollingParent.onStopNestedScroll(this); 20815 mNestedScrollingParent = null; 20816 } 20817 } 20818 20819 /** 20820 * Returns true if this view has a nested scrolling parent. 20821 * 20822 * <p>The presence of a nested scrolling parent indicates that this view has initiated 20823 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 20824 * 20825 * @return whether this view has a nested scrolling parent 20826 */ 20827 public boolean hasNestedScrollingParent() { 20828 return mNestedScrollingParent != null; 20829 } 20830 20831 /** 20832 * Dispatch one step of a nested scroll in progress. 20833 * 20834 * <p>Implementations of views that support nested scrolling should call this to report 20835 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 20836 * is not currently in progress or nested scrolling is not 20837 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 20838 * 20839 * <p>Compatible View implementations should also call 20840 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 20841 * consuming a component of the scroll event themselves.</p> 20842 * 20843 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 20844 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 20845 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 20846 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 20847 * @param offsetInWindow Optional. If not null, on return this will contain the offset 20848 * in local view coordinates of this view from before this operation 20849 * to after it completes. View implementations may use this to adjust 20850 * expected input coordinate tracking. 20851 * @return true if the event was dispatched, false if it could not be dispatched. 20852 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 20853 */ 20854 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 20855 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 20856 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20857 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 20858 int startX = 0; 20859 int startY = 0; 20860 if (offsetInWindow != null) { 20861 getLocationInWindow(offsetInWindow); 20862 startX = offsetInWindow[0]; 20863 startY = offsetInWindow[1]; 20864 } 20865 20866 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 20867 dxUnconsumed, dyUnconsumed); 20868 20869 if (offsetInWindow != null) { 20870 getLocationInWindow(offsetInWindow); 20871 offsetInWindow[0] -= startX; 20872 offsetInWindow[1] -= startY; 20873 } 20874 return true; 20875 } else if (offsetInWindow != null) { 20876 // No motion, no dispatch. Keep offsetInWindow up to date. 20877 offsetInWindow[0] = 0; 20878 offsetInWindow[1] = 0; 20879 } 20880 } 20881 return false; 20882 } 20883 20884 /** 20885 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 20886 * 20887 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 20888 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 20889 * scrolling operation to consume some or all of the scroll operation before the child view 20890 * consumes it.</p> 20891 * 20892 * @param dx Horizontal scroll distance in pixels 20893 * @param dy Vertical scroll distance in pixels 20894 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 20895 * and consumed[1] the consumed dy. 20896 * @param offsetInWindow Optional. If not null, on return this will contain the offset 20897 * in local view coordinates of this view from before this operation 20898 * to after it completes. View implementations may use this to adjust 20899 * expected input coordinate tracking. 20900 * @return true if the parent consumed some or all of the scroll delta 20901 * @see #dispatchNestedScroll(int, int, int, int, int[]) 20902 */ 20903 public boolean dispatchNestedPreScroll(int dx, int dy, 20904 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 20905 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20906 if (dx != 0 || dy != 0) { 20907 int startX = 0; 20908 int startY = 0; 20909 if (offsetInWindow != null) { 20910 getLocationInWindow(offsetInWindow); 20911 startX = offsetInWindow[0]; 20912 startY = offsetInWindow[1]; 20913 } 20914 20915 if (consumed == null) { 20916 if (mTempNestedScrollConsumed == null) { 20917 mTempNestedScrollConsumed = new int[2]; 20918 } 20919 consumed = mTempNestedScrollConsumed; 20920 } 20921 consumed[0] = 0; 20922 consumed[1] = 0; 20923 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 20924 20925 if (offsetInWindow != null) { 20926 getLocationInWindow(offsetInWindow); 20927 offsetInWindow[0] -= startX; 20928 offsetInWindow[1] -= startY; 20929 } 20930 return consumed[0] != 0 || consumed[1] != 0; 20931 } else if (offsetInWindow != null) { 20932 offsetInWindow[0] = 0; 20933 offsetInWindow[1] = 0; 20934 } 20935 } 20936 return false; 20937 } 20938 20939 /** 20940 * Dispatch a fling to a nested scrolling parent. 20941 * 20942 * <p>This method should be used to indicate that a nested scrolling child has detected 20943 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 20944 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 20945 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 20946 * along a scrollable axis.</p> 20947 * 20948 * <p>If a nested scrolling child view would normally fling but it is at the edge of 20949 * its own content, it can use this method to delegate the fling to its nested scrolling 20950 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 20951 * 20952 * @param velocityX Horizontal fling velocity in pixels per second 20953 * @param velocityY Vertical fling velocity in pixels per second 20954 * @param consumed true if the child consumed the fling, false otherwise 20955 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 20956 */ 20957 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 20958 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20959 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 20960 } 20961 return false; 20962 } 20963 20964 /** 20965 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 20966 * 20967 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 20968 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 20969 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 20970 * before the child view consumes it. If this method returns <code>true</code>, a nested 20971 * parent view consumed the fling and this view should not scroll as a result.</p> 20972 * 20973 * <p>For a better user experience, only one view in a nested scrolling chain should consume 20974 * the fling at a time. If a parent view consumed the fling this method will return false. 20975 * Custom view implementations should account for this in two ways:</p> 20976 * 20977 * <ul> 20978 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 20979 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 20980 * position regardless.</li> 20981 * <li>If a nested parent does consume the fling, this view should not scroll at all, 20982 * even to settle back to a valid idle position.</li> 20983 * </ul> 20984 * 20985 * <p>Views should also not offer fling velocities to nested parent views along an axis 20986 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 20987 * should not offer a horizontal fling velocity to its parents since scrolling along that 20988 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 20989 * 20990 * @param velocityX Horizontal fling velocity in pixels per second 20991 * @param velocityY Vertical fling velocity in pixels per second 20992 * @return true if a nested scrolling parent consumed the fling 20993 */ 20994 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 20995 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20996 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 20997 } 20998 return false; 20999 } 21000 21001 /** 21002 * Gets a scale factor that determines the distance the view should scroll 21003 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21004 * @return The vertical scroll scale factor. 21005 * @hide 21006 */ 21007 protected float getVerticalScrollFactor() { 21008 if (mVerticalScrollFactor == 0) { 21009 TypedValue outValue = new TypedValue(); 21010 if (!mContext.getTheme().resolveAttribute( 21011 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21012 throw new IllegalStateException( 21013 "Expected theme to define listPreferredItemHeight."); 21014 } 21015 mVerticalScrollFactor = outValue.getDimension( 21016 mContext.getResources().getDisplayMetrics()); 21017 } 21018 return mVerticalScrollFactor; 21019 } 21020 21021 /** 21022 * Gets a scale factor that determines the distance the view should scroll 21023 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21024 * @return The horizontal scroll scale factor. 21025 * @hide 21026 */ 21027 protected float getHorizontalScrollFactor() { 21028 // TODO: Should use something else. 21029 return getVerticalScrollFactor(); 21030 } 21031 21032 /** 21033 * Return the value specifying the text direction or policy that was set with 21034 * {@link #setTextDirection(int)}. 21035 * 21036 * @return the defined text direction. It can be one of: 21037 * 21038 * {@link #TEXT_DIRECTION_INHERIT}, 21039 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21040 * {@link #TEXT_DIRECTION_ANY_RTL}, 21041 * {@link #TEXT_DIRECTION_LTR}, 21042 * {@link #TEXT_DIRECTION_RTL}, 21043 * {@link #TEXT_DIRECTION_LOCALE}, 21044 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21045 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21046 * 21047 * @attr ref android.R.styleable#View_textDirection 21048 * 21049 * @hide 21050 */ 21051 @ViewDebug.ExportedProperty(category = "text", mapping = { 21052 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21053 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21054 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21055 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21056 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21057 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21058 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21059 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21060 }) 21061 public int getRawTextDirection() { 21062 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21063 } 21064 21065 /** 21066 * Set the text direction. 21067 * 21068 * @param textDirection the direction to set. Should be one of: 21069 * 21070 * {@link #TEXT_DIRECTION_INHERIT}, 21071 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21072 * {@link #TEXT_DIRECTION_ANY_RTL}, 21073 * {@link #TEXT_DIRECTION_LTR}, 21074 * {@link #TEXT_DIRECTION_RTL}, 21075 * {@link #TEXT_DIRECTION_LOCALE} 21076 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21077 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21078 * 21079 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21080 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21081 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21082 * 21083 * @attr ref android.R.styleable#View_textDirection 21084 */ 21085 public void setTextDirection(int textDirection) { 21086 if (getRawTextDirection() != textDirection) { 21087 // Reset the current text direction and the resolved one 21088 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21089 resetResolvedTextDirection(); 21090 // Set the new text direction 21091 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21092 // Do resolution 21093 resolveTextDirection(); 21094 // Notify change 21095 onRtlPropertiesChanged(getLayoutDirection()); 21096 // Refresh 21097 requestLayout(); 21098 invalidate(true); 21099 } 21100 } 21101 21102 /** 21103 * Return the resolved text direction. 21104 * 21105 * @return the resolved text direction. Returns one of: 21106 * 21107 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21108 * {@link #TEXT_DIRECTION_ANY_RTL}, 21109 * {@link #TEXT_DIRECTION_LTR}, 21110 * {@link #TEXT_DIRECTION_RTL}, 21111 * {@link #TEXT_DIRECTION_LOCALE}, 21112 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21113 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21114 * 21115 * @attr ref android.R.styleable#View_textDirection 21116 */ 21117 @ViewDebug.ExportedProperty(category = "text", mapping = { 21118 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21119 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21120 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21121 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21122 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21123 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21124 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21125 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21126 }) 21127 public int getTextDirection() { 21128 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21129 } 21130 21131 /** 21132 * Resolve the text direction. 21133 * 21134 * @return true if resolution has been done, false otherwise. 21135 * 21136 * @hide 21137 */ 21138 public boolean resolveTextDirection() { 21139 // Reset any previous text direction resolution 21140 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21141 21142 if (hasRtlSupport()) { 21143 // Set resolved text direction flag depending on text direction flag 21144 final int textDirection = getRawTextDirection(); 21145 switch(textDirection) { 21146 case TEXT_DIRECTION_INHERIT: 21147 if (!canResolveTextDirection()) { 21148 // We cannot do the resolution if there is no parent, so use the default one 21149 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21150 // Resolution will need to happen again later 21151 return false; 21152 } 21153 21154 // Parent has not yet resolved, so we still return the default 21155 try { 21156 if (!mParent.isTextDirectionResolved()) { 21157 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21158 // Resolution will need to happen again later 21159 return false; 21160 } 21161 } catch (AbstractMethodError e) { 21162 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21163 " does not fully implement ViewParent", e); 21164 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21165 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21166 return true; 21167 } 21168 21169 // Set current resolved direction to the same value as the parent's one 21170 int parentResolvedDirection; 21171 try { 21172 parentResolvedDirection = mParent.getTextDirection(); 21173 } catch (AbstractMethodError e) { 21174 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21175 " does not fully implement ViewParent", e); 21176 parentResolvedDirection = TEXT_DIRECTION_LTR; 21177 } 21178 switch (parentResolvedDirection) { 21179 case TEXT_DIRECTION_FIRST_STRONG: 21180 case TEXT_DIRECTION_ANY_RTL: 21181 case TEXT_DIRECTION_LTR: 21182 case TEXT_DIRECTION_RTL: 21183 case TEXT_DIRECTION_LOCALE: 21184 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21185 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21186 mPrivateFlags2 |= 21187 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21188 break; 21189 default: 21190 // Default resolved direction is "first strong" heuristic 21191 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21192 } 21193 break; 21194 case TEXT_DIRECTION_FIRST_STRONG: 21195 case TEXT_DIRECTION_ANY_RTL: 21196 case TEXT_DIRECTION_LTR: 21197 case TEXT_DIRECTION_RTL: 21198 case TEXT_DIRECTION_LOCALE: 21199 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21200 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21201 // Resolved direction is the same as text direction 21202 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21203 break; 21204 default: 21205 // Default resolved direction is "first strong" heuristic 21206 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21207 } 21208 } else { 21209 // Default resolved direction is "first strong" heuristic 21210 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21211 } 21212 21213 // Set to resolved 21214 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21215 return true; 21216 } 21217 21218 /** 21219 * Check if text direction resolution can be done. 21220 * 21221 * @return true if text direction resolution can be done otherwise return false. 21222 */ 21223 public boolean canResolveTextDirection() { 21224 switch (getRawTextDirection()) { 21225 case TEXT_DIRECTION_INHERIT: 21226 if (mParent != null) { 21227 try { 21228 return mParent.canResolveTextDirection(); 21229 } catch (AbstractMethodError e) { 21230 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21231 " does not fully implement ViewParent", e); 21232 } 21233 } 21234 return false; 21235 21236 default: 21237 return true; 21238 } 21239 } 21240 21241 /** 21242 * Reset resolved text direction. Text direction will be resolved during a call to 21243 * {@link #onMeasure(int, int)}. 21244 * 21245 * @hide 21246 */ 21247 public void resetResolvedTextDirection() { 21248 // Reset any previous text direction resolution 21249 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21250 // Set to default value 21251 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21252 } 21253 21254 /** 21255 * @return true if text direction is inherited. 21256 * 21257 * @hide 21258 */ 21259 public boolean isTextDirectionInherited() { 21260 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21261 } 21262 21263 /** 21264 * @return true if text direction is resolved. 21265 */ 21266 public boolean isTextDirectionResolved() { 21267 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21268 } 21269 21270 /** 21271 * Return the value specifying the text alignment or policy that was set with 21272 * {@link #setTextAlignment(int)}. 21273 * 21274 * @return the defined text alignment. It can be one of: 21275 * 21276 * {@link #TEXT_ALIGNMENT_INHERIT}, 21277 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21278 * {@link #TEXT_ALIGNMENT_CENTER}, 21279 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21280 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21281 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21282 * {@link #TEXT_ALIGNMENT_VIEW_END} 21283 * 21284 * @attr ref android.R.styleable#View_textAlignment 21285 * 21286 * @hide 21287 */ 21288 @ViewDebug.ExportedProperty(category = "text", mapping = { 21289 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21290 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21291 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21292 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21293 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21294 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21295 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21296 }) 21297 @TextAlignment 21298 public int getRawTextAlignment() { 21299 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21300 } 21301 21302 /** 21303 * Set the text alignment. 21304 * 21305 * @param textAlignment The text alignment to set. Should be one of 21306 * 21307 * {@link #TEXT_ALIGNMENT_INHERIT}, 21308 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21309 * {@link #TEXT_ALIGNMENT_CENTER}, 21310 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21311 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21312 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21313 * {@link #TEXT_ALIGNMENT_VIEW_END} 21314 * 21315 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21316 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21317 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21318 * 21319 * @attr ref android.R.styleable#View_textAlignment 21320 */ 21321 public void setTextAlignment(@TextAlignment int textAlignment) { 21322 if (textAlignment != getRawTextAlignment()) { 21323 // Reset the current and resolved text alignment 21324 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21325 resetResolvedTextAlignment(); 21326 // Set the new text alignment 21327 mPrivateFlags2 |= 21328 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21329 // Do resolution 21330 resolveTextAlignment(); 21331 // Notify change 21332 onRtlPropertiesChanged(getLayoutDirection()); 21333 // Refresh 21334 requestLayout(); 21335 invalidate(true); 21336 } 21337 } 21338 21339 /** 21340 * Return the resolved text alignment. 21341 * 21342 * @return the resolved text alignment. Returns one of: 21343 * 21344 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21345 * {@link #TEXT_ALIGNMENT_CENTER}, 21346 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21347 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21348 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21349 * {@link #TEXT_ALIGNMENT_VIEW_END} 21350 * 21351 * @attr ref android.R.styleable#View_textAlignment 21352 */ 21353 @ViewDebug.ExportedProperty(category = "text", mapping = { 21354 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21355 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21356 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21357 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21358 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21359 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21360 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21361 }) 21362 @TextAlignment 21363 public int getTextAlignment() { 21364 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21365 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21366 } 21367 21368 /** 21369 * Resolve the text alignment. 21370 * 21371 * @return true if resolution has been done, false otherwise. 21372 * 21373 * @hide 21374 */ 21375 public boolean resolveTextAlignment() { 21376 // Reset any previous text alignment resolution 21377 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21378 21379 if (hasRtlSupport()) { 21380 // Set resolved text alignment flag depending on text alignment flag 21381 final int textAlignment = getRawTextAlignment(); 21382 switch (textAlignment) { 21383 case TEXT_ALIGNMENT_INHERIT: 21384 // Check if we can resolve the text alignment 21385 if (!canResolveTextAlignment()) { 21386 // We cannot do the resolution if there is no parent so use the default 21387 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21388 // Resolution will need to happen again later 21389 return false; 21390 } 21391 21392 // Parent has not yet resolved, so we still return the default 21393 try { 21394 if (!mParent.isTextAlignmentResolved()) { 21395 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21396 // Resolution will need to happen again later 21397 return false; 21398 } 21399 } catch (AbstractMethodError e) { 21400 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21401 " does not fully implement ViewParent", e); 21402 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21403 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21404 return true; 21405 } 21406 21407 int parentResolvedTextAlignment; 21408 try { 21409 parentResolvedTextAlignment = mParent.getTextAlignment(); 21410 } catch (AbstractMethodError e) { 21411 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21412 " does not fully implement ViewParent", e); 21413 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21414 } 21415 switch (parentResolvedTextAlignment) { 21416 case TEXT_ALIGNMENT_GRAVITY: 21417 case TEXT_ALIGNMENT_TEXT_START: 21418 case TEXT_ALIGNMENT_TEXT_END: 21419 case TEXT_ALIGNMENT_CENTER: 21420 case TEXT_ALIGNMENT_VIEW_START: 21421 case TEXT_ALIGNMENT_VIEW_END: 21422 // Resolved text alignment is the same as the parent resolved 21423 // text alignment 21424 mPrivateFlags2 |= 21425 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21426 break; 21427 default: 21428 // Use default resolved text alignment 21429 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21430 } 21431 break; 21432 case TEXT_ALIGNMENT_GRAVITY: 21433 case TEXT_ALIGNMENT_TEXT_START: 21434 case TEXT_ALIGNMENT_TEXT_END: 21435 case TEXT_ALIGNMENT_CENTER: 21436 case TEXT_ALIGNMENT_VIEW_START: 21437 case TEXT_ALIGNMENT_VIEW_END: 21438 // Resolved text alignment is the same as text alignment 21439 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21440 break; 21441 default: 21442 // Use default resolved text alignment 21443 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21444 } 21445 } else { 21446 // Use default resolved text alignment 21447 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21448 } 21449 21450 // Set the resolved 21451 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21452 return true; 21453 } 21454 21455 /** 21456 * Check if text alignment resolution can be done. 21457 * 21458 * @return true if text alignment resolution can be done otherwise return false. 21459 */ 21460 public boolean canResolveTextAlignment() { 21461 switch (getRawTextAlignment()) { 21462 case TEXT_DIRECTION_INHERIT: 21463 if (mParent != null) { 21464 try { 21465 return mParent.canResolveTextAlignment(); 21466 } catch (AbstractMethodError e) { 21467 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21468 " does not fully implement ViewParent", e); 21469 } 21470 } 21471 return false; 21472 21473 default: 21474 return true; 21475 } 21476 } 21477 21478 /** 21479 * Reset resolved text alignment. Text alignment will be resolved during a call to 21480 * {@link #onMeasure(int, int)}. 21481 * 21482 * @hide 21483 */ 21484 public void resetResolvedTextAlignment() { 21485 // Reset any previous text alignment resolution 21486 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21487 // Set to default 21488 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21489 } 21490 21491 /** 21492 * @return true if text alignment is inherited. 21493 * 21494 * @hide 21495 */ 21496 public boolean isTextAlignmentInherited() { 21497 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21498 } 21499 21500 /** 21501 * @return true if text alignment is resolved. 21502 */ 21503 public boolean isTextAlignmentResolved() { 21504 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21505 } 21506 21507 /** 21508 * Generate a value suitable for use in {@link #setId(int)}. 21509 * This value will not collide with ID values generated at build time by aapt for R.id. 21510 * 21511 * @return a generated ID value 21512 */ 21513 public static int generateViewId() { 21514 for (;;) { 21515 final int result = sNextGeneratedId.get(); 21516 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 21517 int newValue = result + 1; 21518 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 21519 if (sNextGeneratedId.compareAndSet(result, newValue)) { 21520 return result; 21521 } 21522 } 21523 } 21524 21525 /** 21526 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 21527 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 21528 * a normal View or a ViewGroup with 21529 * {@link android.view.ViewGroup#isTransitionGroup()} true. 21530 * @hide 21531 */ 21532 public void captureTransitioningViews(List<View> transitioningViews) { 21533 if (getVisibility() == View.VISIBLE) { 21534 transitioningViews.add(this); 21535 } 21536 } 21537 21538 /** 21539 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 21540 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 21541 * @hide 21542 */ 21543 public void findNamedViews(Map<String, View> namedElements) { 21544 if (getVisibility() == VISIBLE || mGhostView != null) { 21545 String transitionName = getTransitionName(); 21546 if (transitionName != null) { 21547 namedElements.put(transitionName, this); 21548 } 21549 } 21550 } 21551 21552 /** 21553 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 21554 * The default implementation does not care the location or event types, but some subclasses 21555 * may use it (such as WebViews). 21556 * @param event The MotionEvent from a mouse 21557 * @param x The x position of the event, local to the view 21558 * @param y The y position of the event, local to the view 21559 * @see PointerIcon 21560 */ 21561 public PointerIcon getPointerIcon(MotionEvent event, float x, float y) { 21562 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 21563 return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW); 21564 } 21565 return mPointerIcon; 21566 } 21567 21568 /** 21569 * Set the pointer icon for the current view. 21570 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 21571 */ 21572 public void setPointerIcon(PointerIcon pointerIcon) { 21573 mPointerIcon = pointerIcon; 21574 } 21575 21576 /** 21577 * Request capturing further mouse events. 21578 * 21579 * When the view captures, the mouse pointer icon will disappear and will not change its 21580 * position. Further mouse events will come to the capturing view, and the mouse movements 21581 * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and 21582 * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not 21583 * be affected. 21584 * 21585 * The capture will be released through {@link #releasePointerCapture()}, or will be lost 21586 * automatically when the view or containing window disappear. 21587 * 21588 * @return true when succeeds. 21589 * @see #releasePointerCapture() 21590 * @see #hasPointerCapture() 21591 */ 21592 public void setPointerCapture() { 21593 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21594 if (viewRootImpl != null) { 21595 viewRootImpl.setPointerCapture(this); 21596 } 21597 } 21598 21599 21600 /** 21601 * Release the current capture of mouse events. 21602 * 21603 * If the view does not have the capture, it will do nothing. 21604 * @see #setPointerCapture() 21605 * @see #hasPointerCapture() 21606 */ 21607 public void releasePointerCapture() { 21608 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21609 if (viewRootImpl != null) { 21610 viewRootImpl.releasePointerCapture(this); 21611 } 21612 } 21613 21614 /** 21615 * Checks the capture status of mouse events. 21616 * 21617 * @return true if the view has the capture. 21618 * @see #setPointerCapture() 21619 * @see #hasPointerCapture() 21620 */ 21621 public boolean hasPointerCapture() { 21622 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21623 return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this); 21624 } 21625 21626 // 21627 // Properties 21628 // 21629 /** 21630 * A Property wrapper around the <code>alpha</code> functionality handled by the 21631 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 21632 */ 21633 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 21634 @Override 21635 public void setValue(View object, float value) { 21636 object.setAlpha(value); 21637 } 21638 21639 @Override 21640 public Float get(View object) { 21641 return object.getAlpha(); 21642 } 21643 }; 21644 21645 /** 21646 * A Property wrapper around the <code>translationX</code> functionality handled by the 21647 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 21648 */ 21649 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 21650 @Override 21651 public void setValue(View object, float value) { 21652 object.setTranslationX(value); 21653 } 21654 21655 @Override 21656 public Float get(View object) { 21657 return object.getTranslationX(); 21658 } 21659 }; 21660 21661 /** 21662 * A Property wrapper around the <code>translationY</code> functionality handled by the 21663 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 21664 */ 21665 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 21666 @Override 21667 public void setValue(View object, float value) { 21668 object.setTranslationY(value); 21669 } 21670 21671 @Override 21672 public Float get(View object) { 21673 return object.getTranslationY(); 21674 } 21675 }; 21676 21677 /** 21678 * A Property wrapper around the <code>translationZ</code> functionality handled by the 21679 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 21680 */ 21681 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 21682 @Override 21683 public void setValue(View object, float value) { 21684 object.setTranslationZ(value); 21685 } 21686 21687 @Override 21688 public Float get(View object) { 21689 return object.getTranslationZ(); 21690 } 21691 }; 21692 21693 /** 21694 * A Property wrapper around the <code>x</code> functionality handled by the 21695 * {@link View#setX(float)} and {@link View#getX()} methods. 21696 */ 21697 public static final Property<View, Float> X = new FloatProperty<View>("x") { 21698 @Override 21699 public void setValue(View object, float value) { 21700 object.setX(value); 21701 } 21702 21703 @Override 21704 public Float get(View object) { 21705 return object.getX(); 21706 } 21707 }; 21708 21709 /** 21710 * A Property wrapper around the <code>y</code> functionality handled by the 21711 * {@link View#setY(float)} and {@link View#getY()} methods. 21712 */ 21713 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 21714 @Override 21715 public void setValue(View object, float value) { 21716 object.setY(value); 21717 } 21718 21719 @Override 21720 public Float get(View object) { 21721 return object.getY(); 21722 } 21723 }; 21724 21725 /** 21726 * A Property wrapper around the <code>z</code> functionality handled by the 21727 * {@link View#setZ(float)} and {@link View#getZ()} methods. 21728 */ 21729 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 21730 @Override 21731 public void setValue(View object, float value) { 21732 object.setZ(value); 21733 } 21734 21735 @Override 21736 public Float get(View object) { 21737 return object.getZ(); 21738 } 21739 }; 21740 21741 /** 21742 * A Property wrapper around the <code>rotation</code> functionality handled by the 21743 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 21744 */ 21745 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 21746 @Override 21747 public void setValue(View object, float value) { 21748 object.setRotation(value); 21749 } 21750 21751 @Override 21752 public Float get(View object) { 21753 return object.getRotation(); 21754 } 21755 }; 21756 21757 /** 21758 * A Property wrapper around the <code>rotationX</code> functionality handled by the 21759 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 21760 */ 21761 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 21762 @Override 21763 public void setValue(View object, float value) { 21764 object.setRotationX(value); 21765 } 21766 21767 @Override 21768 public Float get(View object) { 21769 return object.getRotationX(); 21770 } 21771 }; 21772 21773 /** 21774 * A Property wrapper around the <code>rotationY</code> functionality handled by the 21775 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 21776 */ 21777 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 21778 @Override 21779 public void setValue(View object, float value) { 21780 object.setRotationY(value); 21781 } 21782 21783 @Override 21784 public Float get(View object) { 21785 return object.getRotationY(); 21786 } 21787 }; 21788 21789 /** 21790 * A Property wrapper around the <code>scaleX</code> functionality handled by the 21791 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 21792 */ 21793 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 21794 @Override 21795 public void setValue(View object, float value) { 21796 object.setScaleX(value); 21797 } 21798 21799 @Override 21800 public Float get(View object) { 21801 return object.getScaleX(); 21802 } 21803 }; 21804 21805 /** 21806 * A Property wrapper around the <code>scaleY</code> functionality handled by the 21807 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 21808 */ 21809 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 21810 @Override 21811 public void setValue(View object, float value) { 21812 object.setScaleY(value); 21813 } 21814 21815 @Override 21816 public Float get(View object) { 21817 return object.getScaleY(); 21818 } 21819 }; 21820 21821 /** 21822 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 21823 * Each MeasureSpec represents a requirement for either the width or the height. 21824 * A MeasureSpec is comprised of a size and a mode. There are three possible 21825 * modes: 21826 * <dl> 21827 * <dt>UNSPECIFIED</dt> 21828 * <dd> 21829 * The parent has not imposed any constraint on the child. It can be whatever size 21830 * it wants. 21831 * </dd> 21832 * 21833 * <dt>EXACTLY</dt> 21834 * <dd> 21835 * The parent has determined an exact size for the child. The child is going to be 21836 * given those bounds regardless of how big it wants to be. 21837 * </dd> 21838 * 21839 * <dt>AT_MOST</dt> 21840 * <dd> 21841 * The child can be as large as it wants up to the specified size. 21842 * </dd> 21843 * </dl> 21844 * 21845 * MeasureSpecs are implemented as ints to reduce object allocation. This class 21846 * is provided to pack and unpack the <size, mode> tuple into the int. 21847 */ 21848 public static class MeasureSpec { 21849 private static final int MODE_SHIFT = 30; 21850 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 21851 21852 /** @hide */ 21853 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 21854 @Retention(RetentionPolicy.SOURCE) 21855 public @interface MeasureSpecMode {} 21856 21857 /** 21858 * Measure specification mode: The parent has not imposed any constraint 21859 * on the child. It can be whatever size it wants. 21860 */ 21861 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 21862 21863 /** 21864 * Measure specification mode: The parent has determined an exact size 21865 * for the child. The child is going to be given those bounds regardless 21866 * of how big it wants to be. 21867 */ 21868 public static final int EXACTLY = 1 << MODE_SHIFT; 21869 21870 /** 21871 * Measure specification mode: The child can be as large as it wants up 21872 * to the specified size. 21873 */ 21874 public static final int AT_MOST = 2 << MODE_SHIFT; 21875 21876 /** 21877 * Creates a measure specification based on the supplied size and mode. 21878 * 21879 * The mode must always be one of the following: 21880 * <ul> 21881 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 21882 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 21883 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 21884 * </ul> 21885 * 21886 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 21887 * implementation was such that the order of arguments did not matter 21888 * and overflow in either value could impact the resulting MeasureSpec. 21889 * {@link android.widget.RelativeLayout} was affected by this bug. 21890 * Apps targeting API levels greater than 17 will get the fixed, more strict 21891 * behavior.</p> 21892 * 21893 * @param size the size of the measure specification 21894 * @param mode the mode of the measure specification 21895 * @return the measure specification based on size and mode 21896 */ 21897 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 21898 @MeasureSpecMode int mode) { 21899 if (sUseBrokenMakeMeasureSpec) { 21900 return size + mode; 21901 } else { 21902 return (size & ~MODE_MASK) | (mode & MODE_MASK); 21903 } 21904 } 21905 21906 /** 21907 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 21908 * will automatically get a size of 0. Older apps expect this. 21909 * 21910 * @hide internal use only for compatibility with system widgets and older apps 21911 */ 21912 public static int makeSafeMeasureSpec(int size, int mode) { 21913 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 21914 return 0; 21915 } 21916 return makeMeasureSpec(size, mode); 21917 } 21918 21919 /** 21920 * Extracts the mode from the supplied measure specification. 21921 * 21922 * @param measureSpec the measure specification to extract the mode from 21923 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 21924 * {@link android.view.View.MeasureSpec#AT_MOST} or 21925 * {@link android.view.View.MeasureSpec#EXACTLY} 21926 */ 21927 @MeasureSpecMode 21928 public static int getMode(int measureSpec) { 21929 //noinspection ResourceType 21930 return (measureSpec & MODE_MASK); 21931 } 21932 21933 /** 21934 * Extracts the size from the supplied measure specification. 21935 * 21936 * @param measureSpec the measure specification to extract the size from 21937 * @return the size in pixels defined in the supplied measure specification 21938 */ 21939 public static int getSize(int measureSpec) { 21940 return (measureSpec & ~MODE_MASK); 21941 } 21942 21943 static int adjust(int measureSpec, int delta) { 21944 final int mode = getMode(measureSpec); 21945 int size = getSize(measureSpec); 21946 if (mode == UNSPECIFIED) { 21947 // No need to adjust size for UNSPECIFIED mode. 21948 return makeMeasureSpec(size, UNSPECIFIED); 21949 } 21950 size += delta; 21951 if (size < 0) { 21952 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 21953 ") spec: " + toString(measureSpec) + " delta: " + delta); 21954 size = 0; 21955 } 21956 return makeMeasureSpec(size, mode); 21957 } 21958 21959 /** 21960 * Returns a String representation of the specified measure 21961 * specification. 21962 * 21963 * @param measureSpec the measure specification to convert to a String 21964 * @return a String with the following format: "MeasureSpec: MODE SIZE" 21965 */ 21966 public static String toString(int measureSpec) { 21967 int mode = getMode(measureSpec); 21968 int size = getSize(measureSpec); 21969 21970 StringBuilder sb = new StringBuilder("MeasureSpec: "); 21971 21972 if (mode == UNSPECIFIED) 21973 sb.append("UNSPECIFIED "); 21974 else if (mode == EXACTLY) 21975 sb.append("EXACTLY "); 21976 else if (mode == AT_MOST) 21977 sb.append("AT_MOST "); 21978 else 21979 sb.append(mode).append(" "); 21980 21981 sb.append(size); 21982 return sb.toString(); 21983 } 21984 } 21985 21986 private final class CheckForLongPress implements Runnable { 21987 private int mOriginalWindowAttachCount; 21988 private float mX; 21989 private float mY; 21990 21991 @Override 21992 public void run() { 21993 if (isPressed() && (mParent != null) 21994 && mOriginalWindowAttachCount == mWindowAttachCount) { 21995 if (performLongClick(mX, mY)) { 21996 mHasPerformedLongPress = true; 21997 } 21998 } 21999 } 22000 22001 public void setAnchor(float x, float y) { 22002 mX = x; 22003 mY = y; 22004 } 22005 22006 public void rememberWindowAttachCount() { 22007 mOriginalWindowAttachCount = mWindowAttachCount; 22008 } 22009 } 22010 22011 private final class CheckForTap implements Runnable { 22012 public float x; 22013 public float y; 22014 22015 @Override 22016 public void run() { 22017 mPrivateFlags &= ~PFLAG_PREPRESSED; 22018 setPressed(true, x, y); 22019 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22020 } 22021 } 22022 22023 private final class PerformClick implements Runnable { 22024 @Override 22025 public void run() { 22026 performClick(); 22027 } 22028 } 22029 22030 /** 22031 * This method returns a ViewPropertyAnimator object, which can be used to animate 22032 * specific properties on this View. 22033 * 22034 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22035 */ 22036 public ViewPropertyAnimator animate() { 22037 if (mAnimator == null) { 22038 mAnimator = new ViewPropertyAnimator(this); 22039 } 22040 return mAnimator; 22041 } 22042 22043 /** 22044 * Sets the name of the View to be used to identify Views in Transitions. 22045 * Names should be unique in the View hierarchy. 22046 * 22047 * @param transitionName The name of the View to uniquely identify it for Transitions. 22048 */ 22049 public final void setTransitionName(String transitionName) { 22050 mTransitionName = transitionName; 22051 } 22052 22053 /** 22054 * Returns the name of the View to be used to identify Views in Transitions. 22055 * Names should be unique in the View hierarchy. 22056 * 22057 * <p>This returns null if the View has not been given a name.</p> 22058 * 22059 * @return The name used of the View to be used to identify Views in Transitions or null 22060 * if no name has been given. 22061 */ 22062 @ViewDebug.ExportedProperty 22063 public String getTransitionName() { 22064 return mTransitionName; 22065 } 22066 22067 /** 22068 * @hide 22069 */ 22070 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data) { 22071 // Do nothing. 22072 } 22073 22074 /** 22075 * Interface definition for a callback to be invoked when a hardware key event is 22076 * dispatched to this view. The callback will be invoked before the key event is 22077 * given to the view. This is only useful for hardware keyboards; a software input 22078 * method has no obligation to trigger this listener. 22079 */ 22080 public interface OnKeyListener { 22081 /** 22082 * Called when a hardware key is dispatched to a view. This allows listeners to 22083 * get a chance to respond before the target view. 22084 * <p>Key presses in software keyboards will generally NOT trigger this method, 22085 * although some may elect to do so in some situations. Do not assume a 22086 * software input method has to be key-based; even if it is, it may use key presses 22087 * in a different way than you expect, so there is no way to reliably catch soft 22088 * input key presses. 22089 * 22090 * @param v The view the key has been dispatched to. 22091 * @param keyCode The code for the physical key that was pressed 22092 * @param event The KeyEvent object containing full information about 22093 * the event. 22094 * @return True if the listener has consumed the event, false otherwise. 22095 */ 22096 boolean onKey(View v, int keyCode, KeyEvent event); 22097 } 22098 22099 /** 22100 * Interface definition for a callback to be invoked when a touch event is 22101 * dispatched to this view. The callback will be invoked before the touch 22102 * event is given to the view. 22103 */ 22104 public interface OnTouchListener { 22105 /** 22106 * Called when a touch event is dispatched to a view. This allows listeners to 22107 * get a chance to respond before the target view. 22108 * 22109 * @param v The view the touch event has been dispatched to. 22110 * @param event The MotionEvent object containing full information about 22111 * the event. 22112 * @return True if the listener has consumed the event, false otherwise. 22113 */ 22114 boolean onTouch(View v, MotionEvent event); 22115 } 22116 22117 /** 22118 * Interface definition for a callback to be invoked when a hover event is 22119 * dispatched to this view. The callback will be invoked before the hover 22120 * event is given to the view. 22121 */ 22122 public interface OnHoverListener { 22123 /** 22124 * Called when a hover event is dispatched to a view. This allows listeners to 22125 * get a chance to respond before the target view. 22126 * 22127 * @param v The view the hover event has been dispatched to. 22128 * @param event The MotionEvent object containing full information about 22129 * the event. 22130 * @return True if the listener has consumed the event, false otherwise. 22131 */ 22132 boolean onHover(View v, MotionEvent event); 22133 } 22134 22135 /** 22136 * Interface definition for a callback to be invoked when a generic motion event is 22137 * dispatched to this view. The callback will be invoked before the generic motion 22138 * event is given to the view. 22139 */ 22140 public interface OnGenericMotionListener { 22141 /** 22142 * Called when a generic motion event is dispatched to a view. This allows listeners to 22143 * get a chance to respond before the target view. 22144 * 22145 * @param v The view the generic motion event has been dispatched to. 22146 * @param event The MotionEvent object containing full information about 22147 * the event. 22148 * @return True if the listener has consumed the event, false otherwise. 22149 */ 22150 boolean onGenericMotion(View v, MotionEvent event); 22151 } 22152 22153 /** 22154 * Interface definition for a callback to be invoked when a view has been clicked and held. 22155 */ 22156 public interface OnLongClickListener { 22157 /** 22158 * Called when a view has been clicked and held. 22159 * 22160 * @param v The view that was clicked and held. 22161 * 22162 * @return true if the callback consumed the long click, false otherwise. 22163 */ 22164 boolean onLongClick(View v); 22165 } 22166 22167 /** 22168 * Interface definition for a callback to be invoked when a drag is being dispatched 22169 * to this view. The callback will be invoked before the hosting view's own 22170 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22171 * onDrag(event) behavior, it should return 'false' from this callback. 22172 * 22173 * <div class="special reference"> 22174 * <h3>Developer Guides</h3> 22175 * <p>For a guide to implementing drag and drop features, read the 22176 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22177 * </div> 22178 */ 22179 public interface OnDragListener { 22180 /** 22181 * Called when a drag event is dispatched to a view. This allows listeners 22182 * to get a chance to override base View behavior. 22183 * 22184 * @param v The View that received the drag event. 22185 * @param event The {@link android.view.DragEvent} object for the drag event. 22186 * @return {@code true} if the drag event was handled successfully, or {@code false} 22187 * if the drag event was not handled. Note that {@code false} will trigger the View 22188 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22189 */ 22190 boolean onDrag(View v, DragEvent event); 22191 } 22192 22193 /** 22194 * Interface definition for a callback to be invoked when the focus state of 22195 * a view changed. 22196 */ 22197 public interface OnFocusChangeListener { 22198 /** 22199 * Called when the focus state of a view has changed. 22200 * 22201 * @param v The view whose state has changed. 22202 * @param hasFocus The new focus state of v. 22203 */ 22204 void onFocusChange(View v, boolean hasFocus); 22205 } 22206 22207 /** 22208 * Interface definition for a callback to be invoked when a view is clicked. 22209 */ 22210 public interface OnClickListener { 22211 /** 22212 * Called when a view has been clicked. 22213 * 22214 * @param v The view that was clicked. 22215 */ 22216 void onClick(View v); 22217 } 22218 22219 /** 22220 * Interface definition for a callback to be invoked when a view is context clicked. 22221 */ 22222 public interface OnContextClickListener { 22223 /** 22224 * Called when a view is context clicked. 22225 * 22226 * @param v The view that has been context clicked. 22227 * @return true if the callback consumed the context click, false otherwise. 22228 */ 22229 boolean onContextClick(View v); 22230 } 22231 22232 /** 22233 * Interface definition for a callback to be invoked when the context menu 22234 * for this view is being built. 22235 */ 22236 public interface OnCreateContextMenuListener { 22237 /** 22238 * Called when the context menu for this view is being built. It is not 22239 * safe to hold onto the menu after this method returns. 22240 * 22241 * @param menu The context menu that is being built 22242 * @param v The view for which the context menu is being built 22243 * @param menuInfo Extra information about the item for which the 22244 * context menu should be shown. This information will vary 22245 * depending on the class of v. 22246 */ 22247 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22248 } 22249 22250 /** 22251 * Interface definition for a callback to be invoked when the status bar changes 22252 * visibility. This reports <strong>global</strong> changes to the system UI 22253 * state, not what the application is requesting. 22254 * 22255 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22256 */ 22257 public interface OnSystemUiVisibilityChangeListener { 22258 /** 22259 * Called when the status bar changes visibility because of a call to 22260 * {@link View#setSystemUiVisibility(int)}. 22261 * 22262 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22263 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22264 * This tells you the <strong>global</strong> state of these UI visibility 22265 * flags, not what your app is currently applying. 22266 */ 22267 public void onSystemUiVisibilityChange(int visibility); 22268 } 22269 22270 /** 22271 * Interface definition for a callback to be invoked when this view is attached 22272 * or detached from its window. 22273 */ 22274 public interface OnAttachStateChangeListener { 22275 /** 22276 * Called when the view is attached to a window. 22277 * @param v The view that was attached 22278 */ 22279 public void onViewAttachedToWindow(View v); 22280 /** 22281 * Called when the view is detached from a window. 22282 * @param v The view that was detached 22283 */ 22284 public void onViewDetachedFromWindow(View v); 22285 } 22286 22287 /** 22288 * Listener for applying window insets on a view in a custom way. 22289 * 22290 * <p>Apps may choose to implement this interface if they want to apply custom policy 22291 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22292 * is set, its 22293 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22294 * method will be called instead of the View's own 22295 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22296 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22297 * the View's normal behavior as part of its own.</p> 22298 */ 22299 public interface OnApplyWindowInsetsListener { 22300 /** 22301 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22302 * on a View, this listener method will be called instead of the view's own 22303 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22304 * 22305 * @param v The view applying window insets 22306 * @param insets The insets to apply 22307 * @return The insets supplied, minus any insets that were consumed 22308 */ 22309 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22310 } 22311 22312 private final class UnsetPressedState implements Runnable { 22313 @Override 22314 public void run() { 22315 setPressed(false); 22316 } 22317 } 22318 22319 /** 22320 * Base class for derived classes that want to save and restore their own 22321 * state in {@link android.view.View#onSaveInstanceState()}. 22322 */ 22323 public static class BaseSavedState extends AbsSavedState { 22324 String mStartActivityRequestWhoSaved; 22325 22326 /** 22327 * Constructor used when reading from a parcel. Reads the state of the superclass. 22328 * 22329 * @param source 22330 */ 22331 public BaseSavedState(Parcel source) { 22332 super(source); 22333 mStartActivityRequestWhoSaved = source.readString(); 22334 } 22335 22336 /** 22337 * Constructor called by derived classes when creating their SavedState objects 22338 * 22339 * @param superState The state of the superclass of this view 22340 */ 22341 public BaseSavedState(Parcelable superState) { 22342 super(superState); 22343 } 22344 22345 @Override 22346 public void writeToParcel(Parcel out, int flags) { 22347 super.writeToParcel(out, flags); 22348 out.writeString(mStartActivityRequestWhoSaved); 22349 } 22350 22351 public static final Parcelable.Creator<BaseSavedState> CREATOR = 22352 new Parcelable.Creator<BaseSavedState>() { 22353 public BaseSavedState createFromParcel(Parcel in) { 22354 return new BaseSavedState(in); 22355 } 22356 22357 public BaseSavedState[] newArray(int size) { 22358 return new BaseSavedState[size]; 22359 } 22360 }; 22361 } 22362 22363 /** 22364 * A set of information given to a view when it is attached to its parent 22365 * window. 22366 */ 22367 final static class AttachInfo { 22368 interface Callbacks { 22369 void playSoundEffect(int effectId); 22370 boolean performHapticFeedback(int effectId, boolean always); 22371 } 22372 22373 /** 22374 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22375 * to a Handler. This class contains the target (View) to invalidate and 22376 * the coordinates of the dirty rectangle. 22377 * 22378 * For performance purposes, this class also implements a pool of up to 22379 * POOL_LIMIT objects that get reused. This reduces memory allocations 22380 * whenever possible. 22381 */ 22382 static class InvalidateInfo { 22383 private static final int POOL_LIMIT = 10; 22384 22385 private static final SynchronizedPool<InvalidateInfo> sPool = 22386 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22387 22388 View target; 22389 22390 int left; 22391 int top; 22392 int right; 22393 int bottom; 22394 22395 public static InvalidateInfo obtain() { 22396 InvalidateInfo instance = sPool.acquire(); 22397 return (instance != null) ? instance : new InvalidateInfo(); 22398 } 22399 22400 public void recycle() { 22401 target = null; 22402 sPool.release(this); 22403 } 22404 } 22405 22406 final IWindowSession mSession; 22407 22408 final IWindow mWindow; 22409 22410 final IBinder mWindowToken; 22411 22412 final Display mDisplay; 22413 22414 final Callbacks mRootCallbacks; 22415 22416 IWindowId mIWindowId; 22417 WindowId mWindowId; 22418 22419 /** 22420 * The top view of the hierarchy. 22421 */ 22422 View mRootView; 22423 22424 IBinder mPanelParentWindowToken; 22425 22426 boolean mHardwareAccelerated; 22427 boolean mHardwareAccelerationRequested; 22428 ThreadedRenderer mHardwareRenderer; 22429 List<RenderNode> mPendingAnimatingRenderNodes; 22430 22431 /** 22432 * The state of the display to which the window is attached, as reported 22433 * by {@link Display#getState()}. Note that the display state constants 22434 * declared by {@link Display} do not exactly line up with the screen state 22435 * constants declared by {@link View} (there are more display states than 22436 * screen states). 22437 */ 22438 int mDisplayState = Display.STATE_UNKNOWN; 22439 22440 /** 22441 * Scale factor used by the compatibility mode 22442 */ 22443 float mApplicationScale; 22444 22445 /** 22446 * Indicates whether the application is in compatibility mode 22447 */ 22448 boolean mScalingRequired; 22449 22450 /** 22451 * Left position of this view's window 22452 */ 22453 int mWindowLeft; 22454 22455 /** 22456 * Top position of this view's window 22457 */ 22458 int mWindowTop; 22459 22460 /** 22461 * Indicates whether views need to use 32-bit drawing caches 22462 */ 22463 boolean mUse32BitDrawingCache; 22464 22465 /** 22466 * For windows that are full-screen but using insets to layout inside 22467 * of the screen areas, these are the current insets to appear inside 22468 * the overscan area of the display. 22469 */ 22470 final Rect mOverscanInsets = new Rect(); 22471 22472 /** 22473 * For windows that are full-screen but using insets to layout inside 22474 * of the screen decorations, these are the current insets for the 22475 * content of the window. 22476 */ 22477 final Rect mContentInsets = new Rect(); 22478 22479 /** 22480 * For windows that are full-screen but using insets to layout inside 22481 * of the screen decorations, these are the current insets for the 22482 * actual visible parts of the window. 22483 */ 22484 final Rect mVisibleInsets = new Rect(); 22485 22486 /** 22487 * For windows that are full-screen but using insets to layout inside 22488 * of the screen decorations, these are the current insets for the 22489 * stable system windows. 22490 */ 22491 final Rect mStableInsets = new Rect(); 22492 22493 /** 22494 * For windows that include areas that are not covered by real surface these are the outsets 22495 * for real surface. 22496 */ 22497 final Rect mOutsets = new Rect(); 22498 22499 /** 22500 * The internal insets given by this window. This value is 22501 * supplied by the client (through 22502 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22503 * be given to the window manager when changed to be used in laying 22504 * out windows behind it. 22505 */ 22506 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22507 = new ViewTreeObserver.InternalInsetsInfo(); 22508 22509 /** 22510 * Set to true when mGivenInternalInsets is non-empty. 22511 */ 22512 boolean mHasNonEmptyGivenInternalInsets; 22513 22514 /** 22515 * All views in the window's hierarchy that serve as scroll containers, 22516 * used to determine if the window can be resized or must be panned 22517 * to adjust for a soft input area. 22518 */ 22519 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 22520 22521 final KeyEvent.DispatcherState mKeyDispatchState 22522 = new KeyEvent.DispatcherState(); 22523 22524 /** 22525 * Indicates whether the view's window currently has the focus. 22526 */ 22527 boolean mHasWindowFocus; 22528 22529 /** 22530 * The current visibility of the window. 22531 */ 22532 int mWindowVisibility; 22533 22534 /** 22535 * Indicates the time at which drawing started to occur. 22536 */ 22537 long mDrawingTime; 22538 22539 /** 22540 * Indicates whether or not ignoring the DIRTY_MASK flags. 22541 */ 22542 boolean mIgnoreDirtyState; 22543 22544 /** 22545 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 22546 * to avoid clearing that flag prematurely. 22547 */ 22548 boolean mSetIgnoreDirtyState = false; 22549 22550 /** 22551 * Indicates whether the view's window is currently in touch mode. 22552 */ 22553 boolean mInTouchMode; 22554 22555 /** 22556 * Indicates whether the view has requested unbuffered input dispatching for the current 22557 * event stream. 22558 */ 22559 boolean mUnbufferedDispatchRequested; 22560 22561 /** 22562 * Indicates that ViewAncestor should trigger a global layout change 22563 * the next time it performs a traversal 22564 */ 22565 boolean mRecomputeGlobalAttributes; 22566 22567 /** 22568 * Always report new attributes at next traversal. 22569 */ 22570 boolean mForceReportNewAttributes; 22571 22572 /** 22573 * Set during a traveral if any views want to keep the screen on. 22574 */ 22575 boolean mKeepScreenOn; 22576 22577 /** 22578 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 22579 */ 22580 int mSystemUiVisibility; 22581 22582 /** 22583 * Hack to force certain system UI visibility flags to be cleared. 22584 */ 22585 int mDisabledSystemUiVisibility; 22586 22587 /** 22588 * Last global system UI visibility reported by the window manager. 22589 */ 22590 int mGlobalSystemUiVisibility; 22591 22592 /** 22593 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 22594 * attached. 22595 */ 22596 boolean mHasSystemUiListeners; 22597 22598 /** 22599 * Set if the window has requested to extend into the overscan region 22600 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 22601 */ 22602 boolean mOverscanRequested; 22603 22604 /** 22605 * Set if the visibility of any views has changed. 22606 */ 22607 boolean mViewVisibilityChanged; 22608 22609 /** 22610 * Set to true if a view has been scrolled. 22611 */ 22612 boolean mViewScrollChanged; 22613 22614 /** 22615 * Set to true if high contrast mode enabled 22616 */ 22617 boolean mHighContrastText; 22618 22619 /** 22620 * Global to the view hierarchy used as a temporary for dealing with 22621 * x/y points in the transparent region computations. 22622 */ 22623 final int[] mTransparentLocation = new int[2]; 22624 22625 /** 22626 * Global to the view hierarchy used as a temporary for dealing with 22627 * x/y points in the ViewGroup.invalidateChild implementation. 22628 */ 22629 final int[] mInvalidateChildLocation = new int[2]; 22630 22631 /** 22632 * Global to the view hierarchy used as a temporary for dealng with 22633 * computing absolute on-screen location. 22634 */ 22635 final int[] mTmpLocation = new int[2]; 22636 22637 /** 22638 * Global to the view hierarchy used as a temporary for dealing with 22639 * x/y location when view is transformed. 22640 */ 22641 final float[] mTmpTransformLocation = new float[2]; 22642 22643 /** 22644 * The view tree observer used to dispatch global events like 22645 * layout, pre-draw, touch mode change, etc. 22646 */ 22647 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 22648 22649 /** 22650 * A Canvas used by the view hierarchy to perform bitmap caching. 22651 */ 22652 Canvas mCanvas; 22653 22654 /** 22655 * The view root impl. 22656 */ 22657 final ViewRootImpl mViewRootImpl; 22658 22659 /** 22660 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 22661 * handler can be used to pump events in the UI events queue. 22662 */ 22663 final Handler mHandler; 22664 22665 /** 22666 * Temporary for use in computing invalidate rectangles while 22667 * calling up the hierarchy. 22668 */ 22669 final Rect mTmpInvalRect = new Rect(); 22670 22671 /** 22672 * Temporary for use in computing hit areas with transformed views 22673 */ 22674 final RectF mTmpTransformRect = new RectF(); 22675 22676 /** 22677 * Temporary for use in computing hit areas with transformed views 22678 */ 22679 final RectF mTmpTransformRect1 = new RectF(); 22680 22681 /** 22682 * Temporary list of rectanges. 22683 */ 22684 final List<RectF> mTmpRectList = new ArrayList<>(); 22685 22686 /** 22687 * Temporary for use in transforming invalidation rect 22688 */ 22689 final Matrix mTmpMatrix = new Matrix(); 22690 22691 /** 22692 * Temporary for use in transforming invalidation rect 22693 */ 22694 final Transformation mTmpTransformation = new Transformation(); 22695 22696 /** 22697 * Temporary for use in querying outlines from OutlineProviders 22698 */ 22699 final Outline mTmpOutline = new Outline(); 22700 22701 /** 22702 * Temporary list for use in collecting focusable descendents of a view. 22703 */ 22704 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 22705 22706 /** 22707 * The id of the window for accessibility purposes. 22708 */ 22709 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 22710 22711 /** 22712 * Flags related to accessibility processing. 22713 * 22714 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 22715 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 22716 */ 22717 int mAccessibilityFetchFlags; 22718 22719 /** 22720 * The drawable for highlighting accessibility focus. 22721 */ 22722 Drawable mAccessibilityFocusDrawable; 22723 22724 /** 22725 * Show where the margins, bounds and layout bounds are for each view. 22726 */ 22727 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 22728 22729 /** 22730 * Point used to compute visible regions. 22731 */ 22732 final Point mPoint = new Point(); 22733 22734 /** 22735 * Used to track which View originated a requestLayout() call, used when 22736 * requestLayout() is called during layout. 22737 */ 22738 View mViewRequestingLayout; 22739 22740 /** 22741 * Used to track views that need (at least) a partial relayout at their current size 22742 * during the next traversal. 22743 */ 22744 List<View> mPartialLayoutViews = new ArrayList<>(); 22745 22746 /** 22747 * Swapped with mPartialLayoutViews during layout to avoid concurrent 22748 * modification. Lazily assigned during ViewRootImpl layout. 22749 */ 22750 List<View> mEmptyPartialLayoutViews; 22751 22752 /** 22753 * Used to track the identity of the current drag operation. 22754 */ 22755 IBinder mDragToken; 22756 22757 /** 22758 * The drag shadow surface for the current drag operation. 22759 */ 22760 public Surface mDragSurface; 22761 22762 /** 22763 * Creates a new set of attachment information with the specified 22764 * events handler and thread. 22765 * 22766 * @param handler the events handler the view must use 22767 */ 22768 AttachInfo(IWindowSession session, IWindow window, Display display, 22769 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 22770 mSession = session; 22771 mWindow = window; 22772 mWindowToken = window.asBinder(); 22773 mDisplay = display; 22774 mViewRootImpl = viewRootImpl; 22775 mHandler = handler; 22776 mRootCallbacks = effectPlayer; 22777 } 22778 } 22779 22780 /** 22781 * <p>ScrollabilityCache holds various fields used by a View when scrolling 22782 * is supported. This avoids keeping too many unused fields in most 22783 * instances of View.</p> 22784 */ 22785 private static class ScrollabilityCache implements Runnable { 22786 22787 /** 22788 * Scrollbars are not visible 22789 */ 22790 public static final int OFF = 0; 22791 22792 /** 22793 * Scrollbars are visible 22794 */ 22795 public static final int ON = 1; 22796 22797 /** 22798 * Scrollbars are fading away 22799 */ 22800 public static final int FADING = 2; 22801 22802 public boolean fadeScrollBars; 22803 22804 public int fadingEdgeLength; 22805 public int scrollBarDefaultDelayBeforeFade; 22806 public int scrollBarFadeDuration; 22807 22808 public int scrollBarSize; 22809 public ScrollBarDrawable scrollBar; 22810 public float[] interpolatorValues; 22811 public View host; 22812 22813 public final Paint paint; 22814 public final Matrix matrix; 22815 public Shader shader; 22816 22817 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 22818 22819 private static final float[] OPAQUE = { 255 }; 22820 private static final float[] TRANSPARENT = { 0.0f }; 22821 22822 /** 22823 * When fading should start. This time moves into the future every time 22824 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 22825 */ 22826 public long fadeStartTime; 22827 22828 22829 /** 22830 * The current state of the scrollbars: ON, OFF, or FADING 22831 */ 22832 public int state = OFF; 22833 22834 private int mLastColor; 22835 22836 public final Rect mScrollBarBounds = new Rect(); 22837 22838 public static final int NOT_DRAGGING = 0; 22839 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 22840 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 22841 public int mScrollBarDraggingState = NOT_DRAGGING; 22842 22843 public float mScrollBarDraggingPos = 0; 22844 22845 public ScrollabilityCache(ViewConfiguration configuration, View host) { 22846 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 22847 scrollBarSize = configuration.getScaledScrollBarSize(); 22848 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 22849 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 22850 22851 paint = new Paint(); 22852 matrix = new Matrix(); 22853 // use use a height of 1, and then wack the matrix each time we 22854 // actually use it. 22855 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 22856 paint.setShader(shader); 22857 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 22858 22859 this.host = host; 22860 } 22861 22862 public void setFadeColor(int color) { 22863 if (color != mLastColor) { 22864 mLastColor = color; 22865 22866 if (color != 0) { 22867 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 22868 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 22869 paint.setShader(shader); 22870 // Restore the default transfer mode (src_over) 22871 paint.setXfermode(null); 22872 } else { 22873 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 22874 paint.setShader(shader); 22875 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 22876 } 22877 } 22878 } 22879 22880 public void run() { 22881 long now = AnimationUtils.currentAnimationTimeMillis(); 22882 if (now >= fadeStartTime) { 22883 22884 // the animation fades the scrollbars out by changing 22885 // the opacity (alpha) from fully opaque to fully 22886 // transparent 22887 int nextFrame = (int) now; 22888 int framesCount = 0; 22889 22890 Interpolator interpolator = scrollBarInterpolator; 22891 22892 // Start opaque 22893 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 22894 22895 // End transparent 22896 nextFrame += scrollBarFadeDuration; 22897 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 22898 22899 state = FADING; 22900 22901 // Kick off the fade animation 22902 host.invalidate(true); 22903 } 22904 } 22905 } 22906 22907 /** 22908 * Resuable callback for sending 22909 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 22910 */ 22911 private class SendViewScrolledAccessibilityEvent implements Runnable { 22912 public volatile boolean mIsPending; 22913 22914 public void run() { 22915 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 22916 mIsPending = false; 22917 } 22918 } 22919 22920 /** 22921 * <p> 22922 * This class represents a delegate that can be registered in a {@link View} 22923 * to enhance accessibility support via composition rather via inheritance. 22924 * It is specifically targeted to widget developers that extend basic View 22925 * classes i.e. classes in package android.view, that would like their 22926 * applications to be backwards compatible. 22927 * </p> 22928 * <div class="special reference"> 22929 * <h3>Developer Guides</h3> 22930 * <p>For more information about making applications accessible, read the 22931 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 22932 * developer guide.</p> 22933 * </div> 22934 * <p> 22935 * A scenario in which a developer would like to use an accessibility delegate 22936 * is overriding a method introduced in a later API version then the minimal API 22937 * version supported by the application. For example, the method 22938 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 22939 * in API version 4 when the accessibility APIs were first introduced. If a 22940 * developer would like his application to run on API version 4 devices (assuming 22941 * all other APIs used by the application are version 4 or lower) and take advantage 22942 * of this method, instead of overriding the method which would break the application's 22943 * backwards compatibility, he can override the corresponding method in this 22944 * delegate and register the delegate in the target View if the API version of 22945 * the system is high enough i.e. the API version is same or higher to the API 22946 * version that introduced 22947 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 22948 * </p> 22949 * <p> 22950 * Here is an example implementation: 22951 * </p> 22952 * <code><pre><p> 22953 * if (Build.VERSION.SDK_INT >= 14) { 22954 * // If the API version is equal of higher than the version in 22955 * // which onInitializeAccessibilityNodeInfo was introduced we 22956 * // register a delegate with a customized implementation. 22957 * View view = findViewById(R.id.view_id); 22958 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 22959 * public void onInitializeAccessibilityNodeInfo(View host, 22960 * AccessibilityNodeInfo info) { 22961 * // Let the default implementation populate the info. 22962 * super.onInitializeAccessibilityNodeInfo(host, info); 22963 * // Set some other information. 22964 * info.setEnabled(host.isEnabled()); 22965 * } 22966 * }); 22967 * } 22968 * </code></pre></p> 22969 * <p> 22970 * This delegate contains methods that correspond to the accessibility methods 22971 * in View. If a delegate has been specified the implementation in View hands 22972 * off handling to the corresponding method in this delegate. The default 22973 * implementation the delegate methods behaves exactly as the corresponding 22974 * method in View for the case of no accessibility delegate been set. Hence, 22975 * to customize the behavior of a View method, clients can override only the 22976 * corresponding delegate method without altering the behavior of the rest 22977 * accessibility related methods of the host view. 22978 * </p> 22979 * <p> 22980 * <strong>Note:</strong> On platform versions prior to 22981 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 22982 * views in the {@code android.widget.*} package are called <i>before</i> 22983 * host methods. This prevents certain properties such as class name from 22984 * being modified by overriding 22985 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 22986 * as any changes will be overwritten by the host class. 22987 * <p> 22988 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 22989 * methods are called <i>after</i> host methods, which all properties to be 22990 * modified without being overwritten by the host class. 22991 */ 22992 public static class AccessibilityDelegate { 22993 22994 /** 22995 * Sends an accessibility event of the given type. If accessibility is not 22996 * enabled this method has no effect. 22997 * <p> 22998 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 22999 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23000 * been set. 23001 * </p> 23002 * 23003 * @param host The View hosting the delegate. 23004 * @param eventType The type of the event to send. 23005 * 23006 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23007 */ 23008 public void sendAccessibilityEvent(View host, int eventType) { 23009 host.sendAccessibilityEventInternal(eventType); 23010 } 23011 23012 /** 23013 * Performs the specified accessibility action on the view. For 23014 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23015 * <p> 23016 * The default implementation behaves as 23017 * {@link View#performAccessibilityAction(int, Bundle) 23018 * View#performAccessibilityAction(int, Bundle)} for the case of 23019 * no accessibility delegate been set. 23020 * </p> 23021 * 23022 * @param action The action to perform. 23023 * @return Whether the action was performed. 23024 * 23025 * @see View#performAccessibilityAction(int, Bundle) 23026 * View#performAccessibilityAction(int, Bundle) 23027 */ 23028 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23029 return host.performAccessibilityActionInternal(action, args); 23030 } 23031 23032 /** 23033 * Sends an accessibility event. This method behaves exactly as 23034 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23035 * empty {@link AccessibilityEvent} and does not perform a check whether 23036 * accessibility is enabled. 23037 * <p> 23038 * The default implementation behaves as 23039 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23040 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 23041 * the case of no accessibility delegate been set. 23042 * </p> 23043 * 23044 * @param host The View hosting the delegate. 23045 * @param event The event to send. 23046 * 23047 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23048 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23049 */ 23050 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23051 host.sendAccessibilityEventUncheckedInternal(event); 23052 } 23053 23054 /** 23055 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23056 * to its children for adding their text content to the event. 23057 * <p> 23058 * The default implementation behaves as 23059 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23060 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23061 * the case of no accessibility delegate been set. 23062 * </p> 23063 * 23064 * @param host The View hosting the delegate. 23065 * @param event The event. 23066 * @return True if the event population was completed. 23067 * 23068 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23069 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23070 */ 23071 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23072 return host.dispatchPopulateAccessibilityEventInternal(event); 23073 } 23074 23075 /** 23076 * Gives a chance to the host View to populate the accessibility event with its 23077 * text content. 23078 * <p> 23079 * The default implementation behaves as 23080 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23081 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23082 * the case of no accessibility delegate been set. 23083 * </p> 23084 * 23085 * @param host The View hosting the delegate. 23086 * @param event The accessibility event which to populate. 23087 * 23088 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23089 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23090 */ 23091 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23092 host.onPopulateAccessibilityEventInternal(event); 23093 } 23094 23095 /** 23096 * Initializes an {@link AccessibilityEvent} with information about the 23097 * the host View which is the event source. 23098 * <p> 23099 * The default implementation behaves as 23100 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23101 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23102 * the case of no accessibility delegate been set. 23103 * </p> 23104 * 23105 * @param host The View hosting the delegate. 23106 * @param event The event to initialize. 23107 * 23108 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23109 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23110 */ 23111 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23112 host.onInitializeAccessibilityEventInternal(event); 23113 } 23114 23115 /** 23116 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23117 * <p> 23118 * The default implementation behaves as 23119 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23120 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23121 * the case of no accessibility delegate been set. 23122 * </p> 23123 * 23124 * @param host The View hosting the delegate. 23125 * @param info The instance to initialize. 23126 * 23127 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23128 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23129 */ 23130 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23131 host.onInitializeAccessibilityNodeInfoInternal(info); 23132 } 23133 23134 /** 23135 * Called when a child of the host View has requested sending an 23136 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23137 * to augment the event. 23138 * <p> 23139 * The default implementation behaves as 23140 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23141 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23142 * the case of no accessibility delegate been set. 23143 * </p> 23144 * 23145 * @param host The View hosting the delegate. 23146 * @param child The child which requests sending the event. 23147 * @param event The event to be sent. 23148 * @return True if the event should be sent 23149 * 23150 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23151 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23152 */ 23153 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23154 AccessibilityEvent event) { 23155 return host.onRequestSendAccessibilityEventInternal(child, event); 23156 } 23157 23158 /** 23159 * Gets the provider for managing a virtual view hierarchy rooted at this View 23160 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23161 * that explore the window content. 23162 * <p> 23163 * The default implementation behaves as 23164 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23165 * the case of no accessibility delegate been set. 23166 * </p> 23167 * 23168 * @return The provider. 23169 * 23170 * @see AccessibilityNodeProvider 23171 */ 23172 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23173 return null; 23174 } 23175 23176 /** 23177 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23178 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23179 * This method is responsible for obtaining an accessibility node info from a 23180 * pool of reusable instances and calling 23181 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23182 * view to initialize the former. 23183 * <p> 23184 * <strong>Note:</strong> The client is responsible for recycling the obtained 23185 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23186 * creation. 23187 * </p> 23188 * <p> 23189 * The default implementation behaves as 23190 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23191 * the case of no accessibility delegate been set. 23192 * </p> 23193 * @return A populated {@link AccessibilityNodeInfo}. 23194 * 23195 * @see AccessibilityNodeInfo 23196 * 23197 * @hide 23198 */ 23199 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23200 return host.createAccessibilityNodeInfoInternal(); 23201 } 23202 } 23203 23204 private class MatchIdPredicate implements Predicate<View> { 23205 public int mId; 23206 23207 @Override 23208 public boolean apply(View view) { 23209 return (view.mID == mId); 23210 } 23211 } 23212 23213 private class MatchLabelForPredicate implements Predicate<View> { 23214 private int mLabeledId; 23215 23216 @Override 23217 public boolean apply(View view) { 23218 return (view.mLabelForId == mLabeledId); 23219 } 23220 } 23221 23222 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23223 private int mChangeTypes = 0; 23224 private boolean mPosted; 23225 private boolean mPostedWithDelay; 23226 private long mLastEventTimeMillis; 23227 23228 @Override 23229 public void run() { 23230 mPosted = false; 23231 mPostedWithDelay = false; 23232 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23233 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23234 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23235 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23236 event.setContentChangeTypes(mChangeTypes); 23237 sendAccessibilityEventUnchecked(event); 23238 } 23239 mChangeTypes = 0; 23240 } 23241 23242 public void runOrPost(int changeType) { 23243 mChangeTypes |= changeType; 23244 23245 // If this is a live region or the child of a live region, collect 23246 // all events from this frame and send them on the next frame. 23247 if (inLiveRegion()) { 23248 // If we're already posted with a delay, remove that. 23249 if (mPostedWithDelay) { 23250 removeCallbacks(this); 23251 mPostedWithDelay = false; 23252 } 23253 // Only post if we're not already posted. 23254 if (!mPosted) { 23255 post(this); 23256 mPosted = true; 23257 } 23258 return; 23259 } 23260 23261 if (mPosted) { 23262 return; 23263 } 23264 23265 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23266 final long minEventIntevalMillis = 23267 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23268 if (timeSinceLastMillis >= minEventIntevalMillis) { 23269 removeCallbacks(this); 23270 run(); 23271 } else { 23272 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23273 mPostedWithDelay = true; 23274 } 23275 } 23276 } 23277 23278 private boolean inLiveRegion() { 23279 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23280 return true; 23281 } 23282 23283 ViewParent parent = getParent(); 23284 while (parent instanceof View) { 23285 if (((View) parent).getAccessibilityLiveRegion() 23286 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23287 return true; 23288 } 23289 parent = parent.getParent(); 23290 } 23291 23292 return false; 23293 } 23294 23295 /** 23296 * Dump all private flags in readable format, useful for documentation and 23297 * sanity checking. 23298 */ 23299 private static void dumpFlags() { 23300 final HashMap<String, String> found = Maps.newHashMap(); 23301 try { 23302 for (Field field : View.class.getDeclaredFields()) { 23303 final int modifiers = field.getModifiers(); 23304 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23305 if (field.getType().equals(int.class)) { 23306 final int value = field.getInt(null); 23307 dumpFlag(found, field.getName(), value); 23308 } else if (field.getType().equals(int[].class)) { 23309 final int[] values = (int[]) field.get(null); 23310 for (int i = 0; i < values.length; i++) { 23311 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23312 } 23313 } 23314 } 23315 } 23316 } catch (IllegalAccessException e) { 23317 throw new RuntimeException(e); 23318 } 23319 23320 final ArrayList<String> keys = Lists.newArrayList(); 23321 keys.addAll(found.keySet()); 23322 Collections.sort(keys); 23323 for (String key : keys) { 23324 Log.d(VIEW_LOG_TAG, found.get(key)); 23325 } 23326 } 23327 23328 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23329 // Sort flags by prefix, then by bits, always keeping unique keys 23330 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23331 final int prefix = name.indexOf('_'); 23332 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23333 final String output = bits + " " + name; 23334 found.put(key, output); 23335 } 23336 23337 /** {@hide} */ 23338 public void encode(@NonNull ViewHierarchyEncoder stream) { 23339 stream.beginObject(this); 23340 encodeProperties(stream); 23341 stream.endObject(); 23342 } 23343 23344 /** {@hide} */ 23345 @CallSuper 23346 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23347 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23348 if (resolveId instanceof String) { 23349 stream.addProperty("id", (String) resolveId); 23350 } else { 23351 stream.addProperty("id", mID); 23352 } 23353 23354 stream.addProperty("misc:transformation.alpha", 23355 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23356 stream.addProperty("misc:transitionName", getTransitionName()); 23357 23358 // layout 23359 stream.addProperty("layout:left", mLeft); 23360 stream.addProperty("layout:right", mRight); 23361 stream.addProperty("layout:top", mTop); 23362 stream.addProperty("layout:bottom", mBottom); 23363 stream.addProperty("layout:width", getWidth()); 23364 stream.addProperty("layout:height", getHeight()); 23365 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23366 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23367 stream.addProperty("layout:hasTransientState", hasTransientState()); 23368 stream.addProperty("layout:baseline", getBaseline()); 23369 23370 // layout params 23371 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23372 if (layoutParams != null) { 23373 stream.addPropertyKey("layoutParams"); 23374 layoutParams.encode(stream); 23375 } 23376 23377 // scrolling 23378 stream.addProperty("scrolling:scrollX", mScrollX); 23379 stream.addProperty("scrolling:scrollY", mScrollY); 23380 23381 // padding 23382 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23383 stream.addProperty("padding:paddingRight", mPaddingRight); 23384 stream.addProperty("padding:paddingTop", mPaddingTop); 23385 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23386 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23387 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23388 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23389 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23390 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23391 23392 // measurement 23393 stream.addProperty("measurement:minHeight", mMinHeight); 23394 stream.addProperty("measurement:minWidth", mMinWidth); 23395 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23396 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23397 23398 // drawing 23399 stream.addProperty("drawing:elevation", getElevation()); 23400 stream.addProperty("drawing:translationX", getTranslationX()); 23401 stream.addProperty("drawing:translationY", getTranslationY()); 23402 stream.addProperty("drawing:translationZ", getTranslationZ()); 23403 stream.addProperty("drawing:rotation", getRotation()); 23404 stream.addProperty("drawing:rotationX", getRotationX()); 23405 stream.addProperty("drawing:rotationY", getRotationY()); 23406 stream.addProperty("drawing:scaleX", getScaleX()); 23407 stream.addProperty("drawing:scaleY", getScaleY()); 23408 stream.addProperty("drawing:pivotX", getPivotX()); 23409 stream.addProperty("drawing:pivotY", getPivotY()); 23410 stream.addProperty("drawing:opaque", isOpaque()); 23411 stream.addProperty("drawing:alpha", getAlpha()); 23412 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23413 stream.addProperty("drawing:shadow", hasShadow()); 23414 stream.addProperty("drawing:solidColor", getSolidColor()); 23415 stream.addProperty("drawing:layerType", mLayerType); 23416 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23417 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23418 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23419 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23420 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23421 23422 // focus 23423 stream.addProperty("focus:hasFocus", hasFocus()); 23424 stream.addProperty("focus:isFocused", isFocused()); 23425 stream.addProperty("focus:isFocusable", isFocusable()); 23426 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23427 23428 stream.addProperty("misc:clickable", isClickable()); 23429 stream.addProperty("misc:pressed", isPressed()); 23430 stream.addProperty("misc:selected", isSelected()); 23431 stream.addProperty("misc:touchMode", isInTouchMode()); 23432 stream.addProperty("misc:hovered", isHovered()); 23433 stream.addProperty("misc:activated", isActivated()); 23434 23435 stream.addProperty("misc:visibility", getVisibility()); 23436 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23437 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23438 23439 stream.addProperty("misc:enabled", isEnabled()); 23440 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23441 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23442 23443 // theme attributes 23444 Resources.Theme theme = getContext().getTheme(); 23445 if (theme != null) { 23446 stream.addPropertyKey("theme"); 23447 theme.encode(stream); 23448 } 23449 23450 // view attribute information 23451 int n = mAttributes != null ? mAttributes.length : 0; 23452 stream.addProperty("meta:__attrCount__", n/2); 23453 for (int i = 0; i < n; i += 2) { 23454 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23455 } 23456 23457 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23458 23459 // text 23460 stream.addProperty("text:textDirection", getTextDirection()); 23461 stream.addProperty("text:textAlignment", getTextAlignment()); 23462 23463 // accessibility 23464 CharSequence contentDescription = getContentDescription(); 23465 stream.addProperty("accessibility:contentDescription", 23466 contentDescription == null ? "" : contentDescription.toString()); 23467 stream.addProperty("accessibility:labelFor", getLabelFor()); 23468 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23469 } 23470} 23471