View.java revision 6d2b3ac67c9d308da89fd98ef50dd9f47f8b29bd
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 /* 6878 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 6879 * drawing order may not be well-defined, and some Views with custom drawing order may 6880 * not be initialized sufficiently to respond properly getChildDrawingOrder. 6881 */ 6882 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 6883 info.setDrawingOrder(0); 6884 return; 6885 } 6886 int drawingOrderInParent = 1; 6887 // Iterate up the hierarchy if parents are not important for a11y 6888 View viewAtDrawingLevel = this; 6889 final ViewParent parent = getParentForAccessibility(); 6890 while (viewAtDrawingLevel != parent) { 6891 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 6892 if (!(currentParent instanceof ViewGroup)) { 6893 // Should only happen for the Decor 6894 drawingOrderInParent = 0; 6895 break; 6896 } else { 6897 final ViewGroup parentGroup = (ViewGroup) currentParent; 6898 final int childCount = parentGroup.getChildCount(); 6899 if (childCount > 1) { 6900 List<View> preorderedList = parentGroup.buildOrderedChildList(); 6901 if (preorderedList != null) { 6902 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 6903 for (int i = 0; i < childDrawIndex; i++) { 6904 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 6905 } 6906 } else { 6907 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 6908 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 6909 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 6910 .getChildDrawingOrder(childCount, childIndex) : childIndex; 6911 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 6912 if (childDrawIndex != 0) { 6913 for (int i = 0; i < numChildrenToIterate; i++) { 6914 final int otherDrawIndex = (customOrder ? 6915 parentGroup.getChildDrawingOrder(childCount, i) : i); 6916 if (otherDrawIndex < childDrawIndex) { 6917 drawingOrderInParent += 6918 numViewsForAccessibility(parentGroup.getChildAt(i)); 6919 } 6920 } 6921 } 6922 } 6923 } 6924 } 6925 viewAtDrawingLevel = (View) currentParent; 6926 } 6927 info.setDrawingOrder(drawingOrderInParent); 6928 } 6929 6930 private static int numViewsForAccessibility(View view) { 6931 if (view != null) { 6932 if (view.includeForAccessibility()) { 6933 return 1; 6934 } else if (view instanceof ViewGroup) { 6935 return ((ViewGroup) view).getNumChildrenForAccessibility(); 6936 } 6937 } 6938 return 0; 6939 } 6940 6941 private View findLabelForView(View view, int labeledId) { 6942 if (mMatchLabelForPredicate == null) { 6943 mMatchLabelForPredicate = new MatchLabelForPredicate(); 6944 } 6945 mMatchLabelForPredicate.mLabeledId = labeledId; 6946 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 6947 } 6948 6949 /** 6950 * Computes whether this view is visible to the user. Such a view is 6951 * attached, visible, all its predecessors are visible, it is not clipped 6952 * entirely by its predecessors, and has an alpha greater than zero. 6953 * 6954 * @return Whether the view is visible on the screen. 6955 * 6956 * @hide 6957 */ 6958 protected boolean isVisibleToUser() { 6959 return isVisibleToUser(null); 6960 } 6961 6962 /** 6963 * Computes whether the given portion of this view is visible to the user. 6964 * Such a view is attached, visible, all its predecessors are visible, 6965 * has an alpha greater than zero, and the specified portion is not 6966 * clipped entirely by its predecessors. 6967 * 6968 * @param boundInView the portion of the view to test; coordinates should be relative; may be 6969 * <code>null</code>, and the entire view will be tested in this case. 6970 * When <code>true</code> is returned by the function, the actual visible 6971 * region will be stored in this parameter; that is, if boundInView is fully 6972 * contained within the view, no modification will be made, otherwise regions 6973 * outside of the visible area of the view will be clipped. 6974 * 6975 * @return Whether the specified portion of the view is visible on the screen. 6976 * 6977 * @hide 6978 */ 6979 protected boolean isVisibleToUser(Rect boundInView) { 6980 if (mAttachInfo != null) { 6981 // Attached to invisible window means this view is not visible. 6982 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 6983 return false; 6984 } 6985 // An invisible predecessor or one with alpha zero means 6986 // that this view is not visible to the user. 6987 Object current = this; 6988 while (current instanceof View) { 6989 View view = (View) current; 6990 // We have attach info so this view is attached and there is no 6991 // need to check whether we reach to ViewRootImpl on the way up. 6992 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 6993 view.getVisibility() != VISIBLE) { 6994 return false; 6995 } 6996 current = view.mParent; 6997 } 6998 // Check if the view is entirely covered by its predecessors. 6999 Rect visibleRect = mAttachInfo.mTmpInvalRect; 7000 Point offset = mAttachInfo.mPoint; 7001 if (!getGlobalVisibleRect(visibleRect, offset)) { 7002 return false; 7003 } 7004 // Check if the visible portion intersects the rectangle of interest. 7005 if (boundInView != null) { 7006 visibleRect.offset(-offset.x, -offset.y); 7007 return boundInView.intersect(visibleRect); 7008 } 7009 return true; 7010 } 7011 return false; 7012 } 7013 7014 /** 7015 * Returns the delegate for implementing accessibility support via 7016 * composition. For more details see {@link AccessibilityDelegate}. 7017 * 7018 * @return The delegate, or null if none set. 7019 * 7020 * @hide 7021 */ 7022 public AccessibilityDelegate getAccessibilityDelegate() { 7023 return mAccessibilityDelegate; 7024 } 7025 7026 /** 7027 * Sets a delegate for implementing accessibility support via composition 7028 * (as opposed to inheritance). For more details, see 7029 * {@link AccessibilityDelegate}. 7030 * <p> 7031 * <strong>Note:</strong> On platform versions prior to 7032 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 7033 * views in the {@code android.widget.*} package are called <i>before</i> 7034 * host methods. This prevents certain properties such as class name from 7035 * being modified by overriding 7036 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 7037 * as any changes will be overwritten by the host class. 7038 * <p> 7039 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 7040 * methods are called <i>after</i> host methods, which all properties to be 7041 * modified without being overwritten by the host class. 7042 * 7043 * @param delegate the object to which accessibility method calls should be 7044 * delegated 7045 * @see AccessibilityDelegate 7046 */ 7047 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 7048 mAccessibilityDelegate = delegate; 7049 } 7050 7051 /** 7052 * Gets the provider for managing a virtual view hierarchy rooted at this View 7053 * and reported to {@link android.accessibilityservice.AccessibilityService}s 7054 * that explore the window content. 7055 * <p> 7056 * If this method returns an instance, this instance is responsible for managing 7057 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 7058 * View including the one representing the View itself. Similarly the returned 7059 * instance is responsible for performing accessibility actions on any virtual 7060 * view or the root view itself. 7061 * </p> 7062 * <p> 7063 * If an {@link AccessibilityDelegate} has been specified via calling 7064 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7065 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 7066 * is responsible for handling this call. 7067 * </p> 7068 * 7069 * @return The provider. 7070 * 7071 * @see AccessibilityNodeProvider 7072 */ 7073 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 7074 if (mAccessibilityDelegate != null) { 7075 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 7076 } else { 7077 return null; 7078 } 7079 } 7080 7081 /** 7082 * Gets the unique identifier of this view on the screen for accessibility purposes. 7083 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 7084 * 7085 * @return The view accessibility id. 7086 * 7087 * @hide 7088 */ 7089 public int getAccessibilityViewId() { 7090 if (mAccessibilityViewId == NO_ID) { 7091 mAccessibilityViewId = sNextAccessibilityViewId++; 7092 } 7093 return mAccessibilityViewId; 7094 } 7095 7096 /** 7097 * Gets the unique identifier of the window in which this View reseides. 7098 * 7099 * @return The window accessibility id. 7100 * 7101 * @hide 7102 */ 7103 public int getAccessibilityWindowId() { 7104 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 7105 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 7106 } 7107 7108 /** 7109 * Returns the {@link View}'s content description. 7110 * <p> 7111 * <strong>Note:</strong> Do not override this method, as it will have no 7112 * effect on the content description presented to accessibility services. 7113 * You must call {@link #setContentDescription(CharSequence)} to modify the 7114 * content description. 7115 * 7116 * @return the content description 7117 * @see #setContentDescription(CharSequence) 7118 * @attr ref android.R.styleable#View_contentDescription 7119 */ 7120 @ViewDebug.ExportedProperty(category = "accessibility") 7121 public CharSequence getContentDescription() { 7122 return mContentDescription; 7123 } 7124 7125 /** 7126 * Sets the {@link View}'s content description. 7127 * <p> 7128 * A content description briefly describes the view and is primarily used 7129 * for accessibility support to determine how a view should be presented to 7130 * the user. In the case of a view with no textual representation, such as 7131 * {@link android.widget.ImageButton}, a useful content description 7132 * explains what the view does. For example, an image button with a phone 7133 * icon that is used to place a call may use "Call" as its content 7134 * description. An image of a floppy disk that is used to save a file may 7135 * use "Save". 7136 * 7137 * @param contentDescription The content description. 7138 * @see #getContentDescription() 7139 * @attr ref android.R.styleable#View_contentDescription 7140 */ 7141 @RemotableViewMethod 7142 public void setContentDescription(CharSequence contentDescription) { 7143 if (mContentDescription == null) { 7144 if (contentDescription == null) { 7145 return; 7146 } 7147 } else if (mContentDescription.equals(contentDescription)) { 7148 return; 7149 } 7150 mContentDescription = contentDescription; 7151 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 7152 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 7153 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 7154 notifySubtreeAccessibilityStateChangedIfNeeded(); 7155 } else { 7156 notifyViewAccessibilityStateChangedIfNeeded( 7157 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 7158 } 7159 } 7160 7161 /** 7162 * Sets the id of a view before which this one is visited in accessibility traversal. 7163 * A screen-reader must visit the content of this view before the content of the one 7164 * it precedes. For example, if view B is set to be before view A, then a screen-reader 7165 * will traverse the entire content of B before traversing the entire content of A, 7166 * regardles of what traversal strategy it is using. 7167 * <p> 7168 * Views that do not have specified before/after relationships are traversed in order 7169 * determined by the screen-reader. 7170 * </p> 7171 * <p> 7172 * Setting that this view is before a view that is not important for accessibility 7173 * or if this view is not important for accessibility will have no effect as the 7174 * screen-reader is not aware of unimportant views. 7175 * </p> 7176 * 7177 * @param beforeId The id of a view this one precedes in accessibility traversal. 7178 * 7179 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 7180 * 7181 * @see #setImportantForAccessibility(int) 7182 */ 7183 @RemotableViewMethod 7184 public void setAccessibilityTraversalBefore(int beforeId) { 7185 if (mAccessibilityTraversalBeforeId == beforeId) { 7186 return; 7187 } 7188 mAccessibilityTraversalBeforeId = beforeId; 7189 notifyViewAccessibilityStateChangedIfNeeded( 7190 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7191 } 7192 7193 /** 7194 * Gets the id of a view before which this one is visited in accessibility traversal. 7195 * 7196 * @return The id of a view this one precedes in accessibility traversal if 7197 * specified, otherwise {@link #NO_ID}. 7198 * 7199 * @see #setAccessibilityTraversalBefore(int) 7200 */ 7201 public int getAccessibilityTraversalBefore() { 7202 return mAccessibilityTraversalBeforeId; 7203 } 7204 7205 /** 7206 * Sets the id of a view after which this one is visited in accessibility traversal. 7207 * A screen-reader must visit the content of the other view before the content of this 7208 * one. For example, if view B is set to be after view A, then a screen-reader 7209 * will traverse the entire content of A before traversing the entire content of B, 7210 * regardles of what traversal strategy it is using. 7211 * <p> 7212 * Views that do not have specified before/after relationships are traversed in order 7213 * determined by the screen-reader. 7214 * </p> 7215 * <p> 7216 * Setting that this view is after a view that is not important for accessibility 7217 * or if this view is not important for accessibility will have no effect as the 7218 * screen-reader is not aware of unimportant views. 7219 * </p> 7220 * 7221 * @param afterId The id of a view this one succedees in accessibility traversal. 7222 * 7223 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 7224 * 7225 * @see #setImportantForAccessibility(int) 7226 */ 7227 @RemotableViewMethod 7228 public void setAccessibilityTraversalAfter(int afterId) { 7229 if (mAccessibilityTraversalAfterId == afterId) { 7230 return; 7231 } 7232 mAccessibilityTraversalAfterId = afterId; 7233 notifyViewAccessibilityStateChangedIfNeeded( 7234 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7235 } 7236 7237 /** 7238 * Gets the id of a view after which this one is visited in accessibility traversal. 7239 * 7240 * @return The id of a view this one succeedes in accessibility traversal if 7241 * specified, otherwise {@link #NO_ID}. 7242 * 7243 * @see #setAccessibilityTraversalAfter(int) 7244 */ 7245 public int getAccessibilityTraversalAfter() { 7246 return mAccessibilityTraversalAfterId; 7247 } 7248 7249 /** 7250 * Gets the id of a view for which this view serves as a label for 7251 * accessibility purposes. 7252 * 7253 * @return The labeled view id. 7254 */ 7255 @ViewDebug.ExportedProperty(category = "accessibility") 7256 public int getLabelFor() { 7257 return mLabelForId; 7258 } 7259 7260 /** 7261 * Sets the id of a view for which this view serves as a label for 7262 * accessibility purposes. 7263 * 7264 * @param id The labeled view id. 7265 */ 7266 @RemotableViewMethod 7267 public void setLabelFor(@IdRes int id) { 7268 if (mLabelForId == id) { 7269 return; 7270 } 7271 mLabelForId = id; 7272 if (mLabelForId != View.NO_ID 7273 && mID == View.NO_ID) { 7274 mID = generateViewId(); 7275 } 7276 notifyViewAccessibilityStateChangedIfNeeded( 7277 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7278 } 7279 7280 /** 7281 * Invoked whenever this view loses focus, either by losing window focus or by losing 7282 * focus within its window. This method can be used to clear any state tied to the 7283 * focus. For instance, if a button is held pressed with the trackball and the window 7284 * loses focus, this method can be used to cancel the press. 7285 * 7286 * Subclasses of View overriding this method should always call super.onFocusLost(). 7287 * 7288 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 7289 * @see #onWindowFocusChanged(boolean) 7290 * 7291 * @hide pending API council approval 7292 */ 7293 @CallSuper 7294 protected void onFocusLost() { 7295 resetPressedState(); 7296 } 7297 7298 private void resetPressedState() { 7299 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 7300 return; 7301 } 7302 7303 if (isPressed()) { 7304 setPressed(false); 7305 7306 if (!mHasPerformedLongPress) { 7307 removeLongPressCallback(); 7308 } 7309 } 7310 } 7311 7312 /** 7313 * Returns true if this view has focus 7314 * 7315 * @return True if this view has focus, false otherwise. 7316 */ 7317 @ViewDebug.ExportedProperty(category = "focus") 7318 public boolean isFocused() { 7319 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 7320 } 7321 7322 /** 7323 * Find the view in the hierarchy rooted at this view that currently has 7324 * focus. 7325 * 7326 * @return The view that currently has focus, or null if no focused view can 7327 * be found. 7328 */ 7329 public View findFocus() { 7330 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 7331 } 7332 7333 /** 7334 * Indicates whether this view is one of the set of scrollable containers in 7335 * its window. 7336 * 7337 * @return whether this view is one of the set of scrollable containers in 7338 * its window 7339 * 7340 * @attr ref android.R.styleable#View_isScrollContainer 7341 */ 7342 public boolean isScrollContainer() { 7343 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 7344 } 7345 7346 /** 7347 * Change whether this view is one of the set of scrollable containers in 7348 * its window. This will be used to determine whether the window can 7349 * resize or must pan when a soft input area is open -- scrollable 7350 * containers allow the window to use resize mode since the container 7351 * will appropriately shrink. 7352 * 7353 * @attr ref android.R.styleable#View_isScrollContainer 7354 */ 7355 public void setScrollContainer(boolean isScrollContainer) { 7356 if (isScrollContainer) { 7357 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 7358 mAttachInfo.mScrollContainers.add(this); 7359 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 7360 } 7361 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 7362 } else { 7363 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 7364 mAttachInfo.mScrollContainers.remove(this); 7365 } 7366 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 7367 } 7368 } 7369 7370 /** 7371 * Returns the quality of the drawing cache. 7372 * 7373 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7374 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7375 * 7376 * @see #setDrawingCacheQuality(int) 7377 * @see #setDrawingCacheEnabled(boolean) 7378 * @see #isDrawingCacheEnabled() 7379 * 7380 * @attr ref android.R.styleable#View_drawingCacheQuality 7381 */ 7382 @DrawingCacheQuality 7383 public int getDrawingCacheQuality() { 7384 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 7385 } 7386 7387 /** 7388 * Set the drawing cache quality of this view. This value is used only when the 7389 * drawing cache is enabled 7390 * 7391 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 7392 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 7393 * 7394 * @see #getDrawingCacheQuality() 7395 * @see #setDrawingCacheEnabled(boolean) 7396 * @see #isDrawingCacheEnabled() 7397 * 7398 * @attr ref android.R.styleable#View_drawingCacheQuality 7399 */ 7400 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 7401 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 7402 } 7403 7404 /** 7405 * Returns whether the screen should remain on, corresponding to the current 7406 * value of {@link #KEEP_SCREEN_ON}. 7407 * 7408 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 7409 * 7410 * @see #setKeepScreenOn(boolean) 7411 * 7412 * @attr ref android.R.styleable#View_keepScreenOn 7413 */ 7414 public boolean getKeepScreenOn() { 7415 return (mViewFlags & KEEP_SCREEN_ON) != 0; 7416 } 7417 7418 /** 7419 * Controls whether the screen should remain on, modifying the 7420 * value of {@link #KEEP_SCREEN_ON}. 7421 * 7422 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 7423 * 7424 * @see #getKeepScreenOn() 7425 * 7426 * @attr ref android.R.styleable#View_keepScreenOn 7427 */ 7428 public void setKeepScreenOn(boolean keepScreenOn) { 7429 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 7430 } 7431 7432 /** 7433 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7434 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7435 * 7436 * @attr ref android.R.styleable#View_nextFocusLeft 7437 */ 7438 public int getNextFocusLeftId() { 7439 return mNextFocusLeftId; 7440 } 7441 7442 /** 7443 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 7444 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 7445 * decide automatically. 7446 * 7447 * @attr ref android.R.styleable#View_nextFocusLeft 7448 */ 7449 public void setNextFocusLeftId(int nextFocusLeftId) { 7450 mNextFocusLeftId = nextFocusLeftId; 7451 } 7452 7453 /** 7454 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7455 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7456 * 7457 * @attr ref android.R.styleable#View_nextFocusRight 7458 */ 7459 public int getNextFocusRightId() { 7460 return mNextFocusRightId; 7461 } 7462 7463 /** 7464 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 7465 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 7466 * decide automatically. 7467 * 7468 * @attr ref android.R.styleable#View_nextFocusRight 7469 */ 7470 public void setNextFocusRightId(int nextFocusRightId) { 7471 mNextFocusRightId = nextFocusRightId; 7472 } 7473 7474 /** 7475 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7476 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7477 * 7478 * @attr ref android.R.styleable#View_nextFocusUp 7479 */ 7480 public int getNextFocusUpId() { 7481 return mNextFocusUpId; 7482 } 7483 7484 /** 7485 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 7486 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 7487 * decide automatically. 7488 * 7489 * @attr ref android.R.styleable#View_nextFocusUp 7490 */ 7491 public void setNextFocusUpId(int nextFocusUpId) { 7492 mNextFocusUpId = nextFocusUpId; 7493 } 7494 7495 /** 7496 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7497 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7498 * 7499 * @attr ref android.R.styleable#View_nextFocusDown 7500 */ 7501 public int getNextFocusDownId() { 7502 return mNextFocusDownId; 7503 } 7504 7505 /** 7506 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 7507 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 7508 * decide automatically. 7509 * 7510 * @attr ref android.R.styleable#View_nextFocusDown 7511 */ 7512 public void setNextFocusDownId(int nextFocusDownId) { 7513 mNextFocusDownId = nextFocusDownId; 7514 } 7515 7516 /** 7517 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7518 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 7519 * 7520 * @attr ref android.R.styleable#View_nextFocusForward 7521 */ 7522 public int getNextFocusForwardId() { 7523 return mNextFocusForwardId; 7524 } 7525 7526 /** 7527 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 7528 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 7529 * decide automatically. 7530 * 7531 * @attr ref android.R.styleable#View_nextFocusForward 7532 */ 7533 public void setNextFocusForwardId(int nextFocusForwardId) { 7534 mNextFocusForwardId = nextFocusForwardId; 7535 } 7536 7537 /** 7538 * Returns the visibility of this view and all of its ancestors 7539 * 7540 * @return True if this view and all of its ancestors are {@link #VISIBLE} 7541 */ 7542 public boolean isShown() { 7543 View current = this; 7544 //noinspection ConstantConditions 7545 do { 7546 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7547 return false; 7548 } 7549 ViewParent parent = current.mParent; 7550 if (parent == null) { 7551 return false; // We are not attached to the view root 7552 } 7553 if (!(parent instanceof View)) { 7554 return true; 7555 } 7556 current = (View) parent; 7557 } while (current != null); 7558 7559 return false; 7560 } 7561 7562 /** 7563 * Called by the view hierarchy when the content insets for a window have 7564 * changed, to allow it to adjust its content to fit within those windows. 7565 * The content insets tell you the space that the status bar, input method, 7566 * and other system windows infringe on the application's window. 7567 * 7568 * <p>You do not normally need to deal with this function, since the default 7569 * window decoration given to applications takes care of applying it to the 7570 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 7571 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 7572 * and your content can be placed under those system elements. You can then 7573 * use this method within your view hierarchy if you have parts of your UI 7574 * which you would like to ensure are not being covered. 7575 * 7576 * <p>The default implementation of this method simply applies the content 7577 * insets to the view's padding, consuming that content (modifying the 7578 * insets to be 0), and returning true. This behavior is off by default, but can 7579 * be enabled through {@link #setFitsSystemWindows(boolean)}. 7580 * 7581 * <p>This function's traversal down the hierarchy is depth-first. The same content 7582 * insets object is propagated down the hierarchy, so any changes made to it will 7583 * be seen by all following views (including potentially ones above in 7584 * the hierarchy since this is a depth-first traversal). The first view 7585 * that returns true will abort the entire traversal. 7586 * 7587 * <p>The default implementation works well for a situation where it is 7588 * used with a container that covers the entire window, allowing it to 7589 * apply the appropriate insets to its content on all edges. If you need 7590 * a more complicated layout (such as two different views fitting system 7591 * windows, one on the top of the window, and one on the bottom), 7592 * you can override the method and handle the insets however you would like. 7593 * Note that the insets provided by the framework are always relative to the 7594 * far edges of the window, not accounting for the location of the called view 7595 * within that window. (In fact when this method is called you do not yet know 7596 * where the layout will place the view, as it is done before layout happens.) 7597 * 7598 * <p>Note: unlike many View methods, there is no dispatch phase to this 7599 * call. If you are overriding it in a ViewGroup and want to allow the 7600 * call to continue to your children, you must be sure to call the super 7601 * implementation. 7602 * 7603 * <p>Here is a sample layout that makes use of fitting system windows 7604 * to have controls for a video view placed inside of the window decorations 7605 * that it hides and shows. This can be used with code like the second 7606 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 7607 * 7608 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 7609 * 7610 * @param insets Current content insets of the window. Prior to 7611 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 7612 * the insets or else you and Android will be unhappy. 7613 * 7614 * @return {@code true} if this view applied the insets and it should not 7615 * continue propagating further down the hierarchy, {@code false} otherwise. 7616 * @see #getFitsSystemWindows() 7617 * @see #setFitsSystemWindows(boolean) 7618 * @see #setSystemUiVisibility(int) 7619 * 7620 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 7621 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 7622 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 7623 * to implement handling their own insets. 7624 */ 7625 protected boolean fitSystemWindows(Rect insets) { 7626 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 7627 if (insets == null) { 7628 // Null insets by definition have already been consumed. 7629 // This call cannot apply insets since there are none to apply, 7630 // so return false. 7631 return false; 7632 } 7633 // If we're not in the process of dispatching the newer apply insets call, 7634 // that means we're not in the compatibility path. Dispatch into the newer 7635 // apply insets path and take things from there. 7636 try { 7637 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 7638 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 7639 } finally { 7640 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 7641 } 7642 } else { 7643 // We're being called from the newer apply insets path. 7644 // Perform the standard fallback behavior. 7645 return fitSystemWindowsInt(insets); 7646 } 7647 } 7648 7649 private boolean fitSystemWindowsInt(Rect insets) { 7650 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 7651 mUserPaddingStart = UNDEFINED_PADDING; 7652 mUserPaddingEnd = UNDEFINED_PADDING; 7653 Rect localInsets = sThreadLocal.get(); 7654 if (localInsets == null) { 7655 localInsets = new Rect(); 7656 sThreadLocal.set(localInsets); 7657 } 7658 boolean res = computeFitSystemWindows(insets, localInsets); 7659 mUserPaddingLeftInitial = localInsets.left; 7660 mUserPaddingRightInitial = localInsets.right; 7661 internalSetPadding(localInsets.left, localInsets.top, 7662 localInsets.right, localInsets.bottom); 7663 return res; 7664 } 7665 return false; 7666 } 7667 7668 /** 7669 * Called when the view should apply {@link WindowInsets} according to its internal policy. 7670 * 7671 * <p>This method should be overridden by views that wish to apply a policy different from or 7672 * in addition to the default behavior. Clients that wish to force a view subtree 7673 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 7674 * 7675 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 7676 * it will be called during dispatch instead of this method. The listener may optionally 7677 * call this method from its own implementation if it wishes to apply the view's default 7678 * insets policy in addition to its own.</p> 7679 * 7680 * <p>Implementations of this method should either return the insets parameter unchanged 7681 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 7682 * that this view applied itself. This allows new inset types added in future platform 7683 * versions to pass through existing implementations unchanged without being erroneously 7684 * consumed.</p> 7685 * 7686 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 7687 * property is set then the view will consume the system window insets and apply them 7688 * as padding for the view.</p> 7689 * 7690 * @param insets Insets to apply 7691 * @return The supplied insets with any applied insets consumed 7692 */ 7693 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 7694 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 7695 // We weren't called from within a direct call to fitSystemWindows, 7696 // call into it as a fallback in case we're in a class that overrides it 7697 // and has logic to perform. 7698 if (fitSystemWindows(insets.getSystemWindowInsets())) { 7699 return insets.consumeSystemWindowInsets(); 7700 } 7701 } else { 7702 // We were called from within a direct call to fitSystemWindows. 7703 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 7704 return insets.consumeSystemWindowInsets(); 7705 } 7706 } 7707 return insets; 7708 } 7709 7710 /** 7711 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 7712 * window insets to this view. The listener's 7713 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 7714 * method will be called instead of the view's 7715 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 7716 * 7717 * @param listener Listener to set 7718 * 7719 * @see #onApplyWindowInsets(WindowInsets) 7720 */ 7721 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 7722 getListenerInfo().mOnApplyWindowInsetsListener = listener; 7723 } 7724 7725 /** 7726 * Request to apply the given window insets to this view or another view in its subtree. 7727 * 7728 * <p>This method should be called by clients wishing to apply insets corresponding to areas 7729 * obscured by window decorations or overlays. This can include the status and navigation bars, 7730 * action bars, input methods and more. New inset categories may be added in the future. 7731 * The method returns the insets provided minus any that were applied by this view or its 7732 * children.</p> 7733 * 7734 * <p>Clients wishing to provide custom behavior should override the 7735 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 7736 * {@link OnApplyWindowInsetsListener} via the 7737 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 7738 * method.</p> 7739 * 7740 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 7741 * </p> 7742 * 7743 * @param insets Insets to apply 7744 * @return The provided insets minus the insets that were consumed 7745 */ 7746 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 7747 try { 7748 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 7749 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 7750 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 7751 } else { 7752 return onApplyWindowInsets(insets); 7753 } 7754 } finally { 7755 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 7756 } 7757 } 7758 7759 /** 7760 * Compute the view's coordinate within the surface. 7761 * 7762 * <p>Computes the coordinates of this view in its surface. The argument 7763 * must be an array of two integers. After the method returns, the array 7764 * contains the x and y location in that order.</p> 7765 * @hide 7766 * @param location an array of two integers in which to hold the coordinates 7767 */ 7768 public void getLocationInSurface(@Size(2) int[] location) { 7769 getLocationInWindow(location); 7770 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 7771 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 7772 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 7773 } 7774 } 7775 7776 /** 7777 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 7778 * only available if the view is attached. 7779 * 7780 * @return WindowInsets from the top of the view hierarchy or null if View is detached 7781 */ 7782 public WindowInsets getRootWindowInsets() { 7783 if (mAttachInfo != null) { 7784 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 7785 } 7786 return null; 7787 } 7788 7789 /** 7790 * @hide Compute the insets that should be consumed by this view and the ones 7791 * that should propagate to those under it. 7792 */ 7793 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 7794 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7795 || mAttachInfo == null 7796 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 7797 && !mAttachInfo.mOverscanRequested)) { 7798 outLocalInsets.set(inoutInsets); 7799 inoutInsets.set(0, 0, 0, 0); 7800 return true; 7801 } else { 7802 // The application wants to take care of fitting system window for 7803 // the content... however we still need to take care of any overscan here. 7804 final Rect overscan = mAttachInfo.mOverscanInsets; 7805 outLocalInsets.set(overscan); 7806 inoutInsets.left -= overscan.left; 7807 inoutInsets.top -= overscan.top; 7808 inoutInsets.right -= overscan.right; 7809 inoutInsets.bottom -= overscan.bottom; 7810 return false; 7811 } 7812 } 7813 7814 /** 7815 * Compute insets that should be consumed by this view and the ones that should propagate 7816 * to those under it. 7817 * 7818 * @param in Insets currently being processed by this View, likely received as a parameter 7819 * to {@link #onApplyWindowInsets(WindowInsets)}. 7820 * @param outLocalInsets A Rect that will receive the insets that should be consumed 7821 * by this view 7822 * @return Insets that should be passed along to views under this one 7823 */ 7824 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 7825 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 7826 || mAttachInfo == null 7827 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 7828 outLocalInsets.set(in.getSystemWindowInsets()); 7829 return in.consumeSystemWindowInsets(); 7830 } else { 7831 outLocalInsets.set(0, 0, 0, 0); 7832 return in; 7833 } 7834 } 7835 7836 /** 7837 * Sets whether or not this view should account for system screen decorations 7838 * such as the status bar and inset its content; that is, controlling whether 7839 * the default implementation of {@link #fitSystemWindows(Rect)} will be 7840 * executed. See that method for more details. 7841 * 7842 * <p>Note that if you are providing your own implementation of 7843 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 7844 * flag to true -- your implementation will be overriding the default 7845 * implementation that checks this flag. 7846 * 7847 * @param fitSystemWindows If true, then the default implementation of 7848 * {@link #fitSystemWindows(Rect)} will be executed. 7849 * 7850 * @attr ref android.R.styleable#View_fitsSystemWindows 7851 * @see #getFitsSystemWindows() 7852 * @see #fitSystemWindows(Rect) 7853 * @see #setSystemUiVisibility(int) 7854 */ 7855 public void setFitsSystemWindows(boolean fitSystemWindows) { 7856 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 7857 } 7858 7859 /** 7860 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 7861 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 7862 * will be executed. 7863 * 7864 * @return {@code true} if the default implementation of 7865 * {@link #fitSystemWindows(Rect)} will be executed. 7866 * 7867 * @attr ref android.R.styleable#View_fitsSystemWindows 7868 * @see #setFitsSystemWindows(boolean) 7869 * @see #fitSystemWindows(Rect) 7870 * @see #setSystemUiVisibility(int) 7871 */ 7872 @ViewDebug.ExportedProperty 7873 public boolean getFitsSystemWindows() { 7874 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 7875 } 7876 7877 /** @hide */ 7878 public boolean fitsSystemWindows() { 7879 return getFitsSystemWindows(); 7880 } 7881 7882 /** 7883 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 7884 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 7885 */ 7886 public void requestFitSystemWindows() { 7887 if (mParent != null) { 7888 mParent.requestFitSystemWindows(); 7889 } 7890 } 7891 7892 /** 7893 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 7894 */ 7895 public void requestApplyInsets() { 7896 requestFitSystemWindows(); 7897 } 7898 7899 /** 7900 * For use by PhoneWindow to make its own system window fitting optional. 7901 * @hide 7902 */ 7903 public void makeOptionalFitsSystemWindows() { 7904 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 7905 } 7906 7907 /** 7908 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 7909 * treat them as such. 7910 * @hide 7911 */ 7912 public void getOutsets(Rect outOutsetRect) { 7913 if (mAttachInfo != null) { 7914 outOutsetRect.set(mAttachInfo.mOutsets); 7915 } else { 7916 outOutsetRect.setEmpty(); 7917 } 7918 } 7919 7920 /** 7921 * Returns the visibility status for this view. 7922 * 7923 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7924 * @attr ref android.R.styleable#View_visibility 7925 */ 7926 @ViewDebug.ExportedProperty(mapping = { 7927 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 7928 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 7929 @ViewDebug.IntToString(from = GONE, to = "GONE") 7930 }) 7931 @Visibility 7932 public int getVisibility() { 7933 return mViewFlags & VISIBILITY_MASK; 7934 } 7935 7936 /** 7937 * Set the enabled state of this view. 7938 * 7939 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 7940 * @attr ref android.R.styleable#View_visibility 7941 */ 7942 @RemotableViewMethod 7943 public void setVisibility(@Visibility int visibility) { 7944 setFlags(visibility, VISIBILITY_MASK); 7945 } 7946 7947 /** 7948 * Returns the enabled status for this view. The interpretation of the 7949 * enabled state varies by subclass. 7950 * 7951 * @return True if this view is enabled, false otherwise. 7952 */ 7953 @ViewDebug.ExportedProperty 7954 public boolean isEnabled() { 7955 return (mViewFlags & ENABLED_MASK) == ENABLED; 7956 } 7957 7958 /** 7959 * Set the enabled state of this view. The interpretation of the enabled 7960 * state varies by subclass. 7961 * 7962 * @param enabled True if this view is enabled, false otherwise. 7963 */ 7964 @RemotableViewMethod 7965 public void setEnabled(boolean enabled) { 7966 if (enabled == isEnabled()) return; 7967 7968 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 7969 7970 /* 7971 * The View most likely has to change its appearance, so refresh 7972 * the drawable state. 7973 */ 7974 refreshDrawableState(); 7975 7976 // Invalidate too, since the default behavior for views is to be 7977 // be drawn at 50% alpha rather than to change the drawable. 7978 invalidate(true); 7979 7980 if (!enabled) { 7981 cancelPendingInputEvents(); 7982 } 7983 } 7984 7985 /** 7986 * Set whether this view can receive the focus. 7987 * 7988 * Setting this to false will also ensure that this view is not focusable 7989 * in touch mode. 7990 * 7991 * @param focusable If true, this view can receive the focus. 7992 * 7993 * @see #setFocusableInTouchMode(boolean) 7994 * @attr ref android.R.styleable#View_focusable 7995 */ 7996 public void setFocusable(boolean focusable) { 7997 if (!focusable) { 7998 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 7999 } 8000 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 8001 } 8002 8003 /** 8004 * Set whether this view can receive focus while in touch mode. 8005 * 8006 * Setting this to true will also ensure that this view is focusable. 8007 * 8008 * @param focusableInTouchMode If true, this view can receive the focus while 8009 * in touch mode. 8010 * 8011 * @see #setFocusable(boolean) 8012 * @attr ref android.R.styleable#View_focusableInTouchMode 8013 */ 8014 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 8015 // Focusable in touch mode should always be set before the focusable flag 8016 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 8017 // which, in touch mode, will not successfully request focus on this view 8018 // because the focusable in touch mode flag is not set 8019 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 8020 if (focusableInTouchMode) { 8021 setFlags(FOCUSABLE, FOCUSABLE_MASK); 8022 } 8023 } 8024 8025 /** 8026 * Set whether this view should have sound effects enabled for events such as 8027 * clicking and touching. 8028 * 8029 * <p>You may wish to disable sound effects for a view if you already play sounds, 8030 * for instance, a dial key that plays dtmf tones. 8031 * 8032 * @param soundEffectsEnabled whether sound effects are enabled for this view. 8033 * @see #isSoundEffectsEnabled() 8034 * @see #playSoundEffect(int) 8035 * @attr ref android.R.styleable#View_soundEffectsEnabled 8036 */ 8037 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 8038 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 8039 } 8040 8041 /** 8042 * @return whether this view should have sound effects enabled for events such as 8043 * clicking and touching. 8044 * 8045 * @see #setSoundEffectsEnabled(boolean) 8046 * @see #playSoundEffect(int) 8047 * @attr ref android.R.styleable#View_soundEffectsEnabled 8048 */ 8049 @ViewDebug.ExportedProperty 8050 public boolean isSoundEffectsEnabled() { 8051 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 8052 } 8053 8054 /** 8055 * Set whether this view should have haptic feedback for events such as 8056 * long presses. 8057 * 8058 * <p>You may wish to disable haptic feedback if your view already controls 8059 * its own haptic feedback. 8060 * 8061 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 8062 * @see #isHapticFeedbackEnabled() 8063 * @see #performHapticFeedback(int) 8064 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8065 */ 8066 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 8067 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 8068 } 8069 8070 /** 8071 * @return whether this view should have haptic feedback enabled for events 8072 * long presses. 8073 * 8074 * @see #setHapticFeedbackEnabled(boolean) 8075 * @see #performHapticFeedback(int) 8076 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 8077 */ 8078 @ViewDebug.ExportedProperty 8079 public boolean isHapticFeedbackEnabled() { 8080 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 8081 } 8082 8083 /** 8084 * Returns the layout direction for this view. 8085 * 8086 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 8087 * {@link #LAYOUT_DIRECTION_RTL}, 8088 * {@link #LAYOUT_DIRECTION_INHERIT} or 8089 * {@link #LAYOUT_DIRECTION_LOCALE}. 8090 * 8091 * @attr ref android.R.styleable#View_layoutDirection 8092 * 8093 * @hide 8094 */ 8095 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8096 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 8097 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 8098 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 8099 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 8100 }) 8101 @LayoutDir 8102 public int getRawLayoutDirection() { 8103 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 8104 } 8105 8106 /** 8107 * Set the layout direction for this view. This will propagate a reset of layout direction 8108 * resolution to the view's children and resolve layout direction for this view. 8109 * 8110 * @param layoutDirection the layout direction to set. Should be one of: 8111 * 8112 * {@link #LAYOUT_DIRECTION_LTR}, 8113 * {@link #LAYOUT_DIRECTION_RTL}, 8114 * {@link #LAYOUT_DIRECTION_INHERIT}, 8115 * {@link #LAYOUT_DIRECTION_LOCALE}. 8116 * 8117 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 8118 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 8119 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 8120 * 8121 * @attr ref android.R.styleable#View_layoutDirection 8122 */ 8123 @RemotableViewMethod 8124 public void setLayoutDirection(@LayoutDir int layoutDirection) { 8125 if (getRawLayoutDirection() != layoutDirection) { 8126 // Reset the current layout direction and the resolved one 8127 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 8128 resetRtlProperties(); 8129 // Set the new layout direction (filtered) 8130 mPrivateFlags2 |= 8131 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 8132 // We need to resolve all RTL properties as they all depend on layout direction 8133 resolveRtlPropertiesIfNeeded(); 8134 requestLayout(); 8135 invalidate(true); 8136 } 8137 } 8138 8139 /** 8140 * Returns the resolved layout direction for this view. 8141 * 8142 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 8143 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 8144 * 8145 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 8146 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 8147 * 8148 * @attr ref android.R.styleable#View_layoutDirection 8149 */ 8150 @ViewDebug.ExportedProperty(category = "layout", mapping = { 8151 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 8152 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 8153 }) 8154 @ResolvedLayoutDir 8155 public int getLayoutDirection() { 8156 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 8157 if (targetSdkVersion < JELLY_BEAN_MR1) { 8158 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 8159 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 8160 } 8161 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 8162 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 8163 } 8164 8165 /** 8166 * Indicates whether or not this view's layout is right-to-left. This is resolved from 8167 * layout attribute and/or the inherited value from the parent 8168 * 8169 * @return true if the layout is right-to-left. 8170 * 8171 * @hide 8172 */ 8173 @ViewDebug.ExportedProperty(category = "layout") 8174 public boolean isLayoutRtl() { 8175 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 8176 } 8177 8178 /** 8179 * Indicates whether the view is currently tracking transient state that the 8180 * app should not need to concern itself with saving and restoring, but that 8181 * the framework should take special note to preserve when possible. 8182 * 8183 * <p>A view with transient state cannot be trivially rebound from an external 8184 * data source, such as an adapter binding item views in a list. This may be 8185 * because the view is performing an animation, tracking user selection 8186 * of content, or similar.</p> 8187 * 8188 * @return true if the view has transient state 8189 */ 8190 @ViewDebug.ExportedProperty(category = "layout") 8191 public boolean hasTransientState() { 8192 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 8193 } 8194 8195 /** 8196 * Set whether this view is currently tracking transient state that the 8197 * framework should attempt to preserve when possible. This flag is reference counted, 8198 * so every call to setHasTransientState(true) should be paired with a later call 8199 * to setHasTransientState(false). 8200 * 8201 * <p>A view with transient state cannot be trivially rebound from an external 8202 * data source, such as an adapter binding item views in a list. This may be 8203 * because the view is performing an animation, tracking user selection 8204 * of content, or similar.</p> 8205 * 8206 * @param hasTransientState true if this view has transient state 8207 */ 8208 public void setHasTransientState(boolean hasTransientState) { 8209 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 8210 mTransientStateCount - 1; 8211 if (mTransientStateCount < 0) { 8212 mTransientStateCount = 0; 8213 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 8214 "unmatched pair of setHasTransientState calls"); 8215 } else if ((hasTransientState && mTransientStateCount == 1) || 8216 (!hasTransientState && mTransientStateCount == 0)) { 8217 // update flag if we've just incremented up from 0 or decremented down to 0 8218 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 8219 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 8220 if (mParent != null) { 8221 try { 8222 mParent.childHasTransientStateChanged(this, hasTransientState); 8223 } catch (AbstractMethodError e) { 8224 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 8225 " does not fully implement ViewParent", e); 8226 } 8227 } 8228 } 8229 } 8230 8231 /** 8232 * Returns true if this view is currently attached to a window. 8233 */ 8234 public boolean isAttachedToWindow() { 8235 return mAttachInfo != null; 8236 } 8237 8238 /** 8239 * Returns true if this view has been through at least one layout since it 8240 * was last attached to or detached from a window. 8241 */ 8242 public boolean isLaidOut() { 8243 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 8244 } 8245 8246 /** 8247 * If this view doesn't do any drawing on its own, set this flag to 8248 * allow further optimizations. By default, this flag is not set on 8249 * View, but could be set on some View subclasses such as ViewGroup. 8250 * 8251 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 8252 * you should clear this flag. 8253 * 8254 * @param willNotDraw whether or not this View draw on its own 8255 */ 8256 public void setWillNotDraw(boolean willNotDraw) { 8257 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 8258 } 8259 8260 /** 8261 * Returns whether or not this View draws on its own. 8262 * 8263 * @return true if this view has nothing to draw, false otherwise 8264 */ 8265 @ViewDebug.ExportedProperty(category = "drawing") 8266 public boolean willNotDraw() { 8267 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 8268 } 8269 8270 /** 8271 * When a View's drawing cache is enabled, drawing is redirected to an 8272 * offscreen bitmap. Some views, like an ImageView, must be able to 8273 * bypass this mechanism if they already draw a single bitmap, to avoid 8274 * unnecessary usage of the memory. 8275 * 8276 * @param willNotCacheDrawing true if this view does not cache its 8277 * drawing, false otherwise 8278 */ 8279 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 8280 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 8281 } 8282 8283 /** 8284 * Returns whether or not this View can cache its drawing or not. 8285 * 8286 * @return true if this view does not cache its drawing, false otherwise 8287 */ 8288 @ViewDebug.ExportedProperty(category = "drawing") 8289 public boolean willNotCacheDrawing() { 8290 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 8291 } 8292 8293 /** 8294 * Indicates whether this view reacts to click events or not. 8295 * 8296 * @return true if the view is clickable, false otherwise 8297 * 8298 * @see #setClickable(boolean) 8299 * @attr ref android.R.styleable#View_clickable 8300 */ 8301 @ViewDebug.ExportedProperty 8302 public boolean isClickable() { 8303 return (mViewFlags & CLICKABLE) == CLICKABLE; 8304 } 8305 8306 /** 8307 * Enables or disables click events for this view. When a view 8308 * is clickable it will change its state to "pressed" on every click. 8309 * Subclasses should set the view clickable to visually react to 8310 * user's clicks. 8311 * 8312 * @param clickable true to make the view clickable, false otherwise 8313 * 8314 * @see #isClickable() 8315 * @attr ref android.R.styleable#View_clickable 8316 */ 8317 public void setClickable(boolean clickable) { 8318 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 8319 } 8320 8321 /** 8322 * Indicates whether this view reacts to long click events or not. 8323 * 8324 * @return true if the view is long clickable, false otherwise 8325 * 8326 * @see #setLongClickable(boolean) 8327 * @attr ref android.R.styleable#View_longClickable 8328 */ 8329 public boolean isLongClickable() { 8330 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 8331 } 8332 8333 /** 8334 * Enables or disables long click events for this view. When a view is long 8335 * clickable it reacts to the user holding down the button for a longer 8336 * duration than a tap. This event can either launch the listener or a 8337 * context menu. 8338 * 8339 * @param longClickable true to make the view long clickable, false otherwise 8340 * @see #isLongClickable() 8341 * @attr ref android.R.styleable#View_longClickable 8342 */ 8343 public void setLongClickable(boolean longClickable) { 8344 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 8345 } 8346 8347 /** 8348 * Indicates whether this view reacts to context clicks or not. 8349 * 8350 * @return true if the view is context clickable, false otherwise 8351 * @see #setContextClickable(boolean) 8352 * @attr ref android.R.styleable#View_contextClickable 8353 */ 8354 public boolean isContextClickable() { 8355 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 8356 } 8357 8358 /** 8359 * Enables or disables context clicking for this view. This event can launch the listener. 8360 * 8361 * @param contextClickable true to make the view react to a context click, false otherwise 8362 * @see #isContextClickable() 8363 * @attr ref android.R.styleable#View_contextClickable 8364 */ 8365 public void setContextClickable(boolean contextClickable) { 8366 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 8367 } 8368 8369 /** 8370 * Sets the pressed state for this view and provides a touch coordinate for 8371 * animation hinting. 8372 * 8373 * @param pressed Pass true to set the View's internal state to "pressed", 8374 * or false to reverts the View's internal state from a 8375 * previously set "pressed" state. 8376 * @param x The x coordinate of the touch that caused the press 8377 * @param y The y coordinate of the touch that caused the press 8378 */ 8379 private void setPressed(boolean pressed, float x, float y) { 8380 if (pressed) { 8381 drawableHotspotChanged(x, y); 8382 } 8383 8384 setPressed(pressed); 8385 } 8386 8387 /** 8388 * Sets the pressed state for this view. 8389 * 8390 * @see #isClickable() 8391 * @see #setClickable(boolean) 8392 * 8393 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 8394 * the View's internal state from a previously set "pressed" state. 8395 */ 8396 public void setPressed(boolean pressed) { 8397 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 8398 8399 if (pressed) { 8400 mPrivateFlags |= PFLAG_PRESSED; 8401 } else { 8402 mPrivateFlags &= ~PFLAG_PRESSED; 8403 } 8404 8405 if (needsRefresh) { 8406 refreshDrawableState(); 8407 } 8408 dispatchSetPressed(pressed); 8409 } 8410 8411 /** 8412 * Dispatch setPressed to all of this View's children. 8413 * 8414 * @see #setPressed(boolean) 8415 * 8416 * @param pressed The new pressed state 8417 */ 8418 protected void dispatchSetPressed(boolean pressed) { 8419 } 8420 8421 /** 8422 * Indicates whether the view is currently in pressed state. Unless 8423 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 8424 * the pressed state. 8425 * 8426 * @see #setPressed(boolean) 8427 * @see #isClickable() 8428 * @see #setClickable(boolean) 8429 * 8430 * @return true if the view is currently pressed, false otherwise 8431 */ 8432 @ViewDebug.ExportedProperty 8433 public boolean isPressed() { 8434 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 8435 } 8436 8437 /** 8438 * @hide 8439 * Indicates whether this view will participate in data collection through 8440 * {@link ViewStructure}. If true, it will not provide any data 8441 * for itself or its children. If false, the normal data collection will be allowed. 8442 * 8443 * @return Returns false if assist data collection is not blocked, else true. 8444 * 8445 * @see #setAssistBlocked(boolean) 8446 * @attr ref android.R.styleable#View_assistBlocked 8447 */ 8448 public boolean isAssistBlocked() { 8449 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 8450 } 8451 8452 /** 8453 * @hide 8454 * Controls whether assist data collection from this view and its children is enabled 8455 * (that is, whether {@link #onProvideStructure} and 8456 * {@link #onProvideVirtualStructure} will be called). The default value is false, 8457 * allowing normal assist collection. Setting this to false will disable assist collection. 8458 * 8459 * @param enabled Set to true to <em>disable</em> assist data collection, or false 8460 * (the default) to allow it. 8461 * 8462 * @see #isAssistBlocked() 8463 * @see #onProvideStructure 8464 * @see #onProvideVirtualStructure 8465 * @attr ref android.R.styleable#View_assistBlocked 8466 */ 8467 public void setAssistBlocked(boolean enabled) { 8468 if (enabled) { 8469 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 8470 } else { 8471 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 8472 } 8473 } 8474 8475 /** 8476 * Indicates whether this view will save its state (that is, 8477 * whether its {@link #onSaveInstanceState} method will be called). 8478 * 8479 * @return Returns true if the view state saving is enabled, else false. 8480 * 8481 * @see #setSaveEnabled(boolean) 8482 * @attr ref android.R.styleable#View_saveEnabled 8483 */ 8484 public boolean isSaveEnabled() { 8485 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 8486 } 8487 8488 /** 8489 * Controls whether the saving of this view's state is 8490 * enabled (that is, whether its {@link #onSaveInstanceState} method 8491 * will be called). Note that even if freezing is enabled, the 8492 * view still must have an id assigned to it (via {@link #setId(int)}) 8493 * for its state to be saved. This flag can only disable the 8494 * saving of this view; any child views may still have their state saved. 8495 * 8496 * @param enabled Set to false to <em>disable</em> state saving, or true 8497 * (the default) to allow it. 8498 * 8499 * @see #isSaveEnabled() 8500 * @see #setId(int) 8501 * @see #onSaveInstanceState() 8502 * @attr ref android.R.styleable#View_saveEnabled 8503 */ 8504 public void setSaveEnabled(boolean enabled) { 8505 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 8506 } 8507 8508 /** 8509 * Gets whether the framework should discard touches when the view's 8510 * window is obscured by another visible window. 8511 * Refer to the {@link View} security documentation for more details. 8512 * 8513 * @return True if touch filtering is enabled. 8514 * 8515 * @see #setFilterTouchesWhenObscured(boolean) 8516 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8517 */ 8518 @ViewDebug.ExportedProperty 8519 public boolean getFilterTouchesWhenObscured() { 8520 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 8521 } 8522 8523 /** 8524 * Sets whether the framework should discard touches when the view's 8525 * window is obscured by another visible window. 8526 * Refer to the {@link View} security documentation for more details. 8527 * 8528 * @param enabled True if touch filtering should be enabled. 8529 * 8530 * @see #getFilterTouchesWhenObscured 8531 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 8532 */ 8533 public void setFilterTouchesWhenObscured(boolean enabled) { 8534 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 8535 FILTER_TOUCHES_WHEN_OBSCURED); 8536 } 8537 8538 /** 8539 * Indicates whether the entire hierarchy under this view will save its 8540 * state when a state saving traversal occurs from its parent. The default 8541 * is true; if false, these views will not be saved unless 8542 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8543 * 8544 * @return Returns true if the view state saving from parent is enabled, else false. 8545 * 8546 * @see #setSaveFromParentEnabled(boolean) 8547 */ 8548 public boolean isSaveFromParentEnabled() { 8549 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 8550 } 8551 8552 /** 8553 * Controls whether the entire hierarchy under this view will save its 8554 * state when a state saving traversal occurs from its parent. The default 8555 * is true; if false, these views will not be saved unless 8556 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 8557 * 8558 * @param enabled Set to false to <em>disable</em> state saving, or true 8559 * (the default) to allow it. 8560 * 8561 * @see #isSaveFromParentEnabled() 8562 * @see #setId(int) 8563 * @see #onSaveInstanceState() 8564 */ 8565 public void setSaveFromParentEnabled(boolean enabled) { 8566 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 8567 } 8568 8569 8570 /** 8571 * Returns whether this View is able to take focus. 8572 * 8573 * @return True if this view can take focus, or false otherwise. 8574 * @attr ref android.R.styleable#View_focusable 8575 */ 8576 @ViewDebug.ExportedProperty(category = "focus") 8577 public final boolean isFocusable() { 8578 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 8579 } 8580 8581 /** 8582 * When a view is focusable, it may not want to take focus when in touch mode. 8583 * For example, a button would like focus when the user is navigating via a D-pad 8584 * so that the user can click on it, but once the user starts touching the screen, 8585 * the button shouldn't take focus 8586 * @return Whether the view is focusable in touch mode. 8587 * @attr ref android.R.styleable#View_focusableInTouchMode 8588 */ 8589 @ViewDebug.ExportedProperty 8590 public final boolean isFocusableInTouchMode() { 8591 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 8592 } 8593 8594 /** 8595 * Find the nearest view in the specified direction that can take focus. 8596 * This does not actually give focus to that view. 8597 * 8598 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8599 * 8600 * @return The nearest focusable in the specified direction, or null if none 8601 * can be found. 8602 */ 8603 public View focusSearch(@FocusRealDirection int direction) { 8604 if (mParent != null) { 8605 return mParent.focusSearch(this, direction); 8606 } else { 8607 return null; 8608 } 8609 } 8610 8611 /** 8612 * This method is the last chance for the focused view and its ancestors to 8613 * respond to an arrow key. This is called when the focused view did not 8614 * consume the key internally, nor could the view system find a new view in 8615 * the requested direction to give focus to. 8616 * 8617 * @param focused The currently focused view. 8618 * @param direction The direction focus wants to move. One of FOCUS_UP, 8619 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 8620 * @return True if the this view consumed this unhandled move. 8621 */ 8622 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 8623 return false; 8624 } 8625 8626 /** 8627 * If a user manually specified the next view id for a particular direction, 8628 * use the root to look up the view. 8629 * @param root The root view of the hierarchy containing this view. 8630 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 8631 * or FOCUS_BACKWARD. 8632 * @return The user specified next view, or null if there is none. 8633 */ 8634 View findUserSetNextFocus(View root, @FocusDirection int direction) { 8635 switch (direction) { 8636 case FOCUS_LEFT: 8637 if (mNextFocusLeftId == View.NO_ID) return null; 8638 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 8639 case FOCUS_RIGHT: 8640 if (mNextFocusRightId == View.NO_ID) return null; 8641 return findViewInsideOutShouldExist(root, mNextFocusRightId); 8642 case FOCUS_UP: 8643 if (mNextFocusUpId == View.NO_ID) return null; 8644 return findViewInsideOutShouldExist(root, mNextFocusUpId); 8645 case FOCUS_DOWN: 8646 if (mNextFocusDownId == View.NO_ID) return null; 8647 return findViewInsideOutShouldExist(root, mNextFocusDownId); 8648 case FOCUS_FORWARD: 8649 if (mNextFocusForwardId == View.NO_ID) return null; 8650 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 8651 case FOCUS_BACKWARD: { 8652 if (mID == View.NO_ID) return null; 8653 final int id = mID; 8654 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 8655 @Override 8656 public boolean apply(View t) { 8657 return t.mNextFocusForwardId == id; 8658 } 8659 }); 8660 } 8661 } 8662 return null; 8663 } 8664 8665 private View findViewInsideOutShouldExist(View root, int id) { 8666 if (mMatchIdPredicate == null) { 8667 mMatchIdPredicate = new MatchIdPredicate(); 8668 } 8669 mMatchIdPredicate.mId = id; 8670 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 8671 if (result == null) { 8672 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 8673 } 8674 return result; 8675 } 8676 8677 /** 8678 * Find and return all focusable views that are descendants of this view, 8679 * possibly including this view if it is focusable itself. 8680 * 8681 * @param direction The direction of the focus 8682 * @return A list of focusable views 8683 */ 8684 public ArrayList<View> getFocusables(@FocusDirection int direction) { 8685 ArrayList<View> result = new ArrayList<View>(24); 8686 addFocusables(result, direction); 8687 return result; 8688 } 8689 8690 /** 8691 * Add any focusable views that are descendants of this view (possibly 8692 * including this view if it is focusable itself) to views. If we are in touch mode, 8693 * only add views that are also focusable in touch mode. 8694 * 8695 * @param views Focusable views found so far 8696 * @param direction The direction of the focus 8697 */ 8698 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 8699 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 8700 } 8701 8702 /** 8703 * Adds any focusable views that are descendants of this view (possibly 8704 * including this view if it is focusable itself) to views. This method 8705 * adds all focusable views regardless if we are in touch mode or 8706 * only views focusable in touch mode if we are in touch mode or 8707 * only views that can take accessibility focus if accessibility is enabled 8708 * depending on the focusable mode parameter. 8709 * 8710 * @param views Focusable views found so far or null if all we are interested is 8711 * the number of focusables. 8712 * @param direction The direction of the focus. 8713 * @param focusableMode The type of focusables to be added. 8714 * 8715 * @see #FOCUSABLES_ALL 8716 * @see #FOCUSABLES_TOUCH_MODE 8717 */ 8718 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 8719 @FocusableMode int focusableMode) { 8720 if (views == null) { 8721 return; 8722 } 8723 if (!isFocusable()) { 8724 return; 8725 } 8726 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 8727 && isInTouchMode() && !isFocusableInTouchMode()) { 8728 return; 8729 } 8730 views.add(this); 8731 } 8732 8733 /** 8734 * Finds the Views that contain given text. The containment is case insensitive. 8735 * The search is performed by either the text that the View renders or the content 8736 * description that describes the view for accessibility purposes and the view does 8737 * not render or both. Clients can specify how the search is to be performed via 8738 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 8739 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 8740 * 8741 * @param outViews The output list of matching Views. 8742 * @param searched The text to match against. 8743 * 8744 * @see #FIND_VIEWS_WITH_TEXT 8745 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 8746 * @see #setContentDescription(CharSequence) 8747 */ 8748 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 8749 @FindViewFlags int flags) { 8750 if (getAccessibilityNodeProvider() != null) { 8751 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 8752 outViews.add(this); 8753 } 8754 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 8755 && (searched != null && searched.length() > 0) 8756 && (mContentDescription != null && mContentDescription.length() > 0)) { 8757 String searchedLowerCase = searched.toString().toLowerCase(); 8758 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 8759 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 8760 outViews.add(this); 8761 } 8762 } 8763 } 8764 8765 /** 8766 * Find and return all touchable views that are descendants of this view, 8767 * possibly including this view if it is touchable itself. 8768 * 8769 * @return A list of touchable views 8770 */ 8771 public ArrayList<View> getTouchables() { 8772 ArrayList<View> result = new ArrayList<View>(); 8773 addTouchables(result); 8774 return result; 8775 } 8776 8777 /** 8778 * Add any touchable views that are descendants of this view (possibly 8779 * including this view if it is touchable itself) to views. 8780 * 8781 * @param views Touchable views found so far 8782 */ 8783 public void addTouchables(ArrayList<View> views) { 8784 final int viewFlags = mViewFlags; 8785 8786 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 8787 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 8788 && (viewFlags & ENABLED_MASK) == ENABLED) { 8789 views.add(this); 8790 } 8791 } 8792 8793 /** 8794 * Returns whether this View is accessibility focused. 8795 * 8796 * @return True if this View is accessibility focused. 8797 */ 8798 public boolean isAccessibilityFocused() { 8799 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 8800 } 8801 8802 /** 8803 * Call this to try to give accessibility focus to this view. 8804 * 8805 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 8806 * returns false or the view is no visible or the view already has accessibility 8807 * focus. 8808 * 8809 * See also {@link #focusSearch(int)}, which is what you call to say that you 8810 * have focus, and you want your parent to look for the next one. 8811 * 8812 * @return Whether this view actually took accessibility focus. 8813 * 8814 * @hide 8815 */ 8816 public boolean requestAccessibilityFocus() { 8817 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 8818 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 8819 return false; 8820 } 8821 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8822 return false; 8823 } 8824 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 8825 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 8826 ViewRootImpl viewRootImpl = getViewRootImpl(); 8827 if (viewRootImpl != null) { 8828 viewRootImpl.setAccessibilityFocus(this, null); 8829 } 8830 invalidate(); 8831 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 8832 return true; 8833 } 8834 return false; 8835 } 8836 8837 /** 8838 * Call this to try to clear accessibility focus of this view. 8839 * 8840 * See also {@link #focusSearch(int)}, which is what you call to say that you 8841 * have focus, and you want your parent to look for the next one. 8842 * 8843 * @hide 8844 */ 8845 public void clearAccessibilityFocus() { 8846 clearAccessibilityFocusNoCallbacks(); 8847 8848 // Clear the global reference of accessibility focus if this view or 8849 // any of its descendants had accessibility focus. This will NOT send 8850 // an event or update internal state if focus is cleared from a 8851 // descendant view, which may leave views in inconsistent states. 8852 final ViewRootImpl viewRootImpl = getViewRootImpl(); 8853 if (viewRootImpl != null) { 8854 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 8855 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 8856 viewRootImpl.setAccessibilityFocus(null, null); 8857 } 8858 } 8859 } 8860 8861 private void sendAccessibilityHoverEvent(int eventType) { 8862 // Since we are not delivering to a client accessibility events from not 8863 // important views (unless the clinet request that) we need to fire the 8864 // event from the deepest view exposed to the client. As a consequence if 8865 // the user crosses a not exposed view the client will see enter and exit 8866 // of the exposed predecessor followed by and enter and exit of that same 8867 // predecessor when entering and exiting the not exposed descendant. This 8868 // is fine since the client has a clear idea which view is hovered at the 8869 // price of a couple more events being sent. This is a simple and 8870 // working solution. 8871 View source = this; 8872 while (true) { 8873 if (source.includeForAccessibility()) { 8874 source.sendAccessibilityEvent(eventType); 8875 return; 8876 } 8877 ViewParent parent = source.getParent(); 8878 if (parent instanceof View) { 8879 source = (View) parent; 8880 } else { 8881 return; 8882 } 8883 } 8884 } 8885 8886 /** 8887 * Clears accessibility focus without calling any callback methods 8888 * normally invoked in {@link #clearAccessibilityFocus()}. This method 8889 * is used for clearing accessibility focus when giving this focus to 8890 * another view. 8891 */ 8892 void clearAccessibilityFocusNoCallbacks() { 8893 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 8894 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 8895 invalidate(); 8896 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 8897 } 8898 } 8899 8900 /** 8901 * Call this to try to give focus to a specific view or to one of its 8902 * descendants. 8903 * 8904 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8905 * false), or if it is focusable and it is not focusable in touch mode 8906 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8907 * 8908 * See also {@link #focusSearch(int)}, which is what you call to say that you 8909 * have focus, and you want your parent to look for the next one. 8910 * 8911 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 8912 * {@link #FOCUS_DOWN} and <code>null</code>. 8913 * 8914 * @return Whether this view or one of its descendants actually took focus. 8915 */ 8916 public final boolean requestFocus() { 8917 return requestFocus(View.FOCUS_DOWN); 8918 } 8919 8920 /** 8921 * Call this to try to give focus to a specific view or to one of its 8922 * descendants and give it a hint about what direction focus is heading. 8923 * 8924 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8925 * false), or if it is focusable and it is not focusable in touch mode 8926 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8927 * 8928 * See also {@link #focusSearch(int)}, which is what you call to say that you 8929 * have focus, and you want your parent to look for the next one. 8930 * 8931 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 8932 * <code>null</code> set for the previously focused rectangle. 8933 * 8934 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8935 * @return Whether this view or one of its descendants actually took focus. 8936 */ 8937 public final boolean requestFocus(int direction) { 8938 return requestFocus(direction, null); 8939 } 8940 8941 /** 8942 * Call this to try to give focus to a specific view or to one of its descendants 8943 * and give it hints about the direction and a specific rectangle that the focus 8944 * is coming from. The rectangle can help give larger views a finer grained hint 8945 * about where focus is coming from, and therefore, where to show selection, or 8946 * forward focus change internally. 8947 * 8948 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 8949 * false), or if it is focusable and it is not focusable in touch mode 8950 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 8951 * 8952 * A View will not take focus if it is not visible. 8953 * 8954 * A View will not take focus if one of its parents has 8955 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 8956 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 8957 * 8958 * See also {@link #focusSearch(int)}, which is what you call to say that you 8959 * have focus, and you want your parent to look for the next one. 8960 * 8961 * You may wish to override this method if your custom {@link View} has an internal 8962 * {@link View} that it wishes to forward the request to. 8963 * 8964 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 8965 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 8966 * to give a finer grained hint about where focus is coming from. May be null 8967 * if there is no hint. 8968 * @return Whether this view or one of its descendants actually took focus. 8969 */ 8970 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 8971 return requestFocusNoSearch(direction, previouslyFocusedRect); 8972 } 8973 8974 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 8975 // need to be focusable 8976 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 8977 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8978 return false; 8979 } 8980 8981 // need to be focusable in touch mode if in touch mode 8982 if (isInTouchMode() && 8983 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 8984 return false; 8985 } 8986 8987 // need to not have any parents blocking us 8988 if (hasAncestorThatBlocksDescendantFocus()) { 8989 return false; 8990 } 8991 8992 handleFocusGainInternal(direction, previouslyFocusedRect); 8993 return true; 8994 } 8995 8996 /** 8997 * Call this to try to give focus to a specific view or to one of its descendants. This is a 8998 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 8999 * touch mode to request focus when they are touched. 9000 * 9001 * @return Whether this view or one of its descendants actually took focus. 9002 * 9003 * @see #isInTouchMode() 9004 * 9005 */ 9006 public final boolean requestFocusFromTouch() { 9007 // Leave touch mode if we need to 9008 if (isInTouchMode()) { 9009 ViewRootImpl viewRoot = getViewRootImpl(); 9010 if (viewRoot != null) { 9011 viewRoot.ensureTouchMode(false); 9012 } 9013 } 9014 return requestFocus(View.FOCUS_DOWN); 9015 } 9016 9017 /** 9018 * @return Whether any ancestor of this view blocks descendant focus. 9019 */ 9020 private boolean hasAncestorThatBlocksDescendantFocus() { 9021 final boolean focusableInTouchMode = isFocusableInTouchMode(); 9022 ViewParent ancestor = mParent; 9023 while (ancestor instanceof ViewGroup) { 9024 final ViewGroup vgAncestor = (ViewGroup) ancestor; 9025 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 9026 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 9027 return true; 9028 } else { 9029 ancestor = vgAncestor.getParent(); 9030 } 9031 } 9032 return false; 9033 } 9034 9035 /** 9036 * Gets the mode for determining whether this View is important for accessibility 9037 * which is if it fires accessibility events and if it is reported to 9038 * accessibility services that query the screen. 9039 * 9040 * @return The mode for determining whether a View is important for accessibility. 9041 * 9042 * @attr ref android.R.styleable#View_importantForAccessibility 9043 * 9044 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9045 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9046 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9047 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9048 */ 9049 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 9050 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 9051 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 9052 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 9053 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 9054 to = "noHideDescendants") 9055 }) 9056 public int getImportantForAccessibility() { 9057 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9058 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9059 } 9060 9061 /** 9062 * Sets the live region mode for this view. This indicates to accessibility 9063 * services whether they should automatically notify the user about changes 9064 * to the view's content description or text, or to the content descriptions 9065 * or text of the view's children (where applicable). 9066 * <p> 9067 * For example, in a login screen with a TextView that displays an "incorrect 9068 * password" notification, that view should be marked as a live region with 9069 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9070 * <p> 9071 * To disable change notifications for this view, use 9072 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 9073 * mode for most views. 9074 * <p> 9075 * To indicate that the user should be notified of changes, use 9076 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 9077 * <p> 9078 * If the view's changes should interrupt ongoing speech and notify the user 9079 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 9080 * 9081 * @param mode The live region mode for this view, one of: 9082 * <ul> 9083 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 9084 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 9085 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 9086 * </ul> 9087 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9088 */ 9089 public void setAccessibilityLiveRegion(int mode) { 9090 if (mode != getAccessibilityLiveRegion()) { 9091 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9092 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 9093 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 9094 notifyViewAccessibilityStateChangedIfNeeded( 9095 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9096 } 9097 } 9098 9099 /** 9100 * Gets the live region mode for this View. 9101 * 9102 * @return The live region mode for the view. 9103 * 9104 * @attr ref android.R.styleable#View_accessibilityLiveRegion 9105 * 9106 * @see #setAccessibilityLiveRegion(int) 9107 */ 9108 public int getAccessibilityLiveRegion() { 9109 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 9110 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 9111 } 9112 9113 /** 9114 * Sets how to determine whether this view is important for accessibility 9115 * which is if it fires accessibility events and if it is reported to 9116 * accessibility services that query the screen. 9117 * 9118 * @param mode How to determine whether this view is important for accessibility. 9119 * 9120 * @attr ref android.R.styleable#View_importantForAccessibility 9121 * 9122 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 9123 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 9124 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 9125 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 9126 */ 9127 public void setImportantForAccessibility(int mode) { 9128 final int oldMode = getImportantForAccessibility(); 9129 if (mode != oldMode) { 9130 final boolean hideDescendants = 9131 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 9132 9133 // If this node or its descendants are no longer important, try to 9134 // clear accessibility focus. 9135 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 9136 final View focusHost = findAccessibilityFocusHost(hideDescendants); 9137 if (focusHost != null) { 9138 focusHost.clearAccessibilityFocus(); 9139 } 9140 } 9141 9142 // If we're moving between AUTO and another state, we might not need 9143 // to send a subtree changed notification. We'll store the computed 9144 // importance, since we'll need to check it later to make sure. 9145 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 9146 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 9147 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 9148 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9149 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 9150 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 9151 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 9152 notifySubtreeAccessibilityStateChangedIfNeeded(); 9153 } else { 9154 notifyViewAccessibilityStateChangedIfNeeded( 9155 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9156 } 9157 } 9158 } 9159 9160 /** 9161 * Returns the view within this view's hierarchy that is hosting 9162 * accessibility focus. 9163 * 9164 * @param searchDescendants whether to search for focus in descendant views 9165 * @return the view hosting accessibility focus, or {@code null} 9166 */ 9167 private View findAccessibilityFocusHost(boolean searchDescendants) { 9168 if (isAccessibilityFocusedViewOrHost()) { 9169 return this; 9170 } 9171 9172 if (searchDescendants) { 9173 final ViewRootImpl viewRoot = getViewRootImpl(); 9174 if (viewRoot != null) { 9175 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 9176 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 9177 return focusHost; 9178 } 9179 } 9180 } 9181 9182 return null; 9183 } 9184 9185 /** 9186 * Computes whether this view should be exposed for accessibility. In 9187 * general, views that are interactive or provide information are exposed 9188 * while views that serve only as containers are hidden. 9189 * <p> 9190 * If an ancestor of this view has importance 9191 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 9192 * returns <code>false</code>. 9193 * <p> 9194 * Otherwise, the value is computed according to the view's 9195 * {@link #getImportantForAccessibility()} value: 9196 * <ol> 9197 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 9198 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 9199 * </code> 9200 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 9201 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 9202 * view satisfies any of the following: 9203 * <ul> 9204 * <li>Is actionable, e.g. {@link #isClickable()}, 9205 * {@link #isLongClickable()}, or {@link #isFocusable()} 9206 * <li>Has an {@link AccessibilityDelegate} 9207 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 9208 * {@link OnKeyListener}, etc. 9209 * <li>Is an accessibility live region, e.g. 9210 * {@link #getAccessibilityLiveRegion()} is not 9211 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 9212 * </ul> 9213 * </ol> 9214 * 9215 * @return Whether the view is exposed for accessibility. 9216 * @see #setImportantForAccessibility(int) 9217 * @see #getImportantForAccessibility() 9218 */ 9219 public boolean isImportantForAccessibility() { 9220 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 9221 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 9222 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 9223 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9224 return false; 9225 } 9226 9227 // Check parent mode to ensure we're not hidden. 9228 ViewParent parent = mParent; 9229 while (parent instanceof View) { 9230 if (((View) parent).getImportantForAccessibility() 9231 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 9232 return false; 9233 } 9234 parent = parent.getParent(); 9235 } 9236 9237 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 9238 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 9239 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 9240 } 9241 9242 /** 9243 * Gets the parent for accessibility purposes. Note that the parent for 9244 * accessibility is not necessary the immediate parent. It is the first 9245 * predecessor that is important for accessibility. 9246 * 9247 * @return The parent for accessibility purposes. 9248 */ 9249 public ViewParent getParentForAccessibility() { 9250 if (mParent instanceof View) { 9251 View parentView = (View) mParent; 9252 if (parentView.includeForAccessibility()) { 9253 return mParent; 9254 } else { 9255 return mParent.getParentForAccessibility(); 9256 } 9257 } 9258 return null; 9259 } 9260 9261 /** 9262 * Adds the children of this View relevant for accessibility to the given list 9263 * as output. Since some Views are not important for accessibility the added 9264 * child views are not necessarily direct children of this view, rather they are 9265 * the first level of descendants important for accessibility. 9266 * 9267 * @param outChildren The output list that will receive children for accessibility. 9268 */ 9269 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 9270 9271 } 9272 9273 /** 9274 * Whether to regard this view for accessibility. A view is regarded for 9275 * accessibility if it is important for accessibility or the querying 9276 * accessibility service has explicitly requested that view not 9277 * important for accessibility are regarded. 9278 * 9279 * @return Whether to regard the view for accessibility. 9280 * 9281 * @hide 9282 */ 9283 public boolean includeForAccessibility() { 9284 if (mAttachInfo != null) { 9285 return (mAttachInfo.mAccessibilityFetchFlags 9286 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 9287 || isImportantForAccessibility(); 9288 } 9289 return false; 9290 } 9291 9292 /** 9293 * Returns whether the View is considered actionable from 9294 * accessibility perspective. Such view are important for 9295 * accessibility. 9296 * 9297 * @return True if the view is actionable for accessibility. 9298 * 9299 * @hide 9300 */ 9301 public boolean isActionableForAccessibility() { 9302 return (isClickable() || isLongClickable() || isFocusable()); 9303 } 9304 9305 /** 9306 * Returns whether the View has registered callbacks which makes it 9307 * important for accessibility. 9308 * 9309 * @return True if the view is actionable for accessibility. 9310 */ 9311 private boolean hasListenersForAccessibility() { 9312 ListenerInfo info = getListenerInfo(); 9313 return mTouchDelegate != null || info.mOnKeyListener != null 9314 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 9315 || info.mOnHoverListener != null || info.mOnDragListener != null; 9316 } 9317 9318 /** 9319 * Notifies that the accessibility state of this view changed. The change 9320 * is local to this view and does not represent structural changes such 9321 * as children and parent. For example, the view became focusable. The 9322 * notification is at at most once every 9323 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9324 * to avoid unnecessary load to the system. Also once a view has a pending 9325 * notification this method is a NOP until the notification has been sent. 9326 * 9327 * @hide 9328 */ 9329 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 9330 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9331 return; 9332 } 9333 if (mSendViewStateChangedAccessibilityEvent == null) { 9334 mSendViewStateChangedAccessibilityEvent = 9335 new SendViewStateChangedAccessibilityEvent(); 9336 } 9337 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 9338 } 9339 9340 /** 9341 * Notifies that the accessibility state of this view changed. The change 9342 * is *not* local to this view and does represent structural changes such 9343 * as children and parent. For example, the view size changed. The 9344 * notification is at at most once every 9345 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 9346 * to avoid unnecessary load to the system. Also once a view has a pending 9347 * notification this method is a NOP until the notification has been sent. 9348 * 9349 * @hide 9350 */ 9351 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 9352 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 9353 return; 9354 } 9355 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 9356 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9357 if (mParent != null) { 9358 try { 9359 mParent.notifySubtreeAccessibilityStateChanged( 9360 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 9361 } catch (AbstractMethodError e) { 9362 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9363 " does not fully implement ViewParent", e); 9364 } 9365 } 9366 } 9367 } 9368 9369 /** 9370 * Change the visibility of the View without triggering any other changes. This is 9371 * important for transitions, where visibility changes should not adjust focus or 9372 * trigger a new layout. This is only used when the visibility has already been changed 9373 * and we need a transient value during an animation. When the animation completes, 9374 * the original visibility value is always restored. 9375 * 9376 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9377 * @hide 9378 */ 9379 public void setTransitionVisibility(@Visibility int visibility) { 9380 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 9381 } 9382 9383 /** 9384 * Reset the flag indicating the accessibility state of the subtree rooted 9385 * at this view changed. 9386 */ 9387 void resetSubtreeAccessibilityStateChanged() { 9388 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 9389 } 9390 9391 /** 9392 * Report an accessibility action to this view's parents for delegated processing. 9393 * 9394 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 9395 * call this method to delegate an accessibility action to a supporting parent. If the parent 9396 * returns true from its 9397 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 9398 * method this method will return true to signify that the action was consumed.</p> 9399 * 9400 * <p>This method is useful for implementing nested scrolling child views. If 9401 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 9402 * a custom view implementation may invoke this method to allow a parent to consume the 9403 * scroll first. If this method returns true the custom view should skip its own scrolling 9404 * behavior.</p> 9405 * 9406 * @param action Accessibility action to delegate 9407 * @param arguments Optional action arguments 9408 * @return true if the action was consumed by a parent 9409 */ 9410 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 9411 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 9412 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 9413 return true; 9414 } 9415 } 9416 return false; 9417 } 9418 9419 /** 9420 * Performs the specified accessibility action on the view. For 9421 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 9422 * <p> 9423 * If an {@link AccessibilityDelegate} has been specified via calling 9424 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 9425 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 9426 * is responsible for handling this call. 9427 * </p> 9428 * 9429 * <p>The default implementation will delegate 9430 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 9431 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 9432 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 9433 * 9434 * @param action The action to perform. 9435 * @param arguments Optional action arguments. 9436 * @return Whether the action was performed. 9437 */ 9438 public boolean performAccessibilityAction(int action, Bundle arguments) { 9439 if (mAccessibilityDelegate != null) { 9440 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 9441 } else { 9442 return performAccessibilityActionInternal(action, arguments); 9443 } 9444 } 9445 9446 /** 9447 * @see #performAccessibilityAction(int, Bundle) 9448 * 9449 * Note: Called from the default {@link AccessibilityDelegate}. 9450 * 9451 * @hide 9452 */ 9453 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 9454 if (isNestedScrollingEnabled() 9455 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 9456 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 9457 || action == R.id.accessibilityActionScrollUp 9458 || action == R.id.accessibilityActionScrollLeft 9459 || action == R.id.accessibilityActionScrollDown 9460 || action == R.id.accessibilityActionScrollRight)) { 9461 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 9462 return true; 9463 } 9464 } 9465 9466 switch (action) { 9467 case AccessibilityNodeInfo.ACTION_CLICK: { 9468 if (isClickable()) { 9469 performClick(); 9470 return true; 9471 } 9472 } break; 9473 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 9474 if (isLongClickable()) { 9475 performLongClick(); 9476 return true; 9477 } 9478 } break; 9479 case AccessibilityNodeInfo.ACTION_FOCUS: { 9480 if (!hasFocus()) { 9481 // Get out of touch mode since accessibility 9482 // wants to move focus around. 9483 getViewRootImpl().ensureTouchMode(false); 9484 return requestFocus(); 9485 } 9486 } break; 9487 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 9488 if (hasFocus()) { 9489 clearFocus(); 9490 return !isFocused(); 9491 } 9492 } break; 9493 case AccessibilityNodeInfo.ACTION_SELECT: { 9494 if (!isSelected()) { 9495 setSelected(true); 9496 return isSelected(); 9497 } 9498 } break; 9499 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 9500 if (isSelected()) { 9501 setSelected(false); 9502 return !isSelected(); 9503 } 9504 } break; 9505 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 9506 if (!isAccessibilityFocused()) { 9507 return requestAccessibilityFocus(); 9508 } 9509 } break; 9510 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 9511 if (isAccessibilityFocused()) { 9512 clearAccessibilityFocus(); 9513 return true; 9514 } 9515 } break; 9516 case AccessibilityNodeInfo.ACTION_NEXT_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, true, extendSelection); 9523 } 9524 } break; 9525 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 9526 if (arguments != null) { 9527 final int granularity = arguments.getInt( 9528 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 9529 final boolean extendSelection = arguments.getBoolean( 9530 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 9531 return traverseAtGranularity(granularity, false, extendSelection); 9532 } 9533 } break; 9534 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 9535 CharSequence text = getIterableTextForAccessibility(); 9536 if (text == null) { 9537 return false; 9538 } 9539 final int start = (arguments != null) ? arguments.getInt( 9540 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 9541 final int end = (arguments != null) ? arguments.getInt( 9542 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 9543 // Only cursor position can be specified (selection length == 0) 9544 if ((getAccessibilitySelectionStart() != start 9545 || getAccessibilitySelectionEnd() != end) 9546 && (start == end)) { 9547 setAccessibilitySelection(start, end); 9548 notifyViewAccessibilityStateChangedIfNeeded( 9549 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9550 return true; 9551 } 9552 } break; 9553 case R.id.accessibilityActionShowOnScreen: { 9554 if (mAttachInfo != null) { 9555 final Rect r = mAttachInfo.mTmpInvalRect; 9556 getDrawingRect(r); 9557 return requestRectangleOnScreen(r, true); 9558 } 9559 } break; 9560 case R.id.accessibilityActionContextClick: { 9561 if (isContextClickable()) { 9562 performContextClick(); 9563 return true; 9564 } 9565 } break; 9566 } 9567 return false; 9568 } 9569 9570 private boolean traverseAtGranularity(int granularity, boolean forward, 9571 boolean extendSelection) { 9572 CharSequence text = getIterableTextForAccessibility(); 9573 if (text == null || text.length() == 0) { 9574 return false; 9575 } 9576 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 9577 if (iterator == null) { 9578 return false; 9579 } 9580 int current = getAccessibilitySelectionEnd(); 9581 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9582 current = forward ? 0 : text.length(); 9583 } 9584 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 9585 if (range == null) { 9586 return false; 9587 } 9588 final int segmentStart = range[0]; 9589 final int segmentEnd = range[1]; 9590 int selectionStart; 9591 int selectionEnd; 9592 if (extendSelection && isAccessibilitySelectionExtendable()) { 9593 selectionStart = getAccessibilitySelectionStart(); 9594 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 9595 selectionStart = forward ? segmentStart : segmentEnd; 9596 } 9597 selectionEnd = forward ? segmentEnd : segmentStart; 9598 } else { 9599 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 9600 } 9601 setAccessibilitySelection(selectionStart, selectionEnd); 9602 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 9603 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 9604 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 9605 return true; 9606 } 9607 9608 /** 9609 * Gets the text reported for accessibility purposes. 9610 * 9611 * @return The accessibility text. 9612 * 9613 * @hide 9614 */ 9615 public CharSequence getIterableTextForAccessibility() { 9616 return getContentDescription(); 9617 } 9618 9619 /** 9620 * Gets whether accessibility selection can be extended. 9621 * 9622 * @return If selection is extensible. 9623 * 9624 * @hide 9625 */ 9626 public boolean isAccessibilitySelectionExtendable() { 9627 return false; 9628 } 9629 9630 /** 9631 * @hide 9632 */ 9633 public int getAccessibilitySelectionStart() { 9634 return mAccessibilityCursorPosition; 9635 } 9636 9637 /** 9638 * @hide 9639 */ 9640 public int getAccessibilitySelectionEnd() { 9641 return getAccessibilitySelectionStart(); 9642 } 9643 9644 /** 9645 * @hide 9646 */ 9647 public void setAccessibilitySelection(int start, int end) { 9648 if (start == end && end == mAccessibilityCursorPosition) { 9649 return; 9650 } 9651 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 9652 mAccessibilityCursorPosition = start; 9653 } else { 9654 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 9655 } 9656 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9657 } 9658 9659 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 9660 int fromIndex, int toIndex) { 9661 if (mParent == null) { 9662 return; 9663 } 9664 AccessibilityEvent event = AccessibilityEvent.obtain( 9665 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 9666 onInitializeAccessibilityEvent(event); 9667 onPopulateAccessibilityEvent(event); 9668 event.setFromIndex(fromIndex); 9669 event.setToIndex(toIndex); 9670 event.setAction(action); 9671 event.setMovementGranularity(granularity); 9672 mParent.requestSendAccessibilityEvent(this, event); 9673 } 9674 9675 /** 9676 * @hide 9677 */ 9678 public TextSegmentIterator getIteratorForGranularity(int granularity) { 9679 switch (granularity) { 9680 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 9681 CharSequence text = getIterableTextForAccessibility(); 9682 if (text != null && text.length() > 0) { 9683 CharacterTextSegmentIterator iterator = 9684 CharacterTextSegmentIterator.getInstance( 9685 mContext.getResources().getConfiguration().locale); 9686 iterator.initialize(text.toString()); 9687 return iterator; 9688 } 9689 } break; 9690 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 9691 CharSequence text = getIterableTextForAccessibility(); 9692 if (text != null && text.length() > 0) { 9693 WordTextSegmentIterator iterator = 9694 WordTextSegmentIterator.getInstance( 9695 mContext.getResources().getConfiguration().locale); 9696 iterator.initialize(text.toString()); 9697 return iterator; 9698 } 9699 } break; 9700 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 9701 CharSequence text = getIterableTextForAccessibility(); 9702 if (text != null && text.length() > 0) { 9703 ParagraphTextSegmentIterator iterator = 9704 ParagraphTextSegmentIterator.getInstance(); 9705 iterator.initialize(text.toString()); 9706 return iterator; 9707 } 9708 } break; 9709 } 9710 return null; 9711 } 9712 9713 /** 9714 * @hide 9715 */ 9716 public void dispatchStartTemporaryDetach() { 9717 onStartTemporaryDetach(); 9718 } 9719 9720 /** 9721 * This is called when a container is going to temporarily detach a child, with 9722 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 9723 * It will either be followed by {@link #onFinishTemporaryDetach()} or 9724 * {@link #onDetachedFromWindow()} when the container is done. 9725 */ 9726 public void onStartTemporaryDetach() { 9727 removeUnsetPressCallback(); 9728 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 9729 } 9730 9731 /** 9732 * @hide 9733 */ 9734 public void dispatchFinishTemporaryDetach() { 9735 onFinishTemporaryDetach(); 9736 } 9737 9738 /** 9739 * Called after {@link #onStartTemporaryDetach} when the container is done 9740 * changing the view. 9741 */ 9742 public void onFinishTemporaryDetach() { 9743 } 9744 9745 /** 9746 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 9747 * for this view's window. Returns null if the view is not currently attached 9748 * to the window. Normally you will not need to use this directly, but 9749 * just use the standard high-level event callbacks like 9750 * {@link #onKeyDown(int, KeyEvent)}. 9751 */ 9752 public KeyEvent.DispatcherState getKeyDispatcherState() { 9753 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 9754 } 9755 9756 /** 9757 * Dispatch a key event before it is processed by any input method 9758 * associated with the view hierarchy. This can be used to intercept 9759 * key events in special situations before the IME consumes them; a 9760 * typical example would be handling the BACK key to update the application's 9761 * UI instead of allowing the IME to see it and close itself. 9762 * 9763 * @param event The key event to be dispatched. 9764 * @return True if the event was handled, false otherwise. 9765 */ 9766 public boolean dispatchKeyEventPreIme(KeyEvent event) { 9767 return onKeyPreIme(event.getKeyCode(), event); 9768 } 9769 9770 /** 9771 * Dispatch a key event to the next view on the focus path. This path runs 9772 * from the top of the view tree down to the currently focused view. If this 9773 * view has focus, it will dispatch to itself. Otherwise it will dispatch 9774 * the next node down the focus path. This method also fires any key 9775 * listeners. 9776 * 9777 * @param event The key event to be dispatched. 9778 * @return True if the event was handled, false otherwise. 9779 */ 9780 public boolean dispatchKeyEvent(KeyEvent event) { 9781 if (mInputEventConsistencyVerifier != null) { 9782 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 9783 } 9784 9785 // Give any attached key listener a first crack at the event. 9786 //noinspection SimplifiableIfStatement 9787 ListenerInfo li = mListenerInfo; 9788 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 9789 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 9790 return true; 9791 } 9792 9793 if (event.dispatch(this, mAttachInfo != null 9794 ? mAttachInfo.mKeyDispatchState : null, this)) { 9795 return true; 9796 } 9797 9798 if (mInputEventConsistencyVerifier != null) { 9799 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9800 } 9801 return false; 9802 } 9803 9804 /** 9805 * Dispatches a key shortcut event. 9806 * 9807 * @param event The key event to be dispatched. 9808 * @return True if the event was handled by the view, false otherwise. 9809 */ 9810 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 9811 return onKeyShortcut(event.getKeyCode(), event); 9812 } 9813 9814 /** 9815 * Pass the touch screen motion event down to the target view, or this 9816 * view if it is the target. 9817 * 9818 * @param event The motion event to be dispatched. 9819 * @return True if the event was handled by the view, false otherwise. 9820 */ 9821 public boolean dispatchTouchEvent(MotionEvent event) { 9822 // If the event should be handled by accessibility focus first. 9823 if (event.isTargetAccessibilityFocus()) { 9824 // We don't have focus or no virtual descendant has it, do not handle the event. 9825 if (!isAccessibilityFocusedViewOrHost()) { 9826 return false; 9827 } 9828 // We have focus and got the event, then use normal event dispatch. 9829 event.setTargetAccessibilityFocus(false); 9830 } 9831 9832 boolean result = false; 9833 9834 if (mInputEventConsistencyVerifier != null) { 9835 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 9836 } 9837 9838 final int actionMasked = event.getActionMasked(); 9839 if (actionMasked == MotionEvent.ACTION_DOWN) { 9840 // Defensive cleanup for new gesture 9841 stopNestedScroll(); 9842 } 9843 9844 if (onFilterTouchEventForSecurity(event)) { 9845 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 9846 result = true; 9847 } 9848 //noinspection SimplifiableIfStatement 9849 ListenerInfo li = mListenerInfo; 9850 if (li != null && li.mOnTouchListener != null 9851 && (mViewFlags & ENABLED_MASK) == ENABLED 9852 && li.mOnTouchListener.onTouch(this, event)) { 9853 result = true; 9854 } 9855 9856 if (!result && onTouchEvent(event)) { 9857 result = true; 9858 } 9859 } 9860 9861 if (!result && mInputEventConsistencyVerifier != null) { 9862 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9863 } 9864 9865 // Clean up after nested scrolls if this is the end of a gesture; 9866 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 9867 // of the gesture. 9868 if (actionMasked == MotionEvent.ACTION_UP || 9869 actionMasked == MotionEvent.ACTION_CANCEL || 9870 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 9871 stopNestedScroll(); 9872 } 9873 9874 return result; 9875 } 9876 9877 boolean isAccessibilityFocusedViewOrHost() { 9878 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 9879 .getAccessibilityFocusedHost() == this); 9880 } 9881 9882 /** 9883 * Filter the touch event to apply security policies. 9884 * 9885 * @param event The motion event to be filtered. 9886 * @return True if the event should be dispatched, false if the event should be dropped. 9887 * 9888 * @see #getFilterTouchesWhenObscured 9889 */ 9890 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 9891 //noinspection RedundantIfStatement 9892 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 9893 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 9894 // Window is obscured, drop this touch. 9895 return false; 9896 } 9897 return true; 9898 } 9899 9900 /** 9901 * Pass a trackball motion event down to the focused view. 9902 * 9903 * @param event The motion event to be dispatched. 9904 * @return True if the event was handled by the view, false otherwise. 9905 */ 9906 public boolean dispatchTrackballEvent(MotionEvent event) { 9907 if (mInputEventConsistencyVerifier != null) { 9908 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 9909 } 9910 9911 return onTrackballEvent(event); 9912 } 9913 9914 /** 9915 * Dispatch a generic motion event. 9916 * <p> 9917 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9918 * are delivered to the view under the pointer. All other generic motion events are 9919 * delivered to the focused view. Hover events are handled specially and are delivered 9920 * to {@link #onHoverEvent(MotionEvent)}. 9921 * </p> 9922 * 9923 * @param event The motion event to be dispatched. 9924 * @return True if the event was handled by the view, false otherwise. 9925 */ 9926 public boolean dispatchGenericMotionEvent(MotionEvent event) { 9927 if (mInputEventConsistencyVerifier != null) { 9928 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 9929 } 9930 9931 final int source = event.getSource(); 9932 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 9933 final int action = event.getAction(); 9934 if (action == MotionEvent.ACTION_HOVER_ENTER 9935 || action == MotionEvent.ACTION_HOVER_MOVE 9936 || action == MotionEvent.ACTION_HOVER_EXIT) { 9937 if (dispatchHoverEvent(event)) { 9938 return true; 9939 } 9940 } else if (dispatchGenericPointerEvent(event)) { 9941 return true; 9942 } 9943 } else if (dispatchGenericFocusedEvent(event)) { 9944 return true; 9945 } 9946 9947 if (dispatchGenericMotionEventInternal(event)) { 9948 return true; 9949 } 9950 9951 if (mInputEventConsistencyVerifier != null) { 9952 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9953 } 9954 return false; 9955 } 9956 9957 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 9958 //noinspection SimplifiableIfStatement 9959 ListenerInfo li = mListenerInfo; 9960 if (li != null && li.mOnGenericMotionListener != null 9961 && (mViewFlags & ENABLED_MASK) == ENABLED 9962 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 9963 return true; 9964 } 9965 9966 if (onGenericMotionEvent(event)) { 9967 return true; 9968 } 9969 9970 final int actionButton = event.getActionButton(); 9971 switch (event.getActionMasked()) { 9972 case MotionEvent.ACTION_BUTTON_PRESS: 9973 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 9974 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 9975 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 9976 if (performContextClick()) { 9977 mInContextButtonPress = true; 9978 setPressed(true, event.getX(), event.getY()); 9979 removeTapCallback(); 9980 removeLongPressCallback(); 9981 return true; 9982 } 9983 } 9984 break; 9985 9986 case MotionEvent.ACTION_BUTTON_RELEASE: 9987 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 9988 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 9989 mInContextButtonPress = false; 9990 mIgnoreNextUpEvent = true; 9991 } 9992 break; 9993 } 9994 9995 if (mInputEventConsistencyVerifier != null) { 9996 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 9997 } 9998 return false; 9999 } 10000 10001 /** 10002 * Dispatch a hover event. 10003 * <p> 10004 * Do not call this method directly. 10005 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10006 * </p> 10007 * 10008 * @param event The motion event to be dispatched. 10009 * @return True if the event was handled by the view, false otherwise. 10010 */ 10011 protected boolean dispatchHoverEvent(MotionEvent event) { 10012 ListenerInfo li = mListenerInfo; 10013 //noinspection SimplifiableIfStatement 10014 if (li != null && li.mOnHoverListener != null 10015 && (mViewFlags & ENABLED_MASK) == ENABLED 10016 && li.mOnHoverListener.onHover(this, event)) { 10017 return true; 10018 } 10019 10020 return onHoverEvent(event); 10021 } 10022 10023 /** 10024 * Returns true if the view has a child to which it has recently sent 10025 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 10026 * it does not have a hovered child, then it must be the innermost hovered view. 10027 * @hide 10028 */ 10029 protected boolean hasHoveredChild() { 10030 return false; 10031 } 10032 10033 /** 10034 * Dispatch a generic motion event to the view under the first pointer. 10035 * <p> 10036 * Do not call this method directly. 10037 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10038 * </p> 10039 * 10040 * @param event The motion event to be dispatched. 10041 * @return True if the event was handled by the view, false otherwise. 10042 */ 10043 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 10044 return false; 10045 } 10046 10047 /** 10048 * Dispatch a generic motion event to the currently focused view. 10049 * <p> 10050 * Do not call this method directly. 10051 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 10052 * </p> 10053 * 10054 * @param event The motion event to be dispatched. 10055 * @return True if the event was handled by the view, false otherwise. 10056 */ 10057 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 10058 return false; 10059 } 10060 10061 /** 10062 * Dispatch a pointer event. 10063 * <p> 10064 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 10065 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 10066 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 10067 * and should not be expected to handle other pointing device features. 10068 * </p> 10069 * 10070 * @param event The motion event to be dispatched. 10071 * @return True if the event was handled by the view, false otherwise. 10072 * @hide 10073 */ 10074 public final boolean dispatchPointerEvent(MotionEvent event) { 10075 if (event.isTouchEvent()) { 10076 return dispatchTouchEvent(event); 10077 } else { 10078 return dispatchGenericMotionEvent(event); 10079 } 10080 } 10081 10082 /** 10083 * Called when the window containing this view gains or loses window focus. 10084 * ViewGroups should override to route to their children. 10085 * 10086 * @param hasFocus True if the window containing this view now has focus, 10087 * false otherwise. 10088 */ 10089 public void dispatchWindowFocusChanged(boolean hasFocus) { 10090 onWindowFocusChanged(hasFocus); 10091 } 10092 10093 /** 10094 * Called when the window containing this view gains or loses focus. Note 10095 * that this is separate from view focus: to receive key events, both 10096 * your view and its window must have focus. If a window is displayed 10097 * on top of yours that takes input focus, then your own window will lose 10098 * focus but the view focus will remain unchanged. 10099 * 10100 * @param hasWindowFocus True if the window containing this view now has 10101 * focus, false otherwise. 10102 */ 10103 public void onWindowFocusChanged(boolean hasWindowFocus) { 10104 InputMethodManager imm = InputMethodManager.peekInstance(); 10105 if (!hasWindowFocus) { 10106 if (isPressed()) { 10107 setPressed(false); 10108 } 10109 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10110 imm.focusOut(this); 10111 } 10112 removeLongPressCallback(); 10113 removeTapCallback(); 10114 onFocusLost(); 10115 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 10116 imm.focusIn(this); 10117 } 10118 refreshDrawableState(); 10119 } 10120 10121 /** 10122 * Returns true if this view is in a window that currently has window focus. 10123 * Note that this is not the same as the view itself having focus. 10124 * 10125 * @return True if this view is in a window that currently has window focus. 10126 */ 10127 public boolean hasWindowFocus() { 10128 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 10129 } 10130 10131 /** 10132 * Dispatch a view visibility change down the view hierarchy. 10133 * ViewGroups should override to route to their children. 10134 * @param changedView The view whose visibility changed. Could be 'this' or 10135 * an ancestor view. 10136 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 10137 * {@link #INVISIBLE} or {@link #GONE}. 10138 */ 10139 protected void dispatchVisibilityChanged(@NonNull View changedView, 10140 @Visibility int visibility) { 10141 onVisibilityChanged(changedView, visibility); 10142 } 10143 10144 /** 10145 * Called when the visibility of the view or an ancestor of the view has 10146 * changed. 10147 * 10148 * @param changedView The view whose visibility changed. May be 10149 * {@code this} or an ancestor view. 10150 * @param visibility The new visibility, one of {@link #VISIBLE}, 10151 * {@link #INVISIBLE} or {@link #GONE}. 10152 */ 10153 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 10154 final boolean visible = visibility == VISIBLE && getVisibility() == VISIBLE; 10155 if (visible && mAttachInfo != null) { 10156 initialAwakenScrollBars(); 10157 } 10158 10159 final Drawable dr = mBackground; 10160 if (dr != null && visible != dr.isVisible()) { 10161 dr.setVisible(visible, false); 10162 } 10163 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 10164 if (fg != null && visible != fg.isVisible()) { 10165 fg.setVisible(visible, false); 10166 } 10167 } 10168 10169 /** 10170 * Dispatch a hint about whether this view is displayed. For instance, when 10171 * a View moves out of the screen, it might receives a display hint indicating 10172 * the view is not displayed. Applications should not <em>rely</em> on this hint 10173 * as there is no guarantee that they will receive one. 10174 * 10175 * @param hint A hint about whether or not this view is displayed: 10176 * {@link #VISIBLE} or {@link #INVISIBLE}. 10177 */ 10178 public void dispatchDisplayHint(@Visibility int hint) { 10179 onDisplayHint(hint); 10180 } 10181 10182 /** 10183 * Gives this view a hint about whether is displayed or not. For instance, when 10184 * a View moves out of the screen, it might receives a display hint indicating 10185 * the view is not displayed. Applications should not <em>rely</em> on this hint 10186 * as there is no guarantee that they will receive one. 10187 * 10188 * @param hint A hint about whether or not this view is displayed: 10189 * {@link #VISIBLE} or {@link #INVISIBLE}. 10190 */ 10191 protected void onDisplayHint(@Visibility int hint) { 10192 } 10193 10194 /** 10195 * Dispatch a window visibility change down the view hierarchy. 10196 * ViewGroups should override to route to their children. 10197 * 10198 * @param visibility The new visibility of the window. 10199 * 10200 * @see #onWindowVisibilityChanged(int) 10201 */ 10202 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 10203 onWindowVisibilityChanged(visibility); 10204 } 10205 10206 /** 10207 * Called when the window containing has change its visibility 10208 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 10209 * that this tells you whether or not your window is being made visible 10210 * to the window manager; this does <em>not</em> tell you whether or not 10211 * your window is obscured by other windows on the screen, even if it 10212 * is itself visible. 10213 * 10214 * @param visibility The new visibility of the window. 10215 */ 10216 protected void onWindowVisibilityChanged(@Visibility int visibility) { 10217 if (visibility == VISIBLE) { 10218 initialAwakenScrollBars(); 10219 } 10220 } 10221 10222 /** 10223 * Returns the current visibility of the window this view is attached to 10224 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 10225 * 10226 * @return Returns the current visibility of the view's window. 10227 */ 10228 @Visibility 10229 public int getWindowVisibility() { 10230 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 10231 } 10232 10233 /** 10234 * Retrieve the overall visible display size in which the window this view is 10235 * attached to has been positioned in. This takes into account screen 10236 * decorations above the window, for both cases where the window itself 10237 * is being position inside of them or the window is being placed under 10238 * then and covered insets are used for the window to position its content 10239 * inside. In effect, this tells you the available area where content can 10240 * be placed and remain visible to users. 10241 * 10242 * <p>This function requires an IPC back to the window manager to retrieve 10243 * the requested information, so should not be used in performance critical 10244 * code like drawing. 10245 * 10246 * @param outRect Filled in with the visible display frame. If the view 10247 * is not attached to a window, this is simply the raw display size. 10248 */ 10249 public void getWindowVisibleDisplayFrame(Rect outRect) { 10250 if (mAttachInfo != null) { 10251 try { 10252 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 10253 } catch (RemoteException e) { 10254 return; 10255 } 10256 // XXX This is really broken, and probably all needs to be done 10257 // in the window manager, and we need to know more about whether 10258 // we want the area behind or in front of the IME. 10259 final Rect insets = mAttachInfo.mVisibleInsets; 10260 outRect.left += insets.left; 10261 outRect.top += insets.top; 10262 outRect.right -= insets.right; 10263 outRect.bottom -= insets.bottom; 10264 return; 10265 } 10266 // The view is not attached to a display so we don't have a context. 10267 // Make a best guess about the display size. 10268 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 10269 d.getRectSize(outRect); 10270 } 10271 10272 /** 10273 * Dispatch a notification about a resource configuration change down 10274 * the view hierarchy. 10275 * ViewGroups should override to route to their children. 10276 * 10277 * @param newConfig The new resource configuration. 10278 * 10279 * @see #onConfigurationChanged(android.content.res.Configuration) 10280 */ 10281 public void dispatchConfigurationChanged(Configuration newConfig) { 10282 onConfigurationChanged(newConfig); 10283 } 10284 10285 /** 10286 * Called when the current configuration of the resources being used 10287 * by the application have changed. You can use this to decide when 10288 * to reload resources that can changed based on orientation and other 10289 * configuration characteristics. You only need to use this if you are 10290 * not relying on the normal {@link android.app.Activity} mechanism of 10291 * recreating the activity instance upon a configuration change. 10292 * 10293 * @param newConfig The new resource configuration. 10294 */ 10295 protected void onConfigurationChanged(Configuration newConfig) { 10296 } 10297 10298 /** 10299 * Private function to aggregate all per-view attributes in to the view 10300 * root. 10301 */ 10302 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10303 performCollectViewAttributes(attachInfo, visibility); 10304 } 10305 10306 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 10307 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 10308 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 10309 attachInfo.mKeepScreenOn = true; 10310 } 10311 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 10312 ListenerInfo li = mListenerInfo; 10313 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 10314 attachInfo.mHasSystemUiListeners = true; 10315 } 10316 } 10317 } 10318 10319 void needGlobalAttributesUpdate(boolean force) { 10320 final AttachInfo ai = mAttachInfo; 10321 if (ai != null && !ai.mRecomputeGlobalAttributes) { 10322 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 10323 || ai.mHasSystemUiListeners) { 10324 ai.mRecomputeGlobalAttributes = true; 10325 } 10326 } 10327 } 10328 10329 /** 10330 * Returns whether the device is currently in touch mode. Touch mode is entered 10331 * once the user begins interacting with the device by touch, and affects various 10332 * things like whether focus is always visible to the user. 10333 * 10334 * @return Whether the device is in touch mode. 10335 */ 10336 @ViewDebug.ExportedProperty 10337 public boolean isInTouchMode() { 10338 if (mAttachInfo != null) { 10339 return mAttachInfo.mInTouchMode; 10340 } else { 10341 return ViewRootImpl.isInTouchMode(); 10342 } 10343 } 10344 10345 /** 10346 * Returns the context the view is running in, through which it can 10347 * access the current theme, resources, etc. 10348 * 10349 * @return The view's Context. 10350 */ 10351 @ViewDebug.CapturedViewProperty 10352 public final Context getContext() { 10353 return mContext; 10354 } 10355 10356 /** 10357 * Handle a key event before it is processed by any input method 10358 * associated with the view hierarchy. This can be used to intercept 10359 * key events in special situations before the IME consumes them; a 10360 * typical example would be handling the BACK key to update the application's 10361 * UI instead of allowing the IME to see it and close itself. 10362 * 10363 * @param keyCode The value in event.getKeyCode(). 10364 * @param event Description of the key event. 10365 * @return If you handled the event, return true. If you want to allow the 10366 * event to be handled by the next receiver, return false. 10367 */ 10368 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 10369 return false; 10370 } 10371 10372 /** 10373 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 10374 * KeyEvent.Callback.onKeyDown()}: perform press of the view 10375 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 10376 * is released, if the view is enabled and clickable. 10377 * <p> 10378 * Key presses in software keyboards will generally NOT trigger this 10379 * listener, although some may elect to do so in some situations. Do not 10380 * rely on this to catch software key presses. 10381 * 10382 * @param keyCode a key code that represents the button pressed, from 10383 * {@link android.view.KeyEvent} 10384 * @param event the KeyEvent object that defines the button action 10385 */ 10386 public boolean onKeyDown(int keyCode, KeyEvent event) { 10387 if (KeyEvent.isConfirmKey(keyCode)) { 10388 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10389 return true; 10390 } 10391 10392 // Long clickable items don't necessarily have to be clickable. 10393 if (((mViewFlags & CLICKABLE) == CLICKABLE 10394 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10395 && (event.getRepeatCount() == 0)) { 10396 // For the purposes of menu anchoring and drawable hotspots, 10397 // key events are considered to be at the center of the view. 10398 final float x = getWidth() / 2f; 10399 final float y = getHeight() / 2f; 10400 setPressed(true, x, y); 10401 checkForLongClick(0, x, y); 10402 return true; 10403 } 10404 } 10405 10406 return false; 10407 } 10408 10409 /** 10410 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 10411 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 10412 * the event). 10413 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10414 * although some may elect to do so in some situations. Do not rely on this to 10415 * catch software key presses. 10416 */ 10417 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 10418 return false; 10419 } 10420 10421 /** 10422 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 10423 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 10424 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 10425 * or {@link KeyEvent#KEYCODE_SPACE} is released. 10426 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10427 * although some may elect to do so in some situations. Do not rely on this to 10428 * catch software key presses. 10429 * 10430 * @param keyCode A key code that represents the button pressed, from 10431 * {@link android.view.KeyEvent}. 10432 * @param event The KeyEvent object that defines the button action. 10433 */ 10434 public boolean onKeyUp(int keyCode, KeyEvent event) { 10435 if (KeyEvent.isConfirmKey(keyCode)) { 10436 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 10437 return true; 10438 } 10439 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 10440 setPressed(false); 10441 10442 if (!mHasPerformedLongPress) { 10443 // This is a tap, so remove the longpress check 10444 removeLongPressCallback(); 10445 return performClick(); 10446 } 10447 } 10448 } 10449 return false; 10450 } 10451 10452 /** 10453 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 10454 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 10455 * the event). 10456 * <p>Key presses in software keyboards will generally NOT trigger this listener, 10457 * although some may elect to do so in some situations. Do not rely on this to 10458 * catch software key presses. 10459 * 10460 * @param keyCode A key code that represents the button pressed, from 10461 * {@link android.view.KeyEvent}. 10462 * @param repeatCount The number of times the action was made. 10463 * @param event The KeyEvent object that defines the button action. 10464 */ 10465 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 10466 return false; 10467 } 10468 10469 /** 10470 * Called on the focused view when a key shortcut event is not handled. 10471 * Override this method to implement local key shortcuts for the View. 10472 * Key shortcuts can also be implemented by setting the 10473 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 10474 * 10475 * @param keyCode The value in event.getKeyCode(). 10476 * @param event Description of the key event. 10477 * @return If you handled the event, return true. If you want to allow the 10478 * event to be handled by the next receiver, return false. 10479 */ 10480 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10481 return false; 10482 } 10483 10484 /** 10485 * Check whether the called view is a text editor, in which case it 10486 * would make sense to automatically display a soft input window for 10487 * it. Subclasses should override this if they implement 10488 * {@link #onCreateInputConnection(EditorInfo)} to return true if 10489 * a call on that method would return a non-null InputConnection, and 10490 * they are really a first-class editor that the user would normally 10491 * start typing on when the go into a window containing your view. 10492 * 10493 * <p>The default implementation always returns false. This does 10494 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 10495 * will not be called or the user can not otherwise perform edits on your 10496 * view; it is just a hint to the system that this is not the primary 10497 * purpose of this view. 10498 * 10499 * @return Returns true if this view is a text editor, else false. 10500 */ 10501 public boolean onCheckIsTextEditor() { 10502 return false; 10503 } 10504 10505 /** 10506 * Create a new InputConnection for an InputMethod to interact 10507 * with the view. The default implementation returns null, since it doesn't 10508 * support input methods. You can override this to implement such support. 10509 * This is only needed for views that take focus and text input. 10510 * 10511 * <p>When implementing this, you probably also want to implement 10512 * {@link #onCheckIsTextEditor()} to indicate you will return a 10513 * non-null InputConnection.</p> 10514 * 10515 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 10516 * object correctly and in its entirety, so that the connected IME can rely 10517 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 10518 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 10519 * must be filled in with the correct cursor position for IMEs to work correctly 10520 * with your application.</p> 10521 * 10522 * @param outAttrs Fill in with attribute information about the connection. 10523 */ 10524 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 10525 return null; 10526 } 10527 10528 /** 10529 * Called by the {@link android.view.inputmethod.InputMethodManager} 10530 * when a view who is not the current 10531 * input connection target is trying to make a call on the manager. The 10532 * default implementation returns false; you can override this to return 10533 * true for certain views if you are performing InputConnection proxying 10534 * to them. 10535 * @param view The View that is making the InputMethodManager call. 10536 * @return Return true to allow the call, false to reject. 10537 */ 10538 public boolean checkInputConnectionProxy(View view) { 10539 return false; 10540 } 10541 10542 /** 10543 * Show the context menu for this view. It is not safe to hold on to the 10544 * menu after returning from this method. 10545 * 10546 * You should normally not overload this method. Overload 10547 * {@link #onCreateContextMenu(ContextMenu)} or define an 10548 * {@link OnCreateContextMenuListener} to add items to the context menu. 10549 * 10550 * @param menu The context menu to populate 10551 */ 10552 public void createContextMenu(ContextMenu menu) { 10553 ContextMenuInfo menuInfo = getContextMenuInfo(); 10554 10555 // Sets the current menu info so all items added to menu will have 10556 // my extra info set. 10557 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 10558 10559 onCreateContextMenu(menu); 10560 ListenerInfo li = mListenerInfo; 10561 if (li != null && li.mOnCreateContextMenuListener != null) { 10562 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 10563 } 10564 10565 // Clear the extra information so subsequent items that aren't mine don't 10566 // have my extra info. 10567 ((MenuBuilder)menu).setCurrentMenuInfo(null); 10568 10569 if (mParent != null) { 10570 mParent.createContextMenu(menu); 10571 } 10572 } 10573 10574 /** 10575 * Views should implement this if they have extra information to associate 10576 * with the context menu. The return result is supplied as a parameter to 10577 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 10578 * callback. 10579 * 10580 * @return Extra information about the item for which the context menu 10581 * should be shown. This information will vary across different 10582 * subclasses of View. 10583 */ 10584 protected ContextMenuInfo getContextMenuInfo() { 10585 return null; 10586 } 10587 10588 /** 10589 * Views should implement this if the view itself is going to add items to 10590 * the context menu. 10591 * 10592 * @param menu the context menu to populate 10593 */ 10594 protected void onCreateContextMenu(ContextMenu menu) { 10595 } 10596 10597 /** 10598 * Implement this method to handle trackball motion events. The 10599 * <em>relative</em> movement of the trackball since the last event 10600 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 10601 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 10602 * that a movement of 1 corresponds to the user pressing one DPAD key (so 10603 * they will often be fractional values, representing the more fine-grained 10604 * movement information available from a trackball). 10605 * 10606 * @param event The motion event. 10607 * @return True if the event was handled, false otherwise. 10608 */ 10609 public boolean onTrackballEvent(MotionEvent event) { 10610 return false; 10611 } 10612 10613 /** 10614 * Implement this method to handle generic motion events. 10615 * <p> 10616 * Generic motion events describe joystick movements, mouse hovers, track pad 10617 * touches, scroll wheel movements and other input events. The 10618 * {@link MotionEvent#getSource() source} of the motion event specifies 10619 * the class of input that was received. Implementations of this method 10620 * must examine the bits in the source before processing the event. 10621 * The following code example shows how this is done. 10622 * </p><p> 10623 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 10624 * are delivered to the view under the pointer. All other generic motion events are 10625 * delivered to the focused view. 10626 * </p> 10627 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 10628 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 10629 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 10630 * // process the joystick movement... 10631 * return true; 10632 * } 10633 * } 10634 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 10635 * switch (event.getAction()) { 10636 * case MotionEvent.ACTION_HOVER_MOVE: 10637 * // process the mouse hover movement... 10638 * return true; 10639 * case MotionEvent.ACTION_SCROLL: 10640 * // process the scroll wheel movement... 10641 * return true; 10642 * } 10643 * } 10644 * return super.onGenericMotionEvent(event); 10645 * }</pre> 10646 * 10647 * @param event The generic motion event being processed. 10648 * @return True if the event was handled, false otherwise. 10649 */ 10650 public boolean onGenericMotionEvent(MotionEvent event) { 10651 return false; 10652 } 10653 10654 /** 10655 * Implement this method to handle hover events. 10656 * <p> 10657 * This method is called whenever a pointer is hovering into, over, or out of the 10658 * bounds of a view and the view is not currently being touched. 10659 * Hover events are represented as pointer events with action 10660 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 10661 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 10662 * </p> 10663 * <ul> 10664 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 10665 * when the pointer enters the bounds of the view.</li> 10666 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 10667 * when the pointer has already entered the bounds of the view and has moved.</li> 10668 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 10669 * when the pointer has exited the bounds of the view or when the pointer is 10670 * about to go down due to a button click, tap, or similar user action that 10671 * causes the view to be touched.</li> 10672 * </ul> 10673 * <p> 10674 * The view should implement this method to return true to indicate that it is 10675 * handling the hover event, such as by changing its drawable state. 10676 * </p><p> 10677 * The default implementation calls {@link #setHovered} to update the hovered state 10678 * of the view when a hover enter or hover exit event is received, if the view 10679 * is enabled and is clickable. The default implementation also sends hover 10680 * accessibility events. 10681 * </p> 10682 * 10683 * @param event The motion event that describes the hover. 10684 * @return True if the view handled the hover event. 10685 * 10686 * @see #isHovered 10687 * @see #setHovered 10688 * @see #onHoverChanged 10689 */ 10690 public boolean onHoverEvent(MotionEvent event) { 10691 // The root view may receive hover (or touch) events that are outside the bounds of 10692 // the window. This code ensures that we only send accessibility events for 10693 // hovers that are actually within the bounds of the root view. 10694 final int action = event.getActionMasked(); 10695 if (!mSendingHoverAccessibilityEvents) { 10696 if ((action == MotionEvent.ACTION_HOVER_ENTER 10697 || action == MotionEvent.ACTION_HOVER_MOVE) 10698 && !hasHoveredChild() 10699 && pointInView(event.getX(), event.getY())) { 10700 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 10701 mSendingHoverAccessibilityEvents = true; 10702 } 10703 } else { 10704 if (action == MotionEvent.ACTION_HOVER_EXIT 10705 || (action == MotionEvent.ACTION_MOVE 10706 && !pointInView(event.getX(), event.getY()))) { 10707 mSendingHoverAccessibilityEvents = false; 10708 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 10709 } 10710 } 10711 10712 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 10713 && event.isFromSource(InputDevice.SOURCE_MOUSE) 10714 && isOnScrollbar(event.getX(), event.getY())) { 10715 awakenScrollBars(); 10716 } 10717 if (isHoverable()) { 10718 switch (action) { 10719 case MotionEvent.ACTION_HOVER_ENTER: 10720 setHovered(true); 10721 break; 10722 case MotionEvent.ACTION_HOVER_EXIT: 10723 setHovered(false); 10724 break; 10725 } 10726 10727 // Dispatch the event to onGenericMotionEvent before returning true. 10728 // This is to provide compatibility with existing applications that 10729 // handled HOVER_MOVE events in onGenericMotionEvent and that would 10730 // break because of the new default handling for hoverable views 10731 // in onHoverEvent. 10732 // Note that onGenericMotionEvent will be called by default when 10733 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 10734 dispatchGenericMotionEventInternal(event); 10735 // The event was already handled by calling setHovered(), so always 10736 // return true. 10737 return true; 10738 } 10739 10740 return false; 10741 } 10742 10743 /** 10744 * Returns true if the view should handle {@link #onHoverEvent} 10745 * by calling {@link #setHovered} to change its hovered state. 10746 * 10747 * @return True if the view is hoverable. 10748 */ 10749 private boolean isHoverable() { 10750 final int viewFlags = mViewFlags; 10751 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10752 return false; 10753 } 10754 10755 return (viewFlags & CLICKABLE) == CLICKABLE 10756 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10757 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 10758 } 10759 10760 /** 10761 * Returns true if the view is currently hovered. 10762 * 10763 * @return True if the view is currently hovered. 10764 * 10765 * @see #setHovered 10766 * @see #onHoverChanged 10767 */ 10768 @ViewDebug.ExportedProperty 10769 public boolean isHovered() { 10770 return (mPrivateFlags & PFLAG_HOVERED) != 0; 10771 } 10772 10773 /** 10774 * Sets whether the view is currently hovered. 10775 * <p> 10776 * Calling this method also changes the drawable state of the view. This 10777 * enables the view to react to hover by using different drawable resources 10778 * to change its appearance. 10779 * </p><p> 10780 * The {@link #onHoverChanged} method is called when the hovered state changes. 10781 * </p> 10782 * 10783 * @param hovered True if the view is hovered. 10784 * 10785 * @see #isHovered 10786 * @see #onHoverChanged 10787 */ 10788 public void setHovered(boolean hovered) { 10789 if (hovered) { 10790 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 10791 mPrivateFlags |= PFLAG_HOVERED; 10792 refreshDrawableState(); 10793 onHoverChanged(true); 10794 } 10795 } else { 10796 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 10797 mPrivateFlags &= ~PFLAG_HOVERED; 10798 refreshDrawableState(); 10799 onHoverChanged(false); 10800 } 10801 } 10802 } 10803 10804 /** 10805 * Implement this method to handle hover state changes. 10806 * <p> 10807 * This method is called whenever the hover state changes as a result of a 10808 * call to {@link #setHovered}. 10809 * </p> 10810 * 10811 * @param hovered The current hover state, as returned by {@link #isHovered}. 10812 * 10813 * @see #isHovered 10814 * @see #setHovered 10815 */ 10816 public void onHoverChanged(boolean hovered) { 10817 } 10818 10819 /** 10820 * Handles scroll bar dragging by mouse input. 10821 * 10822 * @hide 10823 * @param event The motion event. 10824 * 10825 * @return true if the event was handled as a scroll bar dragging, false otherwise. 10826 */ 10827 protected boolean handleScrollBarDragging(MotionEvent event) { 10828 if (mScrollCache == null) { 10829 return false; 10830 } 10831 final float x = event.getX(); 10832 final float y = event.getY(); 10833 final int action = event.getAction(); 10834 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 10835 && action != MotionEvent.ACTION_DOWN) 10836 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 10837 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 10838 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 10839 return false; 10840 } 10841 10842 switch (action) { 10843 case MotionEvent.ACTION_MOVE: 10844 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 10845 return false; 10846 } 10847 if (mScrollCache.mScrollBarDraggingState 10848 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 10849 final Rect bounds = mScrollCache.mScrollBarBounds; 10850 getVerticalScrollBarBounds(bounds); 10851 final int range = computeVerticalScrollRange(); 10852 final int offset = computeVerticalScrollOffset(); 10853 final int extent = computeVerticalScrollExtent(); 10854 10855 final int thumbLength = ScrollBarUtils.getThumbLength( 10856 bounds.height(), bounds.width(), extent, range); 10857 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10858 bounds.height(), thumbLength, extent, range, offset); 10859 10860 final float diff = y - mScrollCache.mScrollBarDraggingPos; 10861 final float maxThumbOffset = bounds.height() - thumbLength; 10862 final float newThumbOffset = 10863 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 10864 final int height = getHeight(); 10865 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 10866 && height > 0 && extent > 0) { 10867 final int newY = Math.round((range - extent) 10868 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 10869 if (newY != getScrollY()) { 10870 mScrollCache.mScrollBarDraggingPos = y; 10871 setScrollY(newY); 10872 } 10873 } 10874 return true; 10875 } 10876 if (mScrollCache.mScrollBarDraggingState 10877 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 10878 final Rect bounds = mScrollCache.mScrollBarBounds; 10879 getHorizontalScrollBarBounds(bounds); 10880 final int range = computeHorizontalScrollRange(); 10881 final int offset = computeHorizontalScrollOffset(); 10882 final int extent = computeHorizontalScrollExtent(); 10883 10884 final int thumbLength = ScrollBarUtils.getThumbLength( 10885 bounds.width(), bounds.height(), extent, range); 10886 final int thumbOffset = ScrollBarUtils.getThumbOffset( 10887 bounds.width(), thumbLength, extent, range, offset); 10888 10889 final float diff = x - mScrollCache.mScrollBarDraggingPos; 10890 final float maxThumbOffset = bounds.width() - thumbLength; 10891 final float newThumbOffset = 10892 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 10893 final int width = getWidth(); 10894 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 10895 && width > 0 && extent > 0) { 10896 final int newX = Math.round((range - extent) 10897 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 10898 if (newX != getScrollX()) { 10899 mScrollCache.mScrollBarDraggingPos = x; 10900 setScrollX(newX); 10901 } 10902 } 10903 return true; 10904 } 10905 case MotionEvent.ACTION_DOWN: 10906 if (mScrollCache.state == ScrollabilityCache.OFF) { 10907 return false; 10908 } 10909 if (isOnVerticalScrollbarThumb(x, y)) { 10910 mScrollCache.mScrollBarDraggingState = 10911 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 10912 mScrollCache.mScrollBarDraggingPos = y; 10913 return true; 10914 } 10915 if (isOnHorizontalScrollbarThumb(x, y)) { 10916 mScrollCache.mScrollBarDraggingState = 10917 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 10918 mScrollCache.mScrollBarDraggingPos = x; 10919 return true; 10920 } 10921 } 10922 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 10923 return false; 10924 } 10925 10926 /** 10927 * Implement this method to handle touch screen motion events. 10928 * <p> 10929 * If this method is used to detect click actions, it is recommended that 10930 * the actions be performed by implementing and calling 10931 * {@link #performClick()}. This will ensure consistent system behavior, 10932 * including: 10933 * <ul> 10934 * <li>obeying click sound preferences 10935 * <li>dispatching OnClickListener calls 10936 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 10937 * accessibility features are enabled 10938 * </ul> 10939 * 10940 * @param event The motion event. 10941 * @return True if the event was handled, false otherwise. 10942 */ 10943 public boolean onTouchEvent(MotionEvent event) { 10944 final float x = event.getX(); 10945 final float y = event.getY(); 10946 final int viewFlags = mViewFlags; 10947 final int action = event.getAction(); 10948 10949 if ((viewFlags & ENABLED_MASK) == DISABLED) { 10950 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 10951 setPressed(false); 10952 } 10953 // A disabled view that is clickable still consumes the touch 10954 // events, it just doesn't respond to them. 10955 return (((viewFlags & CLICKABLE) == CLICKABLE 10956 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 10957 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 10958 } 10959 if (mTouchDelegate != null) { 10960 if (mTouchDelegate.onTouchEvent(event)) { 10961 return true; 10962 } 10963 } 10964 10965 if (((viewFlags & CLICKABLE) == CLICKABLE || 10966 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 10967 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 10968 switch (action) { 10969 case MotionEvent.ACTION_UP: 10970 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 10971 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 10972 // take focus if we don't have it already and we should in 10973 // touch mode. 10974 boolean focusTaken = false; 10975 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 10976 focusTaken = requestFocus(); 10977 } 10978 10979 if (prepressed) { 10980 // The button is being released before we actually 10981 // showed it as pressed. Make it show the pressed 10982 // state now (before scheduling the click) to ensure 10983 // the user sees it. 10984 setPressed(true, x, y); 10985 } 10986 10987 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 10988 // This is a tap, so remove the longpress check 10989 removeLongPressCallback(); 10990 10991 // Only perform take click actions if we were in the pressed state 10992 if (!focusTaken) { 10993 // Use a Runnable and post this rather than calling 10994 // performClick directly. This lets other visual state 10995 // of the view update before click actions start. 10996 if (mPerformClick == null) { 10997 mPerformClick = new PerformClick(); 10998 } 10999 if (!post(mPerformClick)) { 11000 performClick(); 11001 } 11002 } 11003 } 11004 11005 if (mUnsetPressedState == null) { 11006 mUnsetPressedState = new UnsetPressedState(); 11007 } 11008 11009 if (prepressed) { 11010 postDelayed(mUnsetPressedState, 11011 ViewConfiguration.getPressedStateDuration()); 11012 } else if (!post(mUnsetPressedState)) { 11013 // If the post failed, unpress right now 11014 mUnsetPressedState.run(); 11015 } 11016 11017 removeTapCallback(); 11018 } 11019 mIgnoreNextUpEvent = false; 11020 break; 11021 11022 case MotionEvent.ACTION_DOWN: 11023 mHasPerformedLongPress = false; 11024 11025 if (performButtonActionOnTouchDown(event)) { 11026 break; 11027 } 11028 11029 // Walk up the hierarchy to determine if we're inside a scrolling container. 11030 boolean isInScrollingContainer = isInScrollingContainer(); 11031 11032 // For views inside a scrolling container, delay the pressed feedback for 11033 // a short period in case this is a scroll. 11034 if (isInScrollingContainer) { 11035 mPrivateFlags |= PFLAG_PREPRESSED; 11036 if (mPendingCheckForTap == null) { 11037 mPendingCheckForTap = new CheckForTap(); 11038 } 11039 mPendingCheckForTap.x = event.getX(); 11040 mPendingCheckForTap.y = event.getY(); 11041 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 11042 } else { 11043 // Not inside a scrolling container, so show the feedback right away 11044 setPressed(true, x, y); 11045 checkForLongClick(0, x, y); 11046 } 11047 break; 11048 11049 case MotionEvent.ACTION_CANCEL: 11050 setPressed(false); 11051 removeTapCallback(); 11052 removeLongPressCallback(); 11053 mInContextButtonPress = false; 11054 mHasPerformedLongPress = false; 11055 mIgnoreNextUpEvent = false; 11056 break; 11057 11058 case MotionEvent.ACTION_MOVE: 11059 drawableHotspotChanged(x, y); 11060 11061 // Be lenient about moving outside of buttons 11062 if (!pointInView(x, y, mTouchSlop)) { 11063 // Outside button 11064 removeTapCallback(); 11065 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 11066 // Remove any future long press/tap checks 11067 removeLongPressCallback(); 11068 11069 setPressed(false); 11070 } 11071 } 11072 break; 11073 } 11074 11075 return true; 11076 } 11077 11078 return false; 11079 } 11080 11081 /** 11082 * @hide 11083 */ 11084 public boolean isInScrollingContainer() { 11085 ViewParent p = getParent(); 11086 while (p != null && p instanceof ViewGroup) { 11087 if (((ViewGroup) p).shouldDelayChildPressedState()) { 11088 return true; 11089 } 11090 p = p.getParent(); 11091 } 11092 return false; 11093 } 11094 11095 /** 11096 * Remove the longpress detection timer. 11097 */ 11098 private void removeLongPressCallback() { 11099 if (mPendingCheckForLongPress != null) { 11100 removeCallbacks(mPendingCheckForLongPress); 11101 } 11102 } 11103 11104 /** 11105 * Remove the pending click action 11106 */ 11107 private void removePerformClickCallback() { 11108 if (mPerformClick != null) { 11109 removeCallbacks(mPerformClick); 11110 } 11111 } 11112 11113 /** 11114 * Remove the prepress detection timer. 11115 */ 11116 private void removeUnsetPressCallback() { 11117 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 11118 setPressed(false); 11119 removeCallbacks(mUnsetPressedState); 11120 } 11121 } 11122 11123 /** 11124 * Remove the tap detection timer. 11125 */ 11126 private void removeTapCallback() { 11127 if (mPendingCheckForTap != null) { 11128 mPrivateFlags &= ~PFLAG_PREPRESSED; 11129 removeCallbacks(mPendingCheckForTap); 11130 } 11131 } 11132 11133 /** 11134 * Cancels a pending long press. Your subclass can use this if you 11135 * want the context menu to come up if the user presses and holds 11136 * at the same place, but you don't want it to come up if they press 11137 * and then move around enough to cause scrolling. 11138 */ 11139 public void cancelLongPress() { 11140 removeLongPressCallback(); 11141 11142 /* 11143 * The prepressed state handled by the tap callback is a display 11144 * construct, but the tap callback will post a long press callback 11145 * less its own timeout. Remove it here. 11146 */ 11147 removeTapCallback(); 11148 } 11149 11150 /** 11151 * Remove the pending callback for sending a 11152 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 11153 */ 11154 private void removeSendViewScrolledAccessibilityEventCallback() { 11155 if (mSendViewScrolledAccessibilityEvent != null) { 11156 removeCallbacks(mSendViewScrolledAccessibilityEvent); 11157 mSendViewScrolledAccessibilityEvent.mIsPending = false; 11158 } 11159 } 11160 11161 /** 11162 * Sets the TouchDelegate for this View. 11163 */ 11164 public void setTouchDelegate(TouchDelegate delegate) { 11165 mTouchDelegate = delegate; 11166 } 11167 11168 /** 11169 * Gets the TouchDelegate for this View. 11170 */ 11171 public TouchDelegate getTouchDelegate() { 11172 return mTouchDelegate; 11173 } 11174 11175 /** 11176 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 11177 * 11178 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 11179 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 11180 * available. This method should only be called for touch events. 11181 * 11182 * <p class="note">This api is not intended for most applications. Buffered dispatch 11183 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 11184 * streams will not improve your input latency. Side effects include: increased latency, 11185 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 11186 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 11187 * you.</p> 11188 */ 11189 public final void requestUnbufferedDispatch(MotionEvent event) { 11190 final int action = event.getAction(); 11191 if (mAttachInfo == null 11192 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 11193 || !event.isTouchEvent()) { 11194 return; 11195 } 11196 mAttachInfo.mUnbufferedDispatchRequested = true; 11197 } 11198 11199 /** 11200 * Set flags controlling behavior of this view. 11201 * 11202 * @param flags Constant indicating the value which should be set 11203 * @param mask Constant indicating the bit range that should be changed 11204 */ 11205 void setFlags(int flags, int mask) { 11206 final boolean accessibilityEnabled = 11207 AccessibilityManager.getInstance(mContext).isEnabled(); 11208 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 11209 11210 int old = mViewFlags; 11211 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 11212 11213 int changed = mViewFlags ^ old; 11214 if (changed == 0) { 11215 return; 11216 } 11217 int privateFlags = mPrivateFlags; 11218 11219 /* Check if the FOCUSABLE bit has changed */ 11220 if (((changed & FOCUSABLE_MASK) != 0) && 11221 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 11222 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 11223 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 11224 /* Give up focus if we are no longer focusable */ 11225 clearFocus(); 11226 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 11227 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 11228 /* 11229 * Tell the view system that we are now available to take focus 11230 * if no one else already has it. 11231 */ 11232 if (mParent != null) mParent.focusableViewAvailable(this); 11233 } 11234 } 11235 11236 final int newVisibility = flags & VISIBILITY_MASK; 11237 if (newVisibility == VISIBLE) { 11238 if ((changed & VISIBILITY_MASK) != 0) { 11239 /* 11240 * If this view is becoming visible, invalidate it in case it changed while 11241 * it was not visible. Marking it drawn ensures that the invalidation will 11242 * go through. 11243 */ 11244 mPrivateFlags |= PFLAG_DRAWN; 11245 invalidate(true); 11246 11247 needGlobalAttributesUpdate(true); 11248 11249 // a view becoming visible is worth notifying the parent 11250 // about in case nothing has focus. even if this specific view 11251 // isn't focusable, it may contain something that is, so let 11252 // the root view try to give this focus if nothing else does. 11253 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 11254 mParent.focusableViewAvailable(this); 11255 } 11256 } 11257 } 11258 11259 /* Check if the GONE bit has changed */ 11260 if ((changed & GONE) != 0) { 11261 needGlobalAttributesUpdate(false); 11262 requestLayout(); 11263 11264 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 11265 if (hasFocus()) clearFocus(); 11266 clearAccessibilityFocus(); 11267 destroyDrawingCache(); 11268 if (mParent instanceof View) { 11269 // GONE views noop invalidation, so invalidate the parent 11270 ((View) mParent).invalidate(true); 11271 } 11272 // Mark the view drawn to ensure that it gets invalidated properly the next 11273 // time it is visible and gets invalidated 11274 mPrivateFlags |= PFLAG_DRAWN; 11275 } 11276 if (mAttachInfo != null) { 11277 mAttachInfo.mViewVisibilityChanged = true; 11278 } 11279 } 11280 11281 /* Check if the VISIBLE bit has changed */ 11282 if ((changed & INVISIBLE) != 0) { 11283 needGlobalAttributesUpdate(false); 11284 /* 11285 * If this view is becoming invisible, set the DRAWN flag so that 11286 * the next invalidate() will not be skipped. 11287 */ 11288 mPrivateFlags |= PFLAG_DRAWN; 11289 11290 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 11291 // root view becoming invisible shouldn't clear focus and accessibility focus 11292 if (getRootView() != this) { 11293 if (hasFocus()) clearFocus(); 11294 clearAccessibilityFocus(); 11295 } 11296 } 11297 if (mAttachInfo != null) { 11298 mAttachInfo.mViewVisibilityChanged = true; 11299 } 11300 } 11301 11302 if ((changed & VISIBILITY_MASK) != 0) { 11303 // If the view is invisible, cleanup its display list to free up resources 11304 if (newVisibility != VISIBLE && mAttachInfo != null) { 11305 cleanupDraw(); 11306 } 11307 11308 if (mParent instanceof ViewGroup) { 11309 ((ViewGroup) mParent).onChildVisibilityChanged(this, 11310 (changed & VISIBILITY_MASK), newVisibility); 11311 ((View) mParent).invalidate(true); 11312 } else if (mParent != null) { 11313 mParent.invalidateChild(this, null); 11314 } 11315 11316 if (mAttachInfo != null) { 11317 dispatchVisibilityChanged(this, newVisibility); 11318 notifySubtreeAccessibilityStateChangedIfNeeded(); 11319 } 11320 } 11321 11322 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 11323 destroyDrawingCache(); 11324 } 11325 11326 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 11327 destroyDrawingCache(); 11328 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11329 invalidateParentCaches(); 11330 } 11331 11332 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 11333 destroyDrawingCache(); 11334 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11335 } 11336 11337 if ((changed & DRAW_MASK) != 0) { 11338 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 11339 if (mBackground != null 11340 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 11341 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11342 } else { 11343 mPrivateFlags |= PFLAG_SKIP_DRAW; 11344 } 11345 } else { 11346 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 11347 } 11348 requestLayout(); 11349 invalidate(true); 11350 } 11351 11352 if ((changed & KEEP_SCREEN_ON) != 0) { 11353 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 11354 mParent.recomputeViewAttributes(this); 11355 } 11356 } 11357 11358 if (accessibilityEnabled) { 11359 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 11360 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 11361 || (changed & CONTEXT_CLICKABLE) != 0) { 11362 if (oldIncludeForAccessibility != includeForAccessibility()) { 11363 notifySubtreeAccessibilityStateChangedIfNeeded(); 11364 } else { 11365 notifyViewAccessibilityStateChangedIfNeeded( 11366 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11367 } 11368 } else if ((changed & ENABLED_MASK) != 0) { 11369 notifyViewAccessibilityStateChangedIfNeeded( 11370 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11371 } 11372 } 11373 } 11374 11375 /** 11376 * Change the view's z order in the tree, so it's on top of other sibling 11377 * views. This ordering change may affect layout, if the parent container 11378 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 11379 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 11380 * method should be followed by calls to {@link #requestLayout()} and 11381 * {@link View#invalidate()} on the view's parent to force the parent to redraw 11382 * with the new child ordering. 11383 * 11384 * @see ViewGroup#bringChildToFront(View) 11385 */ 11386 public void bringToFront() { 11387 if (mParent != null) { 11388 mParent.bringChildToFront(this); 11389 } 11390 } 11391 11392 /** 11393 * This is called in response to an internal scroll in this view (i.e., the 11394 * view scrolled its own contents). This is typically as a result of 11395 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 11396 * called. 11397 * 11398 * @param l Current horizontal scroll origin. 11399 * @param t Current vertical scroll origin. 11400 * @param oldl Previous horizontal scroll origin. 11401 * @param oldt Previous vertical scroll origin. 11402 */ 11403 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 11404 notifySubtreeAccessibilityStateChangedIfNeeded(); 11405 11406 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 11407 postSendViewScrolledAccessibilityEventCallback(); 11408 } 11409 11410 mBackgroundSizeChanged = true; 11411 if (mForegroundInfo != null) { 11412 mForegroundInfo.mBoundsChanged = true; 11413 } 11414 11415 final AttachInfo ai = mAttachInfo; 11416 if (ai != null) { 11417 ai.mViewScrollChanged = true; 11418 } 11419 11420 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 11421 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 11422 } 11423 } 11424 11425 /** 11426 * Interface definition for a callback to be invoked when the scroll 11427 * X or Y positions of a view change. 11428 * <p> 11429 * <b>Note:</b> Some views handle scrolling independently from View and may 11430 * have their own separate listeners for scroll-type events. For example, 11431 * {@link android.widget.ListView ListView} allows clients to register an 11432 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 11433 * to listen for changes in list scroll position. 11434 * 11435 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 11436 */ 11437 public interface OnScrollChangeListener { 11438 /** 11439 * Called when the scroll position of a view changes. 11440 * 11441 * @param v The view whose scroll position has changed. 11442 * @param scrollX Current horizontal scroll origin. 11443 * @param scrollY Current vertical scroll origin. 11444 * @param oldScrollX Previous horizontal scroll origin. 11445 * @param oldScrollY Previous vertical scroll origin. 11446 */ 11447 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 11448 } 11449 11450 /** 11451 * Interface definition for a callback to be invoked when the layout bounds of a view 11452 * changes due to layout processing. 11453 */ 11454 public interface OnLayoutChangeListener { 11455 /** 11456 * Called when the layout bounds of a view changes due to layout processing. 11457 * 11458 * @param v The view whose bounds have changed. 11459 * @param left The new value of the view's left property. 11460 * @param top The new value of the view's top property. 11461 * @param right The new value of the view's right property. 11462 * @param bottom The new value of the view's bottom property. 11463 * @param oldLeft The previous value of the view's left property. 11464 * @param oldTop The previous value of the view's top property. 11465 * @param oldRight The previous value of the view's right property. 11466 * @param oldBottom The previous value of the view's bottom property. 11467 */ 11468 void onLayoutChange(View v, int left, int top, int right, int bottom, 11469 int oldLeft, int oldTop, int oldRight, int oldBottom); 11470 } 11471 11472 /** 11473 * This is called during layout when the size of this view has changed. If 11474 * you were just added to the view hierarchy, you're called with the old 11475 * values of 0. 11476 * 11477 * @param w Current width of this view. 11478 * @param h Current height of this view. 11479 * @param oldw Old width of this view. 11480 * @param oldh Old height of this view. 11481 */ 11482 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 11483 } 11484 11485 /** 11486 * Called by draw to draw the child views. This may be overridden 11487 * by derived classes to gain control just before its children are drawn 11488 * (but after its own view has been drawn). 11489 * @param canvas the canvas on which to draw the view 11490 */ 11491 protected void dispatchDraw(Canvas canvas) { 11492 11493 } 11494 11495 /** 11496 * Gets the parent of this view. Note that the parent is a 11497 * ViewParent and not necessarily a View. 11498 * 11499 * @return Parent of this view. 11500 */ 11501 public final ViewParent getParent() { 11502 return mParent; 11503 } 11504 11505 /** 11506 * Set the horizontal scrolled position of your view. This will cause a call to 11507 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11508 * invalidated. 11509 * @param value the x position to scroll to 11510 */ 11511 public void setScrollX(int value) { 11512 scrollTo(value, mScrollY); 11513 } 11514 11515 /** 11516 * Set the vertical scrolled position of your view. This will cause a call to 11517 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11518 * invalidated. 11519 * @param value the y position to scroll to 11520 */ 11521 public void setScrollY(int value) { 11522 scrollTo(mScrollX, value); 11523 } 11524 11525 /** 11526 * Return the scrolled left position of this view. This is the left edge of 11527 * the displayed part of your view. You do not need to draw any pixels 11528 * farther left, since those are outside of the frame of your view on 11529 * screen. 11530 * 11531 * @return The left edge of the displayed part of your view, in pixels. 11532 */ 11533 public final int getScrollX() { 11534 return mScrollX; 11535 } 11536 11537 /** 11538 * Return the scrolled top position of this view. This is the top edge of 11539 * the displayed part of your view. You do not need to draw any pixels above 11540 * it, since those are outside of the frame of your view on screen. 11541 * 11542 * @return The top edge of the displayed part of your view, in pixels. 11543 */ 11544 public final int getScrollY() { 11545 return mScrollY; 11546 } 11547 11548 /** 11549 * Return the width of the your view. 11550 * 11551 * @return The width of your view, in pixels. 11552 */ 11553 @ViewDebug.ExportedProperty(category = "layout") 11554 public final int getWidth() { 11555 return mRight - mLeft; 11556 } 11557 11558 /** 11559 * Return the height of your view. 11560 * 11561 * @return The height of your view, in pixels. 11562 */ 11563 @ViewDebug.ExportedProperty(category = "layout") 11564 public final int getHeight() { 11565 return mBottom - mTop; 11566 } 11567 11568 /** 11569 * Return the visible drawing bounds of your view. Fills in the output 11570 * rectangle with the values from getScrollX(), getScrollY(), 11571 * getWidth(), and getHeight(). These bounds do not account for any 11572 * transformation properties currently set on the view, such as 11573 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 11574 * 11575 * @param outRect The (scrolled) drawing bounds of the view. 11576 */ 11577 public void getDrawingRect(Rect outRect) { 11578 outRect.left = mScrollX; 11579 outRect.top = mScrollY; 11580 outRect.right = mScrollX + (mRight - mLeft); 11581 outRect.bottom = mScrollY + (mBottom - mTop); 11582 } 11583 11584 /** 11585 * Like {@link #getMeasuredWidthAndState()}, but only returns the 11586 * raw width component (that is the result is masked by 11587 * {@link #MEASURED_SIZE_MASK}). 11588 * 11589 * @return The raw measured width of this view. 11590 */ 11591 public final int getMeasuredWidth() { 11592 return mMeasuredWidth & MEASURED_SIZE_MASK; 11593 } 11594 11595 /** 11596 * Return the full width measurement information for this view as computed 11597 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11598 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11599 * This should be used during measurement and layout calculations only. Use 11600 * {@link #getWidth()} to see how wide a view is after layout. 11601 * 11602 * @return The measured width of this view as a bit mask. 11603 */ 11604 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11605 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11606 name = "MEASURED_STATE_TOO_SMALL"), 11607 }) 11608 public final int getMeasuredWidthAndState() { 11609 return mMeasuredWidth; 11610 } 11611 11612 /** 11613 * Like {@link #getMeasuredHeightAndState()}, but only returns the 11614 * raw width component (that is the result is masked by 11615 * {@link #MEASURED_SIZE_MASK}). 11616 * 11617 * @return The raw measured height of this view. 11618 */ 11619 public final int getMeasuredHeight() { 11620 return mMeasuredHeight & MEASURED_SIZE_MASK; 11621 } 11622 11623 /** 11624 * Return the full height measurement information for this view as computed 11625 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 11626 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 11627 * This should be used during measurement and layout calculations only. Use 11628 * {@link #getHeight()} to see how wide a view is after layout. 11629 * 11630 * @return The measured width of this view as a bit mask. 11631 */ 11632 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 11633 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 11634 name = "MEASURED_STATE_TOO_SMALL"), 11635 }) 11636 public final int getMeasuredHeightAndState() { 11637 return mMeasuredHeight; 11638 } 11639 11640 /** 11641 * Return only the state bits of {@link #getMeasuredWidthAndState()} 11642 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 11643 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 11644 * and the height component is at the shifted bits 11645 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 11646 */ 11647 public final int getMeasuredState() { 11648 return (mMeasuredWidth&MEASURED_STATE_MASK) 11649 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 11650 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 11651 } 11652 11653 /** 11654 * The transform matrix of this view, which is calculated based on the current 11655 * rotation, scale, and pivot properties. 11656 * 11657 * @see #getRotation() 11658 * @see #getScaleX() 11659 * @see #getScaleY() 11660 * @see #getPivotX() 11661 * @see #getPivotY() 11662 * @return The current transform matrix for the view 11663 */ 11664 public Matrix getMatrix() { 11665 ensureTransformationInfo(); 11666 final Matrix matrix = mTransformationInfo.mMatrix; 11667 mRenderNode.getMatrix(matrix); 11668 return matrix; 11669 } 11670 11671 /** 11672 * Returns true if the transform matrix is the identity matrix. 11673 * Recomputes the matrix if necessary. 11674 * 11675 * @return True if the transform matrix is the identity matrix, false otherwise. 11676 */ 11677 final boolean hasIdentityMatrix() { 11678 return mRenderNode.hasIdentityMatrix(); 11679 } 11680 11681 void ensureTransformationInfo() { 11682 if (mTransformationInfo == null) { 11683 mTransformationInfo = new TransformationInfo(); 11684 } 11685 } 11686 11687 /** 11688 * Utility method to retrieve the inverse of the current mMatrix property. 11689 * We cache the matrix to avoid recalculating it when transform properties 11690 * have not changed. 11691 * 11692 * @return The inverse of the current matrix of this view. 11693 * @hide 11694 */ 11695 public final Matrix getInverseMatrix() { 11696 ensureTransformationInfo(); 11697 if (mTransformationInfo.mInverseMatrix == null) { 11698 mTransformationInfo.mInverseMatrix = new Matrix(); 11699 } 11700 final Matrix matrix = mTransformationInfo.mInverseMatrix; 11701 mRenderNode.getInverseMatrix(matrix); 11702 return matrix; 11703 } 11704 11705 /** 11706 * Gets the distance along the Z axis from the camera to this view. 11707 * 11708 * @see #setCameraDistance(float) 11709 * 11710 * @return The distance along the Z axis. 11711 */ 11712 public float getCameraDistance() { 11713 final float dpi = mResources.getDisplayMetrics().densityDpi; 11714 return -(mRenderNode.getCameraDistance() * dpi); 11715 } 11716 11717 /** 11718 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 11719 * views are drawn) from the camera to this view. The camera's distance 11720 * affects 3D transformations, for instance rotations around the X and Y 11721 * axis. If the rotationX or rotationY properties are changed and this view is 11722 * large (more than half the size of the screen), it is recommended to always 11723 * use a camera distance that's greater than the height (X axis rotation) or 11724 * the width (Y axis rotation) of this view.</p> 11725 * 11726 * <p>The distance of the camera from the view plane can have an affect on the 11727 * perspective distortion of the view when it is rotated around the x or y axis. 11728 * For example, a large distance will result in a large viewing angle, and there 11729 * will not be much perspective distortion of the view as it rotates. A short 11730 * distance may cause much more perspective distortion upon rotation, and can 11731 * also result in some drawing artifacts if the rotated view ends up partially 11732 * behind the camera (which is why the recommendation is to use a distance at 11733 * least as far as the size of the view, if the view is to be rotated.)</p> 11734 * 11735 * <p>The distance is expressed in "depth pixels." The default distance depends 11736 * on the screen density. For instance, on a medium density display, the 11737 * default distance is 1280. On a high density display, the default distance 11738 * is 1920.</p> 11739 * 11740 * <p>If you want to specify a distance that leads to visually consistent 11741 * results across various densities, use the following formula:</p> 11742 * <pre> 11743 * float scale = context.getResources().getDisplayMetrics().density; 11744 * view.setCameraDistance(distance * scale); 11745 * </pre> 11746 * 11747 * <p>The density scale factor of a high density display is 1.5, 11748 * and 1920 = 1280 * 1.5.</p> 11749 * 11750 * @param distance The distance in "depth pixels", if negative the opposite 11751 * value is used 11752 * 11753 * @see #setRotationX(float) 11754 * @see #setRotationY(float) 11755 */ 11756 public void setCameraDistance(float distance) { 11757 final float dpi = mResources.getDisplayMetrics().densityDpi; 11758 11759 invalidateViewProperty(true, false); 11760 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 11761 invalidateViewProperty(false, false); 11762 11763 invalidateParentIfNeededAndWasQuickRejected(); 11764 } 11765 11766 /** 11767 * The degrees that the view is rotated around the pivot point. 11768 * 11769 * @see #setRotation(float) 11770 * @see #getPivotX() 11771 * @see #getPivotY() 11772 * 11773 * @return The degrees of rotation. 11774 */ 11775 @ViewDebug.ExportedProperty(category = "drawing") 11776 public float getRotation() { 11777 return mRenderNode.getRotation(); 11778 } 11779 11780 /** 11781 * Sets the degrees that the view is rotated around the pivot point. Increasing values 11782 * result in clockwise rotation. 11783 * 11784 * @param rotation The degrees of rotation. 11785 * 11786 * @see #getRotation() 11787 * @see #getPivotX() 11788 * @see #getPivotY() 11789 * @see #setRotationX(float) 11790 * @see #setRotationY(float) 11791 * 11792 * @attr ref android.R.styleable#View_rotation 11793 */ 11794 public void setRotation(float rotation) { 11795 if (rotation != getRotation()) { 11796 // Double-invalidation is necessary to capture view's old and new areas 11797 invalidateViewProperty(true, false); 11798 mRenderNode.setRotation(rotation); 11799 invalidateViewProperty(false, true); 11800 11801 invalidateParentIfNeededAndWasQuickRejected(); 11802 notifySubtreeAccessibilityStateChangedIfNeeded(); 11803 } 11804 } 11805 11806 /** 11807 * The degrees that the view is rotated around the vertical axis through the pivot point. 11808 * 11809 * @see #getPivotX() 11810 * @see #getPivotY() 11811 * @see #setRotationY(float) 11812 * 11813 * @return The degrees of Y rotation. 11814 */ 11815 @ViewDebug.ExportedProperty(category = "drawing") 11816 public float getRotationY() { 11817 return mRenderNode.getRotationY(); 11818 } 11819 11820 /** 11821 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 11822 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 11823 * down the y axis. 11824 * 11825 * When rotating large views, it is recommended to adjust the camera distance 11826 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11827 * 11828 * @param rotationY The degrees of Y rotation. 11829 * 11830 * @see #getRotationY() 11831 * @see #getPivotX() 11832 * @see #getPivotY() 11833 * @see #setRotation(float) 11834 * @see #setRotationX(float) 11835 * @see #setCameraDistance(float) 11836 * 11837 * @attr ref android.R.styleable#View_rotationY 11838 */ 11839 public void setRotationY(float rotationY) { 11840 if (rotationY != getRotationY()) { 11841 invalidateViewProperty(true, false); 11842 mRenderNode.setRotationY(rotationY); 11843 invalidateViewProperty(false, true); 11844 11845 invalidateParentIfNeededAndWasQuickRejected(); 11846 notifySubtreeAccessibilityStateChangedIfNeeded(); 11847 } 11848 } 11849 11850 /** 11851 * The degrees that the view is rotated around the horizontal axis through the pivot point. 11852 * 11853 * @see #getPivotX() 11854 * @see #getPivotY() 11855 * @see #setRotationX(float) 11856 * 11857 * @return The degrees of X rotation. 11858 */ 11859 @ViewDebug.ExportedProperty(category = "drawing") 11860 public float getRotationX() { 11861 return mRenderNode.getRotationX(); 11862 } 11863 11864 /** 11865 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 11866 * Increasing values result in clockwise rotation from the viewpoint of looking down the 11867 * x axis. 11868 * 11869 * When rotating large views, it is recommended to adjust the camera distance 11870 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 11871 * 11872 * @param rotationX The degrees of X rotation. 11873 * 11874 * @see #getRotationX() 11875 * @see #getPivotX() 11876 * @see #getPivotY() 11877 * @see #setRotation(float) 11878 * @see #setRotationY(float) 11879 * @see #setCameraDistance(float) 11880 * 11881 * @attr ref android.R.styleable#View_rotationX 11882 */ 11883 public void setRotationX(float rotationX) { 11884 if (rotationX != getRotationX()) { 11885 invalidateViewProperty(true, false); 11886 mRenderNode.setRotationX(rotationX); 11887 invalidateViewProperty(false, true); 11888 11889 invalidateParentIfNeededAndWasQuickRejected(); 11890 notifySubtreeAccessibilityStateChangedIfNeeded(); 11891 } 11892 } 11893 11894 /** 11895 * The amount that the view is scaled in x around the pivot point, as a proportion of 11896 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 11897 * 11898 * <p>By default, this is 1.0f. 11899 * 11900 * @see #getPivotX() 11901 * @see #getPivotY() 11902 * @return The scaling factor. 11903 */ 11904 @ViewDebug.ExportedProperty(category = "drawing") 11905 public float getScaleX() { 11906 return mRenderNode.getScaleX(); 11907 } 11908 11909 /** 11910 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 11911 * the view's unscaled width. A value of 1 means that no scaling is applied. 11912 * 11913 * @param scaleX The scaling factor. 11914 * @see #getPivotX() 11915 * @see #getPivotY() 11916 * 11917 * @attr ref android.R.styleable#View_scaleX 11918 */ 11919 public void setScaleX(float scaleX) { 11920 if (scaleX != getScaleX()) { 11921 invalidateViewProperty(true, false); 11922 mRenderNode.setScaleX(scaleX); 11923 invalidateViewProperty(false, true); 11924 11925 invalidateParentIfNeededAndWasQuickRejected(); 11926 notifySubtreeAccessibilityStateChangedIfNeeded(); 11927 } 11928 } 11929 11930 /** 11931 * The amount that the view is scaled in y around the pivot point, as a proportion of 11932 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 11933 * 11934 * <p>By default, this is 1.0f. 11935 * 11936 * @see #getPivotX() 11937 * @see #getPivotY() 11938 * @return The scaling factor. 11939 */ 11940 @ViewDebug.ExportedProperty(category = "drawing") 11941 public float getScaleY() { 11942 return mRenderNode.getScaleY(); 11943 } 11944 11945 /** 11946 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 11947 * the view's unscaled width. A value of 1 means that no scaling is applied. 11948 * 11949 * @param scaleY The scaling factor. 11950 * @see #getPivotX() 11951 * @see #getPivotY() 11952 * 11953 * @attr ref android.R.styleable#View_scaleY 11954 */ 11955 public void setScaleY(float scaleY) { 11956 if (scaleY != getScaleY()) { 11957 invalidateViewProperty(true, false); 11958 mRenderNode.setScaleY(scaleY); 11959 invalidateViewProperty(false, true); 11960 11961 invalidateParentIfNeededAndWasQuickRejected(); 11962 notifySubtreeAccessibilityStateChangedIfNeeded(); 11963 } 11964 } 11965 11966 /** 11967 * The x location of the point around which the view is {@link #setRotation(float) rotated} 11968 * and {@link #setScaleX(float) scaled}. 11969 * 11970 * @see #getRotation() 11971 * @see #getScaleX() 11972 * @see #getScaleY() 11973 * @see #getPivotY() 11974 * @return The x location of the pivot point. 11975 * 11976 * @attr ref android.R.styleable#View_transformPivotX 11977 */ 11978 @ViewDebug.ExportedProperty(category = "drawing") 11979 public float getPivotX() { 11980 return mRenderNode.getPivotX(); 11981 } 11982 11983 /** 11984 * Sets the x location of the point around which the view is 11985 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 11986 * By default, the pivot point is centered on the object. 11987 * Setting this property disables this behavior and causes the view to use only the 11988 * explicitly set pivotX and pivotY values. 11989 * 11990 * @param pivotX The x location of the pivot point. 11991 * @see #getRotation() 11992 * @see #getScaleX() 11993 * @see #getScaleY() 11994 * @see #getPivotY() 11995 * 11996 * @attr ref android.R.styleable#View_transformPivotX 11997 */ 11998 public void setPivotX(float pivotX) { 11999 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 12000 invalidateViewProperty(true, false); 12001 mRenderNode.setPivotX(pivotX); 12002 invalidateViewProperty(false, true); 12003 12004 invalidateParentIfNeededAndWasQuickRejected(); 12005 } 12006 } 12007 12008 /** 12009 * The y location of the point around which the view is {@link #setRotation(float) rotated} 12010 * and {@link #setScaleY(float) scaled}. 12011 * 12012 * @see #getRotation() 12013 * @see #getScaleX() 12014 * @see #getScaleY() 12015 * @see #getPivotY() 12016 * @return The y location of the pivot point. 12017 * 12018 * @attr ref android.R.styleable#View_transformPivotY 12019 */ 12020 @ViewDebug.ExportedProperty(category = "drawing") 12021 public float getPivotY() { 12022 return mRenderNode.getPivotY(); 12023 } 12024 12025 /** 12026 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 12027 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 12028 * Setting this property disables this behavior and causes the view to use only the 12029 * explicitly set pivotX and pivotY values. 12030 * 12031 * @param pivotY The y location of the pivot point. 12032 * @see #getRotation() 12033 * @see #getScaleX() 12034 * @see #getScaleY() 12035 * @see #getPivotY() 12036 * 12037 * @attr ref android.R.styleable#View_transformPivotY 12038 */ 12039 public void setPivotY(float pivotY) { 12040 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 12041 invalidateViewProperty(true, false); 12042 mRenderNode.setPivotY(pivotY); 12043 invalidateViewProperty(false, true); 12044 12045 invalidateParentIfNeededAndWasQuickRejected(); 12046 } 12047 } 12048 12049 /** 12050 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 12051 * completely transparent and 1 means the view is completely opaque. 12052 * 12053 * <p>By default this is 1.0f. 12054 * @return The opacity of the view. 12055 */ 12056 @ViewDebug.ExportedProperty(category = "drawing") 12057 public float getAlpha() { 12058 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 12059 } 12060 12061 /** 12062 * Returns whether this View has content which overlaps. 12063 * 12064 * <p>This function, intended to be overridden by specific View types, is an optimization when 12065 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 12066 * an offscreen buffer and then composited into place, which can be expensive. If the view has 12067 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 12068 * directly. An example of overlapping rendering is a TextView with a background image, such as 12069 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 12070 * ImageView with only the foreground image. The default implementation returns true; subclasses 12071 * should override if they have cases which can be optimized.</p> 12072 * 12073 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 12074 * necessitates that a View return true if it uses the methods internally without passing the 12075 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 12076 * 12077 * @return true if the content in this view might overlap, false otherwise. 12078 */ 12079 @ViewDebug.ExportedProperty(category = "drawing") 12080 public boolean hasOverlappingRendering() { 12081 return true; 12082 } 12083 12084 /** 12085 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 12086 * completely transparent and 1 means the view is completely opaque. 12087 * 12088 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 12089 * can have significant performance implications, especially for large views. It is best to use 12090 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 12091 * 12092 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 12093 * strongly recommended for performance reasons to either override 12094 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 12095 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 12096 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 12097 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 12098 * of rendering cost, even for simple or small views. Starting with 12099 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 12100 * applied to the view at the rendering level.</p> 12101 * 12102 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 12103 * responsible for applying the opacity itself.</p> 12104 * 12105 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 12106 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 12107 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 12108 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 12109 * 12110 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 12111 * value will clip a View to its bounds, unless the View returns <code>false</code> from 12112 * {@link #hasOverlappingRendering}.</p> 12113 * 12114 * @param alpha The opacity of the view. 12115 * 12116 * @see #hasOverlappingRendering() 12117 * @see #setLayerType(int, android.graphics.Paint) 12118 * 12119 * @attr ref android.R.styleable#View_alpha 12120 */ 12121 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 12122 ensureTransformationInfo(); 12123 if (mTransformationInfo.mAlpha != alpha) { 12124 mTransformationInfo.mAlpha = alpha; 12125 if (onSetAlpha((int) (alpha * 255))) { 12126 mPrivateFlags |= PFLAG_ALPHA_SET; 12127 // subclass is handling alpha - don't optimize rendering cache invalidation 12128 invalidateParentCaches(); 12129 invalidate(true); 12130 } else { 12131 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12132 invalidateViewProperty(true, false); 12133 mRenderNode.setAlpha(getFinalAlpha()); 12134 notifyViewAccessibilityStateChangedIfNeeded( 12135 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12136 } 12137 } 12138 } 12139 12140 /** 12141 * Faster version of setAlpha() which performs the same steps except there are 12142 * no calls to invalidate(). The caller of this function should perform proper invalidation 12143 * on the parent and this object. The return value indicates whether the subclass handles 12144 * alpha (the return value for onSetAlpha()). 12145 * 12146 * @param alpha The new value for the alpha property 12147 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 12148 * the new value for the alpha property is different from the old value 12149 */ 12150 boolean setAlphaNoInvalidation(float alpha) { 12151 ensureTransformationInfo(); 12152 if (mTransformationInfo.mAlpha != alpha) { 12153 mTransformationInfo.mAlpha = alpha; 12154 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 12155 if (subclassHandlesAlpha) { 12156 mPrivateFlags |= PFLAG_ALPHA_SET; 12157 return true; 12158 } else { 12159 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12160 mRenderNode.setAlpha(getFinalAlpha()); 12161 } 12162 } 12163 return false; 12164 } 12165 12166 /** 12167 * This property is hidden and intended only for use by the Fade transition, which 12168 * animates it to produce a visual translucency that does not side-effect (or get 12169 * affected by) the real alpha property. This value is composited with the other 12170 * alpha value (and the AlphaAnimation value, when that is present) to produce 12171 * a final visual translucency result, which is what is passed into the DisplayList. 12172 * 12173 * @hide 12174 */ 12175 public void setTransitionAlpha(float alpha) { 12176 ensureTransformationInfo(); 12177 if (mTransformationInfo.mTransitionAlpha != alpha) { 12178 mTransformationInfo.mTransitionAlpha = alpha; 12179 mPrivateFlags &= ~PFLAG_ALPHA_SET; 12180 invalidateViewProperty(true, false); 12181 mRenderNode.setAlpha(getFinalAlpha()); 12182 } 12183 } 12184 12185 /** 12186 * Calculates the visual alpha of this view, which is a combination of the actual 12187 * alpha value and the transitionAlpha value (if set). 12188 */ 12189 private float getFinalAlpha() { 12190 if (mTransformationInfo != null) { 12191 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 12192 } 12193 return 1; 12194 } 12195 12196 /** 12197 * This property is hidden and intended only for use by the Fade transition, which 12198 * animates it to produce a visual translucency that does not side-effect (or get 12199 * affected by) the real alpha property. This value is composited with the other 12200 * alpha value (and the AlphaAnimation value, when that is present) to produce 12201 * a final visual translucency result, which is what is passed into the DisplayList. 12202 * 12203 * @hide 12204 */ 12205 @ViewDebug.ExportedProperty(category = "drawing") 12206 public float getTransitionAlpha() { 12207 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 12208 } 12209 12210 /** 12211 * Top position of this view relative to its parent. 12212 * 12213 * @return The top of this view, in pixels. 12214 */ 12215 @ViewDebug.CapturedViewProperty 12216 public final int getTop() { 12217 return mTop; 12218 } 12219 12220 /** 12221 * Sets the top position of this view relative to its parent. This method is meant to be called 12222 * by the layout system and should not generally be called otherwise, because the property 12223 * may be changed at any time by the layout. 12224 * 12225 * @param top The top of this view, in pixels. 12226 */ 12227 public final void setTop(int top) { 12228 if (top != mTop) { 12229 final boolean matrixIsIdentity = hasIdentityMatrix(); 12230 if (matrixIsIdentity) { 12231 if (mAttachInfo != null) { 12232 int minTop; 12233 int yLoc; 12234 if (top < mTop) { 12235 minTop = top; 12236 yLoc = top - mTop; 12237 } else { 12238 minTop = mTop; 12239 yLoc = 0; 12240 } 12241 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 12242 } 12243 } else { 12244 // Double-invalidation is necessary to capture view's old and new areas 12245 invalidate(true); 12246 } 12247 12248 int width = mRight - mLeft; 12249 int oldHeight = mBottom - mTop; 12250 12251 mTop = top; 12252 mRenderNode.setTop(mTop); 12253 12254 sizeChange(width, mBottom - mTop, width, oldHeight); 12255 12256 if (!matrixIsIdentity) { 12257 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12258 invalidate(true); 12259 } 12260 mBackgroundSizeChanged = true; 12261 if (mForegroundInfo != null) { 12262 mForegroundInfo.mBoundsChanged = true; 12263 } 12264 invalidateParentIfNeeded(); 12265 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12266 // View was rejected last time it was drawn by its parent; this may have changed 12267 invalidateParentIfNeeded(); 12268 } 12269 } 12270 } 12271 12272 /** 12273 * Bottom position of this view relative to its parent. 12274 * 12275 * @return The bottom of this view, in pixels. 12276 */ 12277 @ViewDebug.CapturedViewProperty 12278 public final int getBottom() { 12279 return mBottom; 12280 } 12281 12282 /** 12283 * True if this view has changed since the last time being drawn. 12284 * 12285 * @return The dirty state of this view. 12286 */ 12287 public boolean isDirty() { 12288 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 12289 } 12290 12291 /** 12292 * Sets the bottom position of this view relative to its parent. This method is meant to be 12293 * called by the layout system and should not generally be called otherwise, because the 12294 * property may be changed at any time by the layout. 12295 * 12296 * @param bottom The bottom of this view, in pixels. 12297 */ 12298 public final void setBottom(int bottom) { 12299 if (bottom != mBottom) { 12300 final boolean matrixIsIdentity = hasIdentityMatrix(); 12301 if (matrixIsIdentity) { 12302 if (mAttachInfo != null) { 12303 int maxBottom; 12304 if (bottom < mBottom) { 12305 maxBottom = mBottom; 12306 } else { 12307 maxBottom = bottom; 12308 } 12309 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 12310 } 12311 } else { 12312 // Double-invalidation is necessary to capture view's old and new areas 12313 invalidate(true); 12314 } 12315 12316 int width = mRight - mLeft; 12317 int oldHeight = mBottom - mTop; 12318 12319 mBottom = bottom; 12320 mRenderNode.setBottom(mBottom); 12321 12322 sizeChange(width, mBottom - mTop, width, oldHeight); 12323 12324 if (!matrixIsIdentity) { 12325 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12326 invalidate(true); 12327 } 12328 mBackgroundSizeChanged = true; 12329 if (mForegroundInfo != null) { 12330 mForegroundInfo.mBoundsChanged = true; 12331 } 12332 invalidateParentIfNeeded(); 12333 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12334 // View was rejected last time it was drawn by its parent; this may have changed 12335 invalidateParentIfNeeded(); 12336 } 12337 } 12338 } 12339 12340 /** 12341 * Left position of this view relative to its parent. 12342 * 12343 * @return The left edge of this view, in pixels. 12344 */ 12345 @ViewDebug.CapturedViewProperty 12346 public final int getLeft() { 12347 return mLeft; 12348 } 12349 12350 /** 12351 * Sets the left position of this view relative to its parent. This method is meant to be called 12352 * by the layout system and should not generally be called otherwise, because the property 12353 * may be changed at any time by the layout. 12354 * 12355 * @param left The left of this view, in pixels. 12356 */ 12357 public final void setLeft(int left) { 12358 if (left != mLeft) { 12359 final boolean matrixIsIdentity = hasIdentityMatrix(); 12360 if (matrixIsIdentity) { 12361 if (mAttachInfo != null) { 12362 int minLeft; 12363 int xLoc; 12364 if (left < mLeft) { 12365 minLeft = left; 12366 xLoc = left - mLeft; 12367 } else { 12368 minLeft = mLeft; 12369 xLoc = 0; 12370 } 12371 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 12372 } 12373 } else { 12374 // Double-invalidation is necessary to capture view's old and new areas 12375 invalidate(true); 12376 } 12377 12378 int oldWidth = mRight - mLeft; 12379 int height = mBottom - mTop; 12380 12381 mLeft = left; 12382 mRenderNode.setLeft(left); 12383 12384 sizeChange(mRight - mLeft, height, oldWidth, height); 12385 12386 if (!matrixIsIdentity) { 12387 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12388 invalidate(true); 12389 } 12390 mBackgroundSizeChanged = true; 12391 if (mForegroundInfo != null) { 12392 mForegroundInfo.mBoundsChanged = true; 12393 } 12394 invalidateParentIfNeeded(); 12395 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12396 // View was rejected last time it was drawn by its parent; this may have changed 12397 invalidateParentIfNeeded(); 12398 } 12399 } 12400 } 12401 12402 /** 12403 * Right position of this view relative to its parent. 12404 * 12405 * @return The right edge of this view, in pixels. 12406 */ 12407 @ViewDebug.CapturedViewProperty 12408 public final int getRight() { 12409 return mRight; 12410 } 12411 12412 /** 12413 * Sets the right position of this view relative to its parent. This method is meant to be called 12414 * by the layout system and should not generally be called otherwise, because the property 12415 * may be changed at any time by the layout. 12416 * 12417 * @param right The right of this view, in pixels. 12418 */ 12419 public final void setRight(int right) { 12420 if (right != mRight) { 12421 final boolean matrixIsIdentity = hasIdentityMatrix(); 12422 if (matrixIsIdentity) { 12423 if (mAttachInfo != null) { 12424 int maxRight; 12425 if (right < mRight) { 12426 maxRight = mRight; 12427 } else { 12428 maxRight = right; 12429 } 12430 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 12431 } 12432 } else { 12433 // Double-invalidation is necessary to capture view's old and new areas 12434 invalidate(true); 12435 } 12436 12437 int oldWidth = mRight - mLeft; 12438 int height = mBottom - mTop; 12439 12440 mRight = right; 12441 mRenderNode.setRight(mRight); 12442 12443 sizeChange(mRight - mLeft, height, oldWidth, height); 12444 12445 if (!matrixIsIdentity) { 12446 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 12447 invalidate(true); 12448 } 12449 mBackgroundSizeChanged = true; 12450 if (mForegroundInfo != null) { 12451 mForegroundInfo.mBoundsChanged = true; 12452 } 12453 invalidateParentIfNeeded(); 12454 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 12455 // View was rejected last time it was drawn by its parent; this may have changed 12456 invalidateParentIfNeeded(); 12457 } 12458 } 12459 } 12460 12461 /** 12462 * The visual x position of this view, in pixels. This is equivalent to the 12463 * {@link #setTranslationX(float) translationX} property plus the current 12464 * {@link #getLeft() left} property. 12465 * 12466 * @return The visual x position of this view, in pixels. 12467 */ 12468 @ViewDebug.ExportedProperty(category = "drawing") 12469 public float getX() { 12470 return mLeft + getTranslationX(); 12471 } 12472 12473 /** 12474 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 12475 * {@link #setTranslationX(float) translationX} property to be the difference between 12476 * the x value passed in and the current {@link #getLeft() left} property. 12477 * 12478 * @param x The visual x position of this view, in pixels. 12479 */ 12480 public void setX(float x) { 12481 setTranslationX(x - mLeft); 12482 } 12483 12484 /** 12485 * The visual y position of this view, in pixels. This is equivalent to the 12486 * {@link #setTranslationY(float) translationY} property plus the current 12487 * {@link #getTop() top} property. 12488 * 12489 * @return The visual y position of this view, in pixels. 12490 */ 12491 @ViewDebug.ExportedProperty(category = "drawing") 12492 public float getY() { 12493 return mTop + getTranslationY(); 12494 } 12495 12496 /** 12497 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 12498 * {@link #setTranslationY(float) translationY} property to be the difference between 12499 * the y value passed in and the current {@link #getTop() top} property. 12500 * 12501 * @param y The visual y position of this view, in pixels. 12502 */ 12503 public void setY(float y) { 12504 setTranslationY(y - mTop); 12505 } 12506 12507 /** 12508 * The visual z position of this view, in pixels. This is equivalent to the 12509 * {@link #setTranslationZ(float) translationZ} property plus the current 12510 * {@link #getElevation() elevation} property. 12511 * 12512 * @return The visual z position of this view, in pixels. 12513 */ 12514 @ViewDebug.ExportedProperty(category = "drawing") 12515 public float getZ() { 12516 return getElevation() + getTranslationZ(); 12517 } 12518 12519 /** 12520 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 12521 * {@link #setTranslationZ(float) translationZ} property to be the difference between 12522 * the x value passed in and the current {@link #getElevation() elevation} property. 12523 * 12524 * @param z The visual z position of this view, in pixels. 12525 */ 12526 public void setZ(float z) { 12527 setTranslationZ(z - getElevation()); 12528 } 12529 12530 /** 12531 * The base elevation of this view relative to its parent, in pixels. 12532 * 12533 * @return The base depth position of the view, in pixels. 12534 */ 12535 @ViewDebug.ExportedProperty(category = "drawing") 12536 public float getElevation() { 12537 return mRenderNode.getElevation(); 12538 } 12539 12540 /** 12541 * Sets the base elevation of this view, in pixels. 12542 * 12543 * @attr ref android.R.styleable#View_elevation 12544 */ 12545 public void setElevation(float elevation) { 12546 if (elevation != getElevation()) { 12547 invalidateViewProperty(true, false); 12548 mRenderNode.setElevation(elevation); 12549 invalidateViewProperty(false, true); 12550 12551 invalidateParentIfNeededAndWasQuickRejected(); 12552 } 12553 } 12554 12555 /** 12556 * The horizontal location of this view relative to its {@link #getLeft() left} position. 12557 * This position is post-layout, in addition to wherever the object's 12558 * layout placed it. 12559 * 12560 * @return The horizontal position of this view relative to its left position, in pixels. 12561 */ 12562 @ViewDebug.ExportedProperty(category = "drawing") 12563 public float getTranslationX() { 12564 return mRenderNode.getTranslationX(); 12565 } 12566 12567 /** 12568 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 12569 * This effectively positions the object post-layout, in addition to wherever the object's 12570 * layout placed it. 12571 * 12572 * @param translationX The horizontal position of this view relative to its left position, 12573 * in pixels. 12574 * 12575 * @attr ref android.R.styleable#View_translationX 12576 */ 12577 public void setTranslationX(float translationX) { 12578 if (translationX != getTranslationX()) { 12579 invalidateViewProperty(true, false); 12580 mRenderNode.setTranslationX(translationX); 12581 invalidateViewProperty(false, true); 12582 12583 invalidateParentIfNeededAndWasQuickRejected(); 12584 notifySubtreeAccessibilityStateChangedIfNeeded(); 12585 } 12586 } 12587 12588 /** 12589 * The vertical location of this view relative to its {@link #getTop() top} position. 12590 * This position is post-layout, in addition to wherever the object's 12591 * layout placed it. 12592 * 12593 * @return The vertical position of this view relative to its top position, 12594 * in pixels. 12595 */ 12596 @ViewDebug.ExportedProperty(category = "drawing") 12597 public float getTranslationY() { 12598 return mRenderNode.getTranslationY(); 12599 } 12600 12601 /** 12602 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 12603 * This effectively positions the object post-layout, in addition to wherever the object's 12604 * layout placed it. 12605 * 12606 * @param translationY The vertical position of this view relative to its top position, 12607 * in pixels. 12608 * 12609 * @attr ref android.R.styleable#View_translationY 12610 */ 12611 public void setTranslationY(float translationY) { 12612 if (translationY != getTranslationY()) { 12613 invalidateViewProperty(true, false); 12614 mRenderNode.setTranslationY(translationY); 12615 invalidateViewProperty(false, true); 12616 12617 invalidateParentIfNeededAndWasQuickRejected(); 12618 notifySubtreeAccessibilityStateChangedIfNeeded(); 12619 } 12620 } 12621 12622 /** 12623 * The depth location of this view relative to its {@link #getElevation() elevation}. 12624 * 12625 * @return The depth of this view relative to its elevation. 12626 */ 12627 @ViewDebug.ExportedProperty(category = "drawing") 12628 public float getTranslationZ() { 12629 return mRenderNode.getTranslationZ(); 12630 } 12631 12632 /** 12633 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 12634 * 12635 * @attr ref android.R.styleable#View_translationZ 12636 */ 12637 public void setTranslationZ(float translationZ) { 12638 if (translationZ != getTranslationZ()) { 12639 invalidateViewProperty(true, false); 12640 mRenderNode.setTranslationZ(translationZ); 12641 invalidateViewProperty(false, true); 12642 12643 invalidateParentIfNeededAndWasQuickRejected(); 12644 } 12645 } 12646 12647 /** @hide */ 12648 public void setAnimationMatrix(Matrix matrix) { 12649 invalidateViewProperty(true, false); 12650 mRenderNode.setAnimationMatrix(matrix); 12651 invalidateViewProperty(false, true); 12652 12653 invalidateParentIfNeededAndWasQuickRejected(); 12654 } 12655 12656 /** 12657 * Returns the current StateListAnimator if exists. 12658 * 12659 * @return StateListAnimator or null if it does not exists 12660 * @see #setStateListAnimator(android.animation.StateListAnimator) 12661 */ 12662 public StateListAnimator getStateListAnimator() { 12663 return mStateListAnimator; 12664 } 12665 12666 /** 12667 * Attaches the provided StateListAnimator to this View. 12668 * <p> 12669 * Any previously attached StateListAnimator will be detached. 12670 * 12671 * @param stateListAnimator The StateListAnimator to update the view 12672 * @see {@link android.animation.StateListAnimator} 12673 */ 12674 public void setStateListAnimator(StateListAnimator stateListAnimator) { 12675 if (mStateListAnimator == stateListAnimator) { 12676 return; 12677 } 12678 if (mStateListAnimator != null) { 12679 mStateListAnimator.setTarget(null); 12680 } 12681 mStateListAnimator = stateListAnimator; 12682 if (stateListAnimator != null) { 12683 stateListAnimator.setTarget(this); 12684 if (isAttachedToWindow()) { 12685 stateListAnimator.setState(getDrawableState()); 12686 } 12687 } 12688 } 12689 12690 /** 12691 * Returns whether the Outline should be used to clip the contents of the View. 12692 * <p> 12693 * Note that this flag will only be respected if the View's Outline returns true from 12694 * {@link Outline#canClip()}. 12695 * 12696 * @see #setOutlineProvider(ViewOutlineProvider) 12697 * @see #setClipToOutline(boolean) 12698 */ 12699 public final boolean getClipToOutline() { 12700 return mRenderNode.getClipToOutline(); 12701 } 12702 12703 /** 12704 * Sets whether the View's Outline should be used to clip the contents of the View. 12705 * <p> 12706 * Only a single non-rectangular clip can be applied on a View at any time. 12707 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 12708 * circular reveal} animation take priority over Outline clipping, and 12709 * child Outline clipping takes priority over Outline clipping done by a 12710 * parent. 12711 * <p> 12712 * Note that this flag will only be respected if the View's Outline returns true from 12713 * {@link Outline#canClip()}. 12714 * 12715 * @see #setOutlineProvider(ViewOutlineProvider) 12716 * @see #getClipToOutline() 12717 */ 12718 public void setClipToOutline(boolean clipToOutline) { 12719 damageInParent(); 12720 if (getClipToOutline() != clipToOutline) { 12721 mRenderNode.setClipToOutline(clipToOutline); 12722 } 12723 } 12724 12725 // correspond to the enum values of View_outlineProvider 12726 private static final int PROVIDER_BACKGROUND = 0; 12727 private static final int PROVIDER_NONE = 1; 12728 private static final int PROVIDER_BOUNDS = 2; 12729 private static final int PROVIDER_PADDED_BOUNDS = 3; 12730 private void setOutlineProviderFromAttribute(int providerInt) { 12731 switch (providerInt) { 12732 case PROVIDER_BACKGROUND: 12733 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 12734 break; 12735 case PROVIDER_NONE: 12736 setOutlineProvider(null); 12737 break; 12738 case PROVIDER_BOUNDS: 12739 setOutlineProvider(ViewOutlineProvider.BOUNDS); 12740 break; 12741 case PROVIDER_PADDED_BOUNDS: 12742 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 12743 break; 12744 } 12745 } 12746 12747 /** 12748 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 12749 * the shape of the shadow it casts, and enables outline clipping. 12750 * <p> 12751 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 12752 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 12753 * outline provider with this method allows this behavior to be overridden. 12754 * <p> 12755 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 12756 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 12757 * <p> 12758 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 12759 * 12760 * @see #setClipToOutline(boolean) 12761 * @see #getClipToOutline() 12762 * @see #getOutlineProvider() 12763 */ 12764 public void setOutlineProvider(ViewOutlineProvider provider) { 12765 mOutlineProvider = provider; 12766 invalidateOutline(); 12767 } 12768 12769 /** 12770 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 12771 * that defines the shape of the shadow it casts, and enables outline clipping. 12772 * 12773 * @see #setOutlineProvider(ViewOutlineProvider) 12774 */ 12775 public ViewOutlineProvider getOutlineProvider() { 12776 return mOutlineProvider; 12777 } 12778 12779 /** 12780 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 12781 * 12782 * @see #setOutlineProvider(ViewOutlineProvider) 12783 */ 12784 public void invalidateOutline() { 12785 rebuildOutline(); 12786 12787 notifySubtreeAccessibilityStateChangedIfNeeded(); 12788 invalidateViewProperty(false, false); 12789 } 12790 12791 /** 12792 * Internal version of {@link #invalidateOutline()} which invalidates the 12793 * outline without invalidating the view itself. This is intended to be called from 12794 * within methods in the View class itself which are the result of the view being 12795 * invalidated already. For example, when we are drawing the background of a View, 12796 * we invalidate the outline in case it changed in the meantime, but we do not 12797 * need to invalidate the view because we're already drawing the background as part 12798 * of drawing the view in response to an earlier invalidation of the view. 12799 */ 12800 private void rebuildOutline() { 12801 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 12802 if (mAttachInfo == null) return; 12803 12804 if (mOutlineProvider == null) { 12805 // no provider, remove outline 12806 mRenderNode.setOutline(null); 12807 } else { 12808 final Outline outline = mAttachInfo.mTmpOutline; 12809 outline.setEmpty(); 12810 outline.setAlpha(1.0f); 12811 12812 mOutlineProvider.getOutline(this, outline); 12813 mRenderNode.setOutline(outline); 12814 } 12815 } 12816 12817 /** 12818 * HierarchyViewer only 12819 * 12820 * @hide 12821 */ 12822 @ViewDebug.ExportedProperty(category = "drawing") 12823 public boolean hasShadow() { 12824 return mRenderNode.hasShadow(); 12825 } 12826 12827 12828 /** @hide */ 12829 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 12830 mRenderNode.setRevealClip(shouldClip, x, y, radius); 12831 invalidateViewProperty(false, false); 12832 } 12833 12834 /** 12835 * Hit rectangle in parent's coordinates 12836 * 12837 * @param outRect The hit rectangle of the view. 12838 */ 12839 public void getHitRect(Rect outRect) { 12840 if (hasIdentityMatrix() || mAttachInfo == null) { 12841 outRect.set(mLeft, mTop, mRight, mBottom); 12842 } else { 12843 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 12844 tmpRect.set(0, 0, getWidth(), getHeight()); 12845 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 12846 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 12847 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 12848 } 12849 } 12850 12851 /** 12852 * Determines whether the given point, in local coordinates is inside the view. 12853 */ 12854 /*package*/ final boolean pointInView(float localX, float localY) { 12855 return pointInView(localX, localY, 0); 12856 } 12857 12858 /** 12859 * Utility method to determine whether the given point, in local coordinates, 12860 * is inside the view, where the area of the view is expanded by the slop factor. 12861 * This method is called while processing touch-move events to determine if the event 12862 * is still within the view. 12863 * 12864 * @hide 12865 */ 12866 public boolean pointInView(float localX, float localY, float slop) { 12867 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 12868 localY < ((mBottom - mTop) + slop); 12869 } 12870 12871 /** 12872 * When a view has focus and the user navigates away from it, the next view is searched for 12873 * starting from the rectangle filled in by this method. 12874 * 12875 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 12876 * of the view. However, if your view maintains some idea of internal selection, 12877 * such as a cursor, or a selected row or column, you should override this method and 12878 * fill in a more specific rectangle. 12879 * 12880 * @param r The rectangle to fill in, in this view's coordinates. 12881 */ 12882 public void getFocusedRect(Rect r) { 12883 getDrawingRect(r); 12884 } 12885 12886 /** 12887 * If some part of this view is not clipped by any of its parents, then 12888 * return that area in r in global (root) coordinates. To convert r to local 12889 * coordinates (without taking possible View rotations into account), offset 12890 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 12891 * If the view is completely clipped or translated out, return false. 12892 * 12893 * @param r If true is returned, r holds the global coordinates of the 12894 * visible portion of this view. 12895 * @param globalOffset If true is returned, globalOffset holds the dx,dy 12896 * between this view and its root. globalOffet may be null. 12897 * @return true if r is non-empty (i.e. part of the view is visible at the 12898 * root level. 12899 */ 12900 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 12901 int width = mRight - mLeft; 12902 int height = mBottom - mTop; 12903 if (width > 0 && height > 0) { 12904 r.set(0, 0, width, height); 12905 if (globalOffset != null) { 12906 globalOffset.set(-mScrollX, -mScrollY); 12907 } 12908 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 12909 } 12910 return false; 12911 } 12912 12913 public final boolean getGlobalVisibleRect(Rect r) { 12914 return getGlobalVisibleRect(r, null); 12915 } 12916 12917 public final boolean getLocalVisibleRect(Rect r) { 12918 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 12919 if (getGlobalVisibleRect(r, offset)) { 12920 r.offset(-offset.x, -offset.y); // make r local 12921 return true; 12922 } 12923 return false; 12924 } 12925 12926 /** 12927 * Offset this view's vertical location by the specified number of pixels. 12928 * 12929 * @param offset the number of pixels to offset the view by 12930 */ 12931 public void offsetTopAndBottom(int offset) { 12932 if (offset != 0) { 12933 final boolean matrixIsIdentity = hasIdentityMatrix(); 12934 if (matrixIsIdentity) { 12935 if (isHardwareAccelerated()) { 12936 invalidateViewProperty(false, false); 12937 } else { 12938 final ViewParent p = mParent; 12939 if (p != null && mAttachInfo != null) { 12940 final Rect r = mAttachInfo.mTmpInvalRect; 12941 int minTop; 12942 int maxBottom; 12943 int yLoc; 12944 if (offset < 0) { 12945 minTop = mTop + offset; 12946 maxBottom = mBottom; 12947 yLoc = offset; 12948 } else { 12949 minTop = mTop; 12950 maxBottom = mBottom + offset; 12951 yLoc = 0; 12952 } 12953 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 12954 p.invalidateChild(this, r); 12955 } 12956 } 12957 } else { 12958 invalidateViewProperty(false, false); 12959 } 12960 12961 mTop += offset; 12962 mBottom += offset; 12963 mRenderNode.offsetTopAndBottom(offset); 12964 if (isHardwareAccelerated()) { 12965 invalidateViewProperty(false, false); 12966 invalidateParentIfNeededAndWasQuickRejected(); 12967 } else { 12968 if (!matrixIsIdentity) { 12969 invalidateViewProperty(false, true); 12970 } 12971 invalidateParentIfNeeded(); 12972 } 12973 notifySubtreeAccessibilityStateChangedIfNeeded(); 12974 } 12975 } 12976 12977 /** 12978 * Offset this view's horizontal location by the specified amount of pixels. 12979 * 12980 * @param offset the number of pixels to offset the view by 12981 */ 12982 public void offsetLeftAndRight(int offset) { 12983 if (offset != 0) { 12984 final boolean matrixIsIdentity = hasIdentityMatrix(); 12985 if (matrixIsIdentity) { 12986 if (isHardwareAccelerated()) { 12987 invalidateViewProperty(false, false); 12988 } else { 12989 final ViewParent p = mParent; 12990 if (p != null && mAttachInfo != null) { 12991 final Rect r = mAttachInfo.mTmpInvalRect; 12992 int minLeft; 12993 int maxRight; 12994 if (offset < 0) { 12995 minLeft = mLeft + offset; 12996 maxRight = mRight; 12997 } else { 12998 minLeft = mLeft; 12999 maxRight = mRight + offset; 13000 } 13001 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 13002 p.invalidateChild(this, r); 13003 } 13004 } 13005 } else { 13006 invalidateViewProperty(false, false); 13007 } 13008 13009 mLeft += offset; 13010 mRight += offset; 13011 mRenderNode.offsetLeftAndRight(offset); 13012 if (isHardwareAccelerated()) { 13013 invalidateViewProperty(false, false); 13014 invalidateParentIfNeededAndWasQuickRejected(); 13015 } else { 13016 if (!matrixIsIdentity) { 13017 invalidateViewProperty(false, true); 13018 } 13019 invalidateParentIfNeeded(); 13020 } 13021 notifySubtreeAccessibilityStateChangedIfNeeded(); 13022 } 13023 } 13024 13025 /** 13026 * Get the LayoutParams associated with this view. All views should have 13027 * layout parameters. These supply parameters to the <i>parent</i> of this 13028 * view specifying how it should be arranged. There are many subclasses of 13029 * ViewGroup.LayoutParams, and these correspond to the different subclasses 13030 * of ViewGroup that are responsible for arranging their children. 13031 * 13032 * This method may return null if this View is not attached to a parent 13033 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 13034 * was not invoked successfully. When a View is attached to a parent 13035 * ViewGroup, this method must not return null. 13036 * 13037 * @return The LayoutParams associated with this view, or null if no 13038 * parameters have been set yet 13039 */ 13040 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 13041 public ViewGroup.LayoutParams getLayoutParams() { 13042 return mLayoutParams; 13043 } 13044 13045 /** 13046 * Set the layout parameters associated with this view. These supply 13047 * parameters to the <i>parent</i> of this view specifying how it should be 13048 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 13049 * correspond to the different subclasses of ViewGroup that are responsible 13050 * for arranging their children. 13051 * 13052 * @param params The layout parameters for this view, cannot be null 13053 */ 13054 public void setLayoutParams(ViewGroup.LayoutParams params) { 13055 if (params == null) { 13056 throw new NullPointerException("Layout parameters cannot be null"); 13057 } 13058 mLayoutParams = params; 13059 resolveLayoutParams(); 13060 if (mParent instanceof ViewGroup) { 13061 ((ViewGroup) mParent).onSetLayoutParams(this, params); 13062 } 13063 requestLayout(); 13064 } 13065 13066 /** 13067 * Resolve the layout parameters depending on the resolved layout direction 13068 * 13069 * @hide 13070 */ 13071 public void resolveLayoutParams() { 13072 if (mLayoutParams != null) { 13073 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 13074 } 13075 } 13076 13077 /** 13078 * Set the scrolled position of your view. This will cause a call to 13079 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13080 * invalidated. 13081 * @param x the x position to scroll to 13082 * @param y the y position to scroll to 13083 */ 13084 public void scrollTo(int x, int y) { 13085 if (mScrollX != x || mScrollY != y) { 13086 int oldX = mScrollX; 13087 int oldY = mScrollY; 13088 mScrollX = x; 13089 mScrollY = y; 13090 invalidateParentCaches(); 13091 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 13092 if (!awakenScrollBars()) { 13093 postInvalidateOnAnimation(); 13094 } 13095 } 13096 } 13097 13098 /** 13099 * Move the scrolled position of your view. This will cause a call to 13100 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13101 * invalidated. 13102 * @param x the amount of pixels to scroll by horizontally 13103 * @param y the amount of pixels to scroll by vertically 13104 */ 13105 public void scrollBy(int x, int y) { 13106 scrollTo(mScrollX + x, mScrollY + y); 13107 } 13108 13109 /** 13110 * <p>Trigger the scrollbars to draw. When invoked this method starts an 13111 * animation to fade the scrollbars out after a default delay. If a subclass 13112 * provides animated scrolling, the start delay should equal the duration 13113 * of the scrolling animation.</p> 13114 * 13115 * <p>The animation starts only if at least one of the scrollbars is 13116 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 13117 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13118 * this method returns true, and false otherwise. If the animation is 13119 * started, this method calls {@link #invalidate()}; in that case the 13120 * caller should not call {@link #invalidate()}.</p> 13121 * 13122 * <p>This method should be invoked every time a subclass directly updates 13123 * the scroll parameters.</p> 13124 * 13125 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 13126 * and {@link #scrollTo(int, int)}.</p> 13127 * 13128 * @return true if the animation is played, false otherwise 13129 * 13130 * @see #awakenScrollBars(int) 13131 * @see #scrollBy(int, int) 13132 * @see #scrollTo(int, int) 13133 * @see #isHorizontalScrollBarEnabled() 13134 * @see #isVerticalScrollBarEnabled() 13135 * @see #setHorizontalScrollBarEnabled(boolean) 13136 * @see #setVerticalScrollBarEnabled(boolean) 13137 */ 13138 protected boolean awakenScrollBars() { 13139 return mScrollCache != null && 13140 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 13141 } 13142 13143 /** 13144 * Trigger the scrollbars to draw. 13145 * This method differs from awakenScrollBars() only in its default duration. 13146 * initialAwakenScrollBars() will show the scroll bars for longer than 13147 * usual to give the user more of a chance to notice them. 13148 * 13149 * @return true if the animation is played, false otherwise. 13150 */ 13151 private boolean initialAwakenScrollBars() { 13152 return mScrollCache != null && 13153 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 13154 } 13155 13156 /** 13157 * <p> 13158 * Trigger the scrollbars to draw. When invoked this method starts an 13159 * animation to fade the scrollbars out after a fixed delay. If a subclass 13160 * provides animated scrolling, the start delay should equal the duration of 13161 * the scrolling animation. 13162 * </p> 13163 * 13164 * <p> 13165 * The animation starts only if at least one of the scrollbars is enabled, 13166 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13167 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13168 * this method returns true, and false otherwise. If the animation is 13169 * started, this method calls {@link #invalidate()}; in that case the caller 13170 * should not call {@link #invalidate()}. 13171 * </p> 13172 * 13173 * <p> 13174 * This method should be invoked every time a subclass directly updates the 13175 * scroll parameters. 13176 * </p> 13177 * 13178 * @param startDelay the delay, in milliseconds, after which the animation 13179 * should start; when the delay is 0, the animation starts 13180 * immediately 13181 * @return true if the animation is played, false otherwise 13182 * 13183 * @see #scrollBy(int, int) 13184 * @see #scrollTo(int, int) 13185 * @see #isHorizontalScrollBarEnabled() 13186 * @see #isVerticalScrollBarEnabled() 13187 * @see #setHorizontalScrollBarEnabled(boolean) 13188 * @see #setVerticalScrollBarEnabled(boolean) 13189 */ 13190 protected boolean awakenScrollBars(int startDelay) { 13191 return awakenScrollBars(startDelay, true); 13192 } 13193 13194 /** 13195 * <p> 13196 * Trigger the scrollbars to draw. When invoked this method starts an 13197 * animation to fade the scrollbars out after a fixed delay. If a subclass 13198 * provides animated scrolling, the start delay should equal the duration of 13199 * the scrolling animation. 13200 * </p> 13201 * 13202 * <p> 13203 * The animation starts only if at least one of the scrollbars is enabled, 13204 * as specified by {@link #isHorizontalScrollBarEnabled()} and 13205 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 13206 * this method returns true, and false otherwise. If the animation is 13207 * started, this method calls {@link #invalidate()} if the invalidate parameter 13208 * is set to true; in that case the caller 13209 * should not call {@link #invalidate()}. 13210 * </p> 13211 * 13212 * <p> 13213 * This method should be invoked every time a subclass directly updates the 13214 * scroll parameters. 13215 * </p> 13216 * 13217 * @param startDelay the delay, in milliseconds, after which the animation 13218 * should start; when the delay is 0, the animation starts 13219 * immediately 13220 * 13221 * @param invalidate Whether this method should call invalidate 13222 * 13223 * @return true if the animation is played, false otherwise 13224 * 13225 * @see #scrollBy(int, int) 13226 * @see #scrollTo(int, int) 13227 * @see #isHorizontalScrollBarEnabled() 13228 * @see #isVerticalScrollBarEnabled() 13229 * @see #setHorizontalScrollBarEnabled(boolean) 13230 * @see #setVerticalScrollBarEnabled(boolean) 13231 */ 13232 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 13233 final ScrollabilityCache scrollCache = mScrollCache; 13234 13235 if (scrollCache == null || !scrollCache.fadeScrollBars) { 13236 return false; 13237 } 13238 13239 if (scrollCache.scrollBar == null) { 13240 scrollCache.scrollBar = new ScrollBarDrawable(); 13241 scrollCache.scrollBar.setCallback(this); 13242 scrollCache.scrollBar.setState(getDrawableState()); 13243 } 13244 13245 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 13246 13247 if (invalidate) { 13248 // Invalidate to show the scrollbars 13249 postInvalidateOnAnimation(); 13250 } 13251 13252 if (scrollCache.state == ScrollabilityCache.OFF) { 13253 // FIXME: this is copied from WindowManagerService. 13254 // We should get this value from the system when it 13255 // is possible to do so. 13256 final int KEY_REPEAT_FIRST_DELAY = 750; 13257 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 13258 } 13259 13260 // Tell mScrollCache when we should start fading. This may 13261 // extend the fade start time if one was already scheduled 13262 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 13263 scrollCache.fadeStartTime = fadeStartTime; 13264 scrollCache.state = ScrollabilityCache.ON; 13265 13266 // Schedule our fader to run, unscheduling any old ones first 13267 if (mAttachInfo != null) { 13268 mAttachInfo.mHandler.removeCallbacks(scrollCache); 13269 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 13270 } 13271 13272 return true; 13273 } 13274 13275 return false; 13276 } 13277 13278 /** 13279 * Do not invalidate views which are not visible and which are not running an animation. They 13280 * will not get drawn and they should not set dirty flags as if they will be drawn 13281 */ 13282 private boolean skipInvalidate() { 13283 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 13284 (!(mParent instanceof ViewGroup) || 13285 !((ViewGroup) mParent).isViewTransitioning(this)); 13286 } 13287 13288 /** 13289 * Mark the area defined by dirty as needing to be drawn. If the view is 13290 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13291 * point in the future. 13292 * <p> 13293 * This must be called from a UI thread. To call from a non-UI thread, call 13294 * {@link #postInvalidate()}. 13295 * <p> 13296 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 13297 * {@code dirty}. 13298 * 13299 * @param dirty the rectangle representing the bounds of the dirty region 13300 */ 13301 public void invalidate(Rect dirty) { 13302 final int scrollX = mScrollX; 13303 final int scrollY = mScrollY; 13304 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 13305 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 13306 } 13307 13308 /** 13309 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 13310 * coordinates of the dirty rect are relative to the view. If the view is 13311 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 13312 * point in the future. 13313 * <p> 13314 * This must be called from a UI thread. To call from a non-UI thread, call 13315 * {@link #postInvalidate()}. 13316 * 13317 * @param l the left position of the dirty region 13318 * @param t the top position of the dirty region 13319 * @param r the right position of the dirty region 13320 * @param b the bottom position of the dirty region 13321 */ 13322 public void invalidate(int l, int t, int r, int b) { 13323 final int scrollX = mScrollX; 13324 final int scrollY = mScrollY; 13325 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 13326 } 13327 13328 /** 13329 * Invalidate the whole view. If the view is visible, 13330 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 13331 * the future. 13332 * <p> 13333 * This must be called from a UI thread. To call from a non-UI thread, call 13334 * {@link #postInvalidate()}. 13335 */ 13336 public void invalidate() { 13337 invalidate(true); 13338 } 13339 13340 /** 13341 * This is where the invalidate() work actually happens. A full invalidate() 13342 * causes the drawing cache to be invalidated, but this function can be 13343 * called with invalidateCache set to false to skip that invalidation step 13344 * for cases that do not need it (for example, a component that remains at 13345 * the same dimensions with the same content). 13346 * 13347 * @param invalidateCache Whether the drawing cache for this view should be 13348 * invalidated as well. This is usually true for a full 13349 * invalidate, but may be set to false if the View's contents or 13350 * dimensions have not changed. 13351 */ 13352 void invalidate(boolean invalidateCache) { 13353 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 13354 } 13355 13356 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 13357 boolean fullInvalidate) { 13358 if (mGhostView != null) { 13359 mGhostView.invalidate(true); 13360 return; 13361 } 13362 13363 if (skipInvalidate()) { 13364 return; 13365 } 13366 13367 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 13368 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 13369 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 13370 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 13371 if (fullInvalidate) { 13372 mLastIsOpaque = isOpaque(); 13373 mPrivateFlags &= ~PFLAG_DRAWN; 13374 } 13375 13376 mPrivateFlags |= PFLAG_DIRTY; 13377 13378 if (invalidateCache) { 13379 mPrivateFlags |= PFLAG_INVALIDATED; 13380 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 13381 } 13382 13383 // Propagate the damage rectangle to the parent view. 13384 final AttachInfo ai = mAttachInfo; 13385 final ViewParent p = mParent; 13386 if (p != null && ai != null && l < r && t < b) { 13387 final Rect damage = ai.mTmpInvalRect; 13388 damage.set(l, t, r, b); 13389 p.invalidateChild(this, damage); 13390 } 13391 13392 // Damage the entire projection receiver, if necessary. 13393 if (mBackground != null && mBackground.isProjected()) { 13394 final View receiver = getProjectionReceiver(); 13395 if (receiver != null) { 13396 receiver.damageInParent(); 13397 } 13398 } 13399 13400 // Damage the entire IsolatedZVolume receiving this view's shadow. 13401 if (isHardwareAccelerated() && getZ() != 0) { 13402 damageShadowReceiver(); 13403 } 13404 } 13405 } 13406 13407 /** 13408 * @return this view's projection receiver, or {@code null} if none exists 13409 */ 13410 private View getProjectionReceiver() { 13411 ViewParent p = getParent(); 13412 while (p != null && p instanceof View) { 13413 final View v = (View) p; 13414 if (v.isProjectionReceiver()) { 13415 return v; 13416 } 13417 p = p.getParent(); 13418 } 13419 13420 return null; 13421 } 13422 13423 /** 13424 * @return whether the view is a projection receiver 13425 */ 13426 private boolean isProjectionReceiver() { 13427 return mBackground != null; 13428 } 13429 13430 /** 13431 * Damage area of the screen that can be covered by this View's shadow. 13432 * 13433 * This method will guarantee that any changes to shadows cast by a View 13434 * are damaged on the screen for future redraw. 13435 */ 13436 private void damageShadowReceiver() { 13437 final AttachInfo ai = mAttachInfo; 13438 if (ai != null) { 13439 ViewParent p = getParent(); 13440 if (p != null && p instanceof ViewGroup) { 13441 final ViewGroup vg = (ViewGroup) p; 13442 vg.damageInParent(); 13443 } 13444 } 13445 } 13446 13447 /** 13448 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 13449 * set any flags or handle all of the cases handled by the default invalidation methods. 13450 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 13451 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 13452 * walk up the hierarchy, transforming the dirty rect as necessary. 13453 * 13454 * The method also handles normal invalidation logic if display list properties are not 13455 * being used in this view. The invalidateParent and forceRedraw flags are used by that 13456 * backup approach, to handle these cases used in the various property-setting methods. 13457 * 13458 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 13459 * are not being used in this view 13460 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 13461 * list properties are not being used in this view 13462 */ 13463 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 13464 if (!isHardwareAccelerated() 13465 || !mRenderNode.isValid() 13466 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 13467 if (invalidateParent) { 13468 invalidateParentCaches(); 13469 } 13470 if (forceRedraw) { 13471 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13472 } 13473 invalidate(false); 13474 } else { 13475 damageInParent(); 13476 } 13477 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 13478 damageShadowReceiver(); 13479 } 13480 } 13481 13482 /** 13483 * Tells the parent view to damage this view's bounds. 13484 * 13485 * @hide 13486 */ 13487 protected void damageInParent() { 13488 final AttachInfo ai = mAttachInfo; 13489 final ViewParent p = mParent; 13490 if (p != null && ai != null) { 13491 final Rect r = ai.mTmpInvalRect; 13492 r.set(0, 0, mRight - mLeft, mBottom - mTop); 13493 if (mParent instanceof ViewGroup) { 13494 ((ViewGroup) mParent).damageChild(this, r); 13495 } else { 13496 mParent.invalidateChild(this, r); 13497 } 13498 } 13499 } 13500 13501 /** 13502 * Utility method to transform a given Rect by the current matrix of this view. 13503 */ 13504 void transformRect(final Rect rect) { 13505 if (!getMatrix().isIdentity()) { 13506 RectF boundingRect = mAttachInfo.mTmpTransformRect; 13507 boundingRect.set(rect); 13508 getMatrix().mapRect(boundingRect); 13509 rect.set((int) Math.floor(boundingRect.left), 13510 (int) Math.floor(boundingRect.top), 13511 (int) Math.ceil(boundingRect.right), 13512 (int) Math.ceil(boundingRect.bottom)); 13513 } 13514 } 13515 13516 /** 13517 * Used to indicate that the parent of this view should clear its caches. This functionality 13518 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13519 * which is necessary when various parent-managed properties of the view change, such as 13520 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 13521 * clears the parent caches and does not causes an invalidate event. 13522 * 13523 * @hide 13524 */ 13525 protected void invalidateParentCaches() { 13526 if (mParent instanceof View) { 13527 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 13528 } 13529 } 13530 13531 /** 13532 * Used to indicate that the parent of this view should be invalidated. This functionality 13533 * is used to force the parent to rebuild its display list (when hardware-accelerated), 13534 * which is necessary when various parent-managed properties of the view change, such as 13535 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 13536 * an invalidation event to the parent. 13537 * 13538 * @hide 13539 */ 13540 protected void invalidateParentIfNeeded() { 13541 if (isHardwareAccelerated() && mParent instanceof View) { 13542 ((View) mParent).invalidate(true); 13543 } 13544 } 13545 13546 /** 13547 * @hide 13548 */ 13549 protected void invalidateParentIfNeededAndWasQuickRejected() { 13550 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 13551 // View was rejected last time it was drawn by its parent; this may have changed 13552 invalidateParentIfNeeded(); 13553 } 13554 } 13555 13556 /** 13557 * Indicates whether this View is opaque. An opaque View guarantees that it will 13558 * draw all the pixels overlapping its bounds using a fully opaque color. 13559 * 13560 * Subclasses of View should override this method whenever possible to indicate 13561 * whether an instance is opaque. Opaque Views are treated in a special way by 13562 * the View hierarchy, possibly allowing it to perform optimizations during 13563 * invalidate/draw passes. 13564 * 13565 * @return True if this View is guaranteed to be fully opaque, false otherwise. 13566 */ 13567 @ViewDebug.ExportedProperty(category = "drawing") 13568 public boolean isOpaque() { 13569 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 13570 getFinalAlpha() >= 1.0f; 13571 } 13572 13573 /** 13574 * @hide 13575 */ 13576 protected void computeOpaqueFlags() { 13577 // Opaque if: 13578 // - Has a background 13579 // - Background is opaque 13580 // - Doesn't have scrollbars or scrollbars overlay 13581 13582 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 13583 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 13584 } else { 13585 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 13586 } 13587 13588 final int flags = mViewFlags; 13589 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 13590 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 13591 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 13592 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 13593 } else { 13594 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 13595 } 13596 } 13597 13598 /** 13599 * @hide 13600 */ 13601 protected boolean hasOpaqueScrollbars() { 13602 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 13603 } 13604 13605 /** 13606 * @return A handler associated with the thread running the View. This 13607 * handler can be used to pump events in the UI events queue. 13608 */ 13609 public Handler getHandler() { 13610 final AttachInfo attachInfo = mAttachInfo; 13611 if (attachInfo != null) { 13612 return attachInfo.mHandler; 13613 } 13614 return null; 13615 } 13616 13617 /** 13618 * Returns the queue of runnable for this view. 13619 * 13620 * @return the queue of runnables for this view 13621 */ 13622 private HandlerActionQueue getRunQueue() { 13623 if (mRunQueue == null) { 13624 mRunQueue = new HandlerActionQueue(); 13625 } 13626 return mRunQueue; 13627 } 13628 13629 /** 13630 * Gets the view root associated with the View. 13631 * @return The view root, or null if none. 13632 * @hide 13633 */ 13634 public ViewRootImpl getViewRootImpl() { 13635 if (mAttachInfo != null) { 13636 return mAttachInfo.mViewRootImpl; 13637 } 13638 return null; 13639 } 13640 13641 /** 13642 * @hide 13643 */ 13644 public ThreadedRenderer getHardwareRenderer() { 13645 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 13646 } 13647 13648 /** 13649 * <p>Causes the Runnable to be added to the message queue. 13650 * The runnable will be run on the user interface thread.</p> 13651 * 13652 * @param action The Runnable that will be executed. 13653 * 13654 * @return Returns true if the Runnable was successfully placed in to the 13655 * message queue. Returns false on failure, usually because the 13656 * looper processing the message queue is exiting. 13657 * 13658 * @see #postDelayed 13659 * @see #removeCallbacks 13660 */ 13661 public boolean post(Runnable action) { 13662 final AttachInfo attachInfo = mAttachInfo; 13663 if (attachInfo != null) { 13664 return attachInfo.mHandler.post(action); 13665 } 13666 13667 // Postpone the runnable until we know on which thread it needs to run. 13668 // Assume that the runnable will be successfully placed after attach. 13669 getRunQueue().post(action); 13670 return true; 13671 } 13672 13673 /** 13674 * <p>Causes the Runnable to be added to the message queue, to be run 13675 * after the specified amount of time elapses. 13676 * The runnable will be run on the user interface thread.</p> 13677 * 13678 * @param action The Runnable that will be executed. 13679 * @param delayMillis The delay (in milliseconds) until the Runnable 13680 * will be executed. 13681 * 13682 * @return true if the Runnable was successfully placed in to the 13683 * message queue. Returns false on failure, usually because the 13684 * looper processing the message queue is exiting. Note that a 13685 * result of true does not mean the Runnable will be processed -- 13686 * if the looper is quit before the delivery time of the message 13687 * occurs then the message will be dropped. 13688 * 13689 * @see #post 13690 * @see #removeCallbacks 13691 */ 13692 public boolean postDelayed(Runnable action, long delayMillis) { 13693 final AttachInfo attachInfo = mAttachInfo; 13694 if (attachInfo != null) { 13695 return attachInfo.mHandler.postDelayed(action, delayMillis); 13696 } 13697 13698 // Postpone the runnable until we know on which thread it needs to run. 13699 // Assume that the runnable will be successfully placed after attach. 13700 getRunQueue().postDelayed(action, delayMillis); 13701 return true; 13702 } 13703 13704 /** 13705 * <p>Causes the Runnable to execute on the next animation time step. 13706 * The runnable will be run on the user interface thread.</p> 13707 * 13708 * @param action The Runnable that will be executed. 13709 * 13710 * @see #postOnAnimationDelayed 13711 * @see #removeCallbacks 13712 */ 13713 public void postOnAnimation(Runnable action) { 13714 final AttachInfo attachInfo = mAttachInfo; 13715 if (attachInfo != null) { 13716 attachInfo.mViewRootImpl.mChoreographer.postCallback( 13717 Choreographer.CALLBACK_ANIMATION, action, null); 13718 } else { 13719 // Postpone the runnable until we know 13720 // on which thread it needs to run. 13721 getRunQueue().post(action); 13722 } 13723 } 13724 13725 /** 13726 * <p>Causes the Runnable to execute on the next animation time step, 13727 * after the specified amount of time elapses. 13728 * The runnable will be run on the user interface thread.</p> 13729 * 13730 * @param action The Runnable that will be executed. 13731 * @param delayMillis The delay (in milliseconds) until the Runnable 13732 * will be executed. 13733 * 13734 * @see #postOnAnimation 13735 * @see #removeCallbacks 13736 */ 13737 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 13738 final AttachInfo attachInfo = mAttachInfo; 13739 if (attachInfo != null) { 13740 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 13741 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 13742 } else { 13743 // Postpone the runnable until we know 13744 // on which thread it needs to run. 13745 getRunQueue().postDelayed(action, delayMillis); 13746 } 13747 } 13748 13749 /** 13750 * <p>Removes the specified Runnable from the message queue.</p> 13751 * 13752 * @param action The Runnable to remove from the message handling queue 13753 * 13754 * @return true if this view could ask the Handler to remove the Runnable, 13755 * false otherwise. When the returned value is true, the Runnable 13756 * may or may not have been actually removed from the message queue 13757 * (for instance, if the Runnable was not in the queue already.) 13758 * 13759 * @see #post 13760 * @see #postDelayed 13761 * @see #postOnAnimation 13762 * @see #postOnAnimationDelayed 13763 */ 13764 public boolean removeCallbacks(Runnable action) { 13765 if (action != null) { 13766 final AttachInfo attachInfo = mAttachInfo; 13767 if (attachInfo != null) { 13768 attachInfo.mHandler.removeCallbacks(action); 13769 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 13770 Choreographer.CALLBACK_ANIMATION, action, null); 13771 } 13772 getRunQueue().removeCallbacks(action); 13773 } 13774 return true; 13775 } 13776 13777 /** 13778 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 13779 * Use this to invalidate the View from a non-UI thread.</p> 13780 * 13781 * <p>This method can be invoked from outside of the UI thread 13782 * only when this View is attached to a window.</p> 13783 * 13784 * @see #invalidate() 13785 * @see #postInvalidateDelayed(long) 13786 */ 13787 public void postInvalidate() { 13788 postInvalidateDelayed(0); 13789 } 13790 13791 /** 13792 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13793 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 13794 * 13795 * <p>This method can be invoked from outside of the UI thread 13796 * only when this View is attached to a window.</p> 13797 * 13798 * @param left The left coordinate of the rectangle to invalidate. 13799 * @param top The top coordinate of the rectangle to invalidate. 13800 * @param right The right coordinate of the rectangle to invalidate. 13801 * @param bottom The bottom coordinate of the rectangle to invalidate. 13802 * 13803 * @see #invalidate(int, int, int, int) 13804 * @see #invalidate(Rect) 13805 * @see #postInvalidateDelayed(long, int, int, int, int) 13806 */ 13807 public void postInvalidate(int left, int top, int right, int bottom) { 13808 postInvalidateDelayed(0, left, top, right, bottom); 13809 } 13810 13811 /** 13812 * <p>Cause an invalidate to happen on a subsequent cycle through the event 13813 * loop. Waits for the specified amount of time.</p> 13814 * 13815 * <p>This method can be invoked from outside of the UI thread 13816 * only when this View is attached to a window.</p> 13817 * 13818 * @param delayMilliseconds the duration in milliseconds to delay the 13819 * invalidation by 13820 * 13821 * @see #invalidate() 13822 * @see #postInvalidate() 13823 */ 13824 public void postInvalidateDelayed(long delayMilliseconds) { 13825 // We try only with the AttachInfo because there's no point in invalidating 13826 // if we are not attached to our window 13827 final AttachInfo attachInfo = mAttachInfo; 13828 if (attachInfo != null) { 13829 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 13830 } 13831 } 13832 13833 /** 13834 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 13835 * through the event loop. Waits for the specified amount of time.</p> 13836 * 13837 * <p>This method can be invoked from outside of the UI thread 13838 * only when this View is attached to a window.</p> 13839 * 13840 * @param delayMilliseconds the duration in milliseconds to delay the 13841 * invalidation by 13842 * @param left The left coordinate of the rectangle to invalidate. 13843 * @param top The top coordinate of the rectangle to invalidate. 13844 * @param right The right coordinate of the rectangle to invalidate. 13845 * @param bottom The bottom coordinate of the rectangle to invalidate. 13846 * 13847 * @see #invalidate(int, int, int, int) 13848 * @see #invalidate(Rect) 13849 * @see #postInvalidate(int, int, int, int) 13850 */ 13851 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 13852 int right, int bottom) { 13853 13854 // We try only with the AttachInfo because there's no point in invalidating 13855 // if we are not attached to our window 13856 final AttachInfo attachInfo = mAttachInfo; 13857 if (attachInfo != null) { 13858 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13859 info.target = this; 13860 info.left = left; 13861 info.top = top; 13862 info.right = right; 13863 info.bottom = bottom; 13864 13865 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 13866 } 13867 } 13868 13869 /** 13870 * <p>Cause an invalidate to happen on the next animation time step, typically the 13871 * next display frame.</p> 13872 * 13873 * <p>This method can be invoked from outside of the UI thread 13874 * only when this View is attached to a window.</p> 13875 * 13876 * @see #invalidate() 13877 */ 13878 public void postInvalidateOnAnimation() { 13879 // We try only with the AttachInfo because there's no point in invalidating 13880 // if we are not attached to our window 13881 final AttachInfo attachInfo = mAttachInfo; 13882 if (attachInfo != null) { 13883 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 13884 } 13885 } 13886 13887 /** 13888 * <p>Cause an invalidate of the specified area to happen on the next animation 13889 * time step, typically the next display frame.</p> 13890 * 13891 * <p>This method can be invoked from outside of the UI thread 13892 * only when this View is attached to a window.</p> 13893 * 13894 * @param left The left coordinate of the rectangle to invalidate. 13895 * @param top The top coordinate of the rectangle to invalidate. 13896 * @param right The right coordinate of the rectangle to invalidate. 13897 * @param bottom The bottom coordinate of the rectangle to invalidate. 13898 * 13899 * @see #invalidate(int, int, int, int) 13900 * @see #invalidate(Rect) 13901 */ 13902 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 13903 // We try only with the AttachInfo because there's no point in invalidating 13904 // if we are not attached to our window 13905 final AttachInfo attachInfo = mAttachInfo; 13906 if (attachInfo != null) { 13907 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 13908 info.target = this; 13909 info.left = left; 13910 info.top = top; 13911 info.right = right; 13912 info.bottom = bottom; 13913 13914 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 13915 } 13916 } 13917 13918 /** 13919 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 13920 * This event is sent at most once every 13921 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 13922 */ 13923 private void postSendViewScrolledAccessibilityEventCallback() { 13924 if (mSendViewScrolledAccessibilityEvent == null) { 13925 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 13926 } 13927 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 13928 mSendViewScrolledAccessibilityEvent.mIsPending = true; 13929 postDelayed(mSendViewScrolledAccessibilityEvent, 13930 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 13931 } 13932 } 13933 13934 /** 13935 * Called by a parent to request that a child update its values for mScrollX 13936 * and mScrollY if necessary. This will typically be done if the child is 13937 * animating a scroll using a {@link android.widget.Scroller Scroller} 13938 * object. 13939 */ 13940 public void computeScroll() { 13941 } 13942 13943 /** 13944 * <p>Indicate whether the horizontal edges are faded when the view is 13945 * scrolled horizontally.</p> 13946 * 13947 * @return true if the horizontal edges should are faded on scroll, false 13948 * otherwise 13949 * 13950 * @see #setHorizontalFadingEdgeEnabled(boolean) 13951 * 13952 * @attr ref android.R.styleable#View_requiresFadingEdge 13953 */ 13954 public boolean isHorizontalFadingEdgeEnabled() { 13955 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 13956 } 13957 13958 /** 13959 * <p>Define whether the horizontal edges should be faded when this view 13960 * is scrolled horizontally.</p> 13961 * 13962 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 13963 * be faded when the view is scrolled 13964 * horizontally 13965 * 13966 * @see #isHorizontalFadingEdgeEnabled() 13967 * 13968 * @attr ref android.R.styleable#View_requiresFadingEdge 13969 */ 13970 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 13971 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 13972 if (horizontalFadingEdgeEnabled) { 13973 initScrollCache(); 13974 } 13975 13976 mViewFlags ^= FADING_EDGE_HORIZONTAL; 13977 } 13978 } 13979 13980 /** 13981 * <p>Indicate whether the vertical edges are faded when the view is 13982 * scrolled horizontally.</p> 13983 * 13984 * @return true if the vertical edges should are faded on scroll, false 13985 * otherwise 13986 * 13987 * @see #setVerticalFadingEdgeEnabled(boolean) 13988 * 13989 * @attr ref android.R.styleable#View_requiresFadingEdge 13990 */ 13991 public boolean isVerticalFadingEdgeEnabled() { 13992 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 13993 } 13994 13995 /** 13996 * <p>Define whether the vertical edges should be faded when this view 13997 * is scrolled vertically.</p> 13998 * 13999 * @param verticalFadingEdgeEnabled true if the vertical edges should 14000 * be faded when the view is scrolled 14001 * vertically 14002 * 14003 * @see #isVerticalFadingEdgeEnabled() 14004 * 14005 * @attr ref android.R.styleable#View_requiresFadingEdge 14006 */ 14007 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 14008 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 14009 if (verticalFadingEdgeEnabled) { 14010 initScrollCache(); 14011 } 14012 14013 mViewFlags ^= FADING_EDGE_VERTICAL; 14014 } 14015 } 14016 14017 /** 14018 * Returns the strength, or intensity, of the top faded edge. The strength is 14019 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14020 * returns 0.0 or 1.0 but no value in between. 14021 * 14022 * Subclasses should override this method to provide a smoother fade transition 14023 * when scrolling occurs. 14024 * 14025 * @return the intensity of the top fade as a float between 0.0f and 1.0f 14026 */ 14027 protected float getTopFadingEdgeStrength() { 14028 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 14029 } 14030 14031 /** 14032 * Returns the strength, or intensity, of the bottom faded edge. The strength is 14033 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14034 * returns 0.0 or 1.0 but no value in between. 14035 * 14036 * Subclasses should override this method to provide a smoother fade transition 14037 * when scrolling occurs. 14038 * 14039 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 14040 */ 14041 protected float getBottomFadingEdgeStrength() { 14042 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 14043 computeVerticalScrollRange() ? 1.0f : 0.0f; 14044 } 14045 14046 /** 14047 * Returns the strength, or intensity, of the left faded edge. The strength is 14048 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14049 * returns 0.0 or 1.0 but no value in between. 14050 * 14051 * Subclasses should override this method to provide a smoother fade transition 14052 * when scrolling occurs. 14053 * 14054 * @return the intensity of the left fade as a float between 0.0f and 1.0f 14055 */ 14056 protected float getLeftFadingEdgeStrength() { 14057 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 14058 } 14059 14060 /** 14061 * Returns the strength, or intensity, of the right faded edge. The strength is 14062 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 14063 * returns 0.0 or 1.0 but no value in between. 14064 * 14065 * Subclasses should override this method to provide a smoother fade transition 14066 * when scrolling occurs. 14067 * 14068 * @return the intensity of the right fade as a float between 0.0f and 1.0f 14069 */ 14070 protected float getRightFadingEdgeStrength() { 14071 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 14072 computeHorizontalScrollRange() ? 1.0f : 0.0f; 14073 } 14074 14075 /** 14076 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 14077 * scrollbar is not drawn by default.</p> 14078 * 14079 * @return true if the horizontal scrollbar should be painted, false 14080 * otherwise 14081 * 14082 * @see #setHorizontalScrollBarEnabled(boolean) 14083 */ 14084 public boolean isHorizontalScrollBarEnabled() { 14085 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 14086 } 14087 14088 /** 14089 * <p>Define whether the horizontal scrollbar should be drawn or not. The 14090 * scrollbar is not drawn by default.</p> 14091 * 14092 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 14093 * be painted 14094 * 14095 * @see #isHorizontalScrollBarEnabled() 14096 */ 14097 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 14098 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 14099 mViewFlags ^= SCROLLBARS_HORIZONTAL; 14100 computeOpaqueFlags(); 14101 resolvePadding(); 14102 } 14103 } 14104 14105 /** 14106 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 14107 * scrollbar is not drawn by default.</p> 14108 * 14109 * @return true if the vertical scrollbar should be painted, false 14110 * otherwise 14111 * 14112 * @see #setVerticalScrollBarEnabled(boolean) 14113 */ 14114 public boolean isVerticalScrollBarEnabled() { 14115 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 14116 } 14117 14118 /** 14119 * <p>Define whether the vertical scrollbar should be drawn or not. The 14120 * scrollbar is not drawn by default.</p> 14121 * 14122 * @param verticalScrollBarEnabled true if the vertical scrollbar should 14123 * be painted 14124 * 14125 * @see #isVerticalScrollBarEnabled() 14126 */ 14127 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 14128 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 14129 mViewFlags ^= SCROLLBARS_VERTICAL; 14130 computeOpaqueFlags(); 14131 resolvePadding(); 14132 } 14133 } 14134 14135 /** 14136 * @hide 14137 */ 14138 protected void recomputePadding() { 14139 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 14140 } 14141 14142 /** 14143 * Define whether scrollbars will fade when the view is not scrolling. 14144 * 14145 * @param fadeScrollbars whether to enable fading 14146 * 14147 * @attr ref android.R.styleable#View_fadeScrollbars 14148 */ 14149 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 14150 initScrollCache(); 14151 final ScrollabilityCache scrollabilityCache = mScrollCache; 14152 scrollabilityCache.fadeScrollBars = fadeScrollbars; 14153 if (fadeScrollbars) { 14154 scrollabilityCache.state = ScrollabilityCache.OFF; 14155 } else { 14156 scrollabilityCache.state = ScrollabilityCache.ON; 14157 } 14158 } 14159 14160 /** 14161 * 14162 * Returns true if scrollbars will fade when this view is not scrolling 14163 * 14164 * @return true if scrollbar fading is enabled 14165 * 14166 * @attr ref android.R.styleable#View_fadeScrollbars 14167 */ 14168 public boolean isScrollbarFadingEnabled() { 14169 return mScrollCache != null && mScrollCache.fadeScrollBars; 14170 } 14171 14172 /** 14173 * 14174 * Returns the delay before scrollbars fade. 14175 * 14176 * @return the delay before scrollbars fade 14177 * 14178 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14179 */ 14180 public int getScrollBarDefaultDelayBeforeFade() { 14181 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 14182 mScrollCache.scrollBarDefaultDelayBeforeFade; 14183 } 14184 14185 /** 14186 * Define the delay before scrollbars fade. 14187 * 14188 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 14189 * 14190 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 14191 */ 14192 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 14193 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 14194 } 14195 14196 /** 14197 * 14198 * Returns the scrollbar fade duration. 14199 * 14200 * @return the scrollbar fade duration 14201 * 14202 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14203 */ 14204 public int getScrollBarFadeDuration() { 14205 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 14206 mScrollCache.scrollBarFadeDuration; 14207 } 14208 14209 /** 14210 * Define the scrollbar fade duration. 14211 * 14212 * @param scrollBarFadeDuration - the scrollbar fade duration 14213 * 14214 * @attr ref android.R.styleable#View_scrollbarFadeDuration 14215 */ 14216 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 14217 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 14218 } 14219 14220 /** 14221 * 14222 * Returns the scrollbar size. 14223 * 14224 * @return the scrollbar size 14225 * 14226 * @attr ref android.R.styleable#View_scrollbarSize 14227 */ 14228 public int getScrollBarSize() { 14229 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 14230 mScrollCache.scrollBarSize; 14231 } 14232 14233 /** 14234 * Define the scrollbar size. 14235 * 14236 * @param scrollBarSize - the scrollbar size 14237 * 14238 * @attr ref android.R.styleable#View_scrollbarSize 14239 */ 14240 public void setScrollBarSize(int scrollBarSize) { 14241 getScrollCache().scrollBarSize = scrollBarSize; 14242 } 14243 14244 /** 14245 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 14246 * inset. When inset, they add to the padding of the view. And the scrollbars 14247 * can be drawn inside the padding area or on the edge of the view. For example, 14248 * if a view has a background drawable and you want to draw the scrollbars 14249 * inside the padding specified by the drawable, you can use 14250 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 14251 * appear at the edge of the view, ignoring the padding, then you can use 14252 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 14253 * @param style the style of the scrollbars. Should be one of 14254 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 14255 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 14256 * @see #SCROLLBARS_INSIDE_OVERLAY 14257 * @see #SCROLLBARS_INSIDE_INSET 14258 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14259 * @see #SCROLLBARS_OUTSIDE_INSET 14260 * 14261 * @attr ref android.R.styleable#View_scrollbarStyle 14262 */ 14263 public void setScrollBarStyle(@ScrollBarStyle int style) { 14264 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 14265 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 14266 computeOpaqueFlags(); 14267 resolvePadding(); 14268 } 14269 } 14270 14271 /** 14272 * <p>Returns the current scrollbar style.</p> 14273 * @return the current scrollbar style 14274 * @see #SCROLLBARS_INSIDE_OVERLAY 14275 * @see #SCROLLBARS_INSIDE_INSET 14276 * @see #SCROLLBARS_OUTSIDE_OVERLAY 14277 * @see #SCROLLBARS_OUTSIDE_INSET 14278 * 14279 * @attr ref android.R.styleable#View_scrollbarStyle 14280 */ 14281 @ViewDebug.ExportedProperty(mapping = { 14282 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 14283 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 14284 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 14285 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 14286 }) 14287 @ScrollBarStyle 14288 public int getScrollBarStyle() { 14289 return mViewFlags & SCROLLBARS_STYLE_MASK; 14290 } 14291 14292 /** 14293 * <p>Compute the horizontal range that the horizontal scrollbar 14294 * represents.</p> 14295 * 14296 * <p>The range is expressed in arbitrary units that must be the same as the 14297 * units used by {@link #computeHorizontalScrollExtent()} and 14298 * {@link #computeHorizontalScrollOffset()}.</p> 14299 * 14300 * <p>The default range is the drawing width of this view.</p> 14301 * 14302 * @return the total horizontal range represented by the horizontal 14303 * scrollbar 14304 * 14305 * @see #computeHorizontalScrollExtent() 14306 * @see #computeHorizontalScrollOffset() 14307 * @see android.widget.ScrollBarDrawable 14308 */ 14309 protected int computeHorizontalScrollRange() { 14310 return getWidth(); 14311 } 14312 14313 /** 14314 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 14315 * within the horizontal range. This value is used to compute the position 14316 * of the thumb within the scrollbar's track.</p> 14317 * 14318 * <p>The range is expressed in arbitrary units that must be the same as the 14319 * units used by {@link #computeHorizontalScrollRange()} and 14320 * {@link #computeHorizontalScrollExtent()}.</p> 14321 * 14322 * <p>The default offset is the scroll offset of this view.</p> 14323 * 14324 * @return the horizontal offset of the scrollbar's thumb 14325 * 14326 * @see #computeHorizontalScrollRange() 14327 * @see #computeHorizontalScrollExtent() 14328 * @see android.widget.ScrollBarDrawable 14329 */ 14330 protected int computeHorizontalScrollOffset() { 14331 return mScrollX; 14332 } 14333 14334 /** 14335 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 14336 * within the horizontal range. This value is used to compute the length 14337 * of the thumb within the scrollbar's track.</p> 14338 * 14339 * <p>The range is expressed in arbitrary units that must be the same as the 14340 * units used by {@link #computeHorizontalScrollRange()} and 14341 * {@link #computeHorizontalScrollOffset()}.</p> 14342 * 14343 * <p>The default extent is the drawing width of this view.</p> 14344 * 14345 * @return the horizontal extent of the scrollbar's thumb 14346 * 14347 * @see #computeHorizontalScrollRange() 14348 * @see #computeHorizontalScrollOffset() 14349 * @see android.widget.ScrollBarDrawable 14350 */ 14351 protected int computeHorizontalScrollExtent() { 14352 return getWidth(); 14353 } 14354 14355 /** 14356 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 14357 * 14358 * <p>The range is expressed in arbitrary units that must be the same as the 14359 * units used by {@link #computeVerticalScrollExtent()} and 14360 * {@link #computeVerticalScrollOffset()}.</p> 14361 * 14362 * @return the total vertical range represented by the vertical scrollbar 14363 * 14364 * <p>The default range is the drawing height of this view.</p> 14365 * 14366 * @see #computeVerticalScrollExtent() 14367 * @see #computeVerticalScrollOffset() 14368 * @see android.widget.ScrollBarDrawable 14369 */ 14370 protected int computeVerticalScrollRange() { 14371 return getHeight(); 14372 } 14373 14374 /** 14375 * <p>Compute the vertical offset of the vertical scrollbar's thumb 14376 * within the horizontal range. This value is used to compute the position 14377 * of the thumb within the scrollbar's track.</p> 14378 * 14379 * <p>The range is expressed in arbitrary units that must be the same as the 14380 * units used by {@link #computeVerticalScrollRange()} and 14381 * {@link #computeVerticalScrollExtent()}.</p> 14382 * 14383 * <p>The default offset is the scroll offset of this view.</p> 14384 * 14385 * @return the vertical offset of the scrollbar's thumb 14386 * 14387 * @see #computeVerticalScrollRange() 14388 * @see #computeVerticalScrollExtent() 14389 * @see android.widget.ScrollBarDrawable 14390 */ 14391 protected int computeVerticalScrollOffset() { 14392 return mScrollY; 14393 } 14394 14395 /** 14396 * <p>Compute the vertical extent of the vertical scrollbar's thumb 14397 * within the vertical range. This value is used to compute the length 14398 * of the thumb within the scrollbar's track.</p> 14399 * 14400 * <p>The range is expressed in arbitrary units that must be the same as the 14401 * units used by {@link #computeVerticalScrollRange()} and 14402 * {@link #computeVerticalScrollOffset()}.</p> 14403 * 14404 * <p>The default extent is the drawing height of this view.</p> 14405 * 14406 * @return the vertical extent of the scrollbar's thumb 14407 * 14408 * @see #computeVerticalScrollRange() 14409 * @see #computeVerticalScrollOffset() 14410 * @see android.widget.ScrollBarDrawable 14411 */ 14412 protected int computeVerticalScrollExtent() { 14413 return getHeight(); 14414 } 14415 14416 /** 14417 * Check if this view can be scrolled horizontally in a certain direction. 14418 * 14419 * @param direction Negative to check scrolling left, positive to check scrolling right. 14420 * @return true if this view can be scrolled in the specified direction, false otherwise. 14421 */ 14422 public boolean canScrollHorizontally(int direction) { 14423 final int offset = computeHorizontalScrollOffset(); 14424 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 14425 if (range == 0) return false; 14426 if (direction < 0) { 14427 return offset > 0; 14428 } else { 14429 return offset < range - 1; 14430 } 14431 } 14432 14433 /** 14434 * Check if this view can be scrolled vertically in a certain direction. 14435 * 14436 * @param direction Negative to check scrolling up, positive to check scrolling down. 14437 * @return true if this view can be scrolled in the specified direction, false otherwise. 14438 */ 14439 public boolean canScrollVertically(int direction) { 14440 final int offset = computeVerticalScrollOffset(); 14441 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 14442 if (range == 0) return false; 14443 if (direction < 0) { 14444 return offset > 0; 14445 } else { 14446 return offset < range - 1; 14447 } 14448 } 14449 14450 void getScrollIndicatorBounds(@NonNull Rect out) { 14451 out.left = mScrollX; 14452 out.right = mScrollX + mRight - mLeft; 14453 out.top = mScrollY; 14454 out.bottom = mScrollY + mBottom - mTop; 14455 } 14456 14457 private void onDrawScrollIndicators(Canvas c) { 14458 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 14459 // No scroll indicators enabled. 14460 return; 14461 } 14462 14463 final Drawable dr = mScrollIndicatorDrawable; 14464 if (dr == null) { 14465 // Scroll indicators aren't supported here. 14466 return; 14467 } 14468 14469 final int h = dr.getIntrinsicHeight(); 14470 final int w = dr.getIntrinsicWidth(); 14471 final Rect rect = mAttachInfo.mTmpInvalRect; 14472 getScrollIndicatorBounds(rect); 14473 14474 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 14475 final boolean canScrollUp = canScrollVertically(-1); 14476 if (canScrollUp) { 14477 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 14478 dr.draw(c); 14479 } 14480 } 14481 14482 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 14483 final boolean canScrollDown = canScrollVertically(1); 14484 if (canScrollDown) { 14485 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 14486 dr.draw(c); 14487 } 14488 } 14489 14490 final int leftRtl; 14491 final int rightRtl; 14492 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14493 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 14494 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 14495 } else { 14496 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 14497 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 14498 } 14499 14500 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 14501 if ((mPrivateFlags3 & leftMask) != 0) { 14502 final boolean canScrollLeft = canScrollHorizontally(-1); 14503 if (canScrollLeft) { 14504 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 14505 dr.draw(c); 14506 } 14507 } 14508 14509 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 14510 if ((mPrivateFlags3 & rightMask) != 0) { 14511 final boolean canScrollRight = canScrollHorizontally(1); 14512 if (canScrollRight) { 14513 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 14514 dr.draw(c); 14515 } 14516 } 14517 } 14518 14519 private void getHorizontalScrollBarBounds(Rect bounds) { 14520 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14521 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14522 && !isVerticalScrollBarHidden(); 14523 final int size = getHorizontalScrollbarHeight(); 14524 final int verticalScrollBarGap = drawVerticalScrollBar ? 14525 getVerticalScrollbarWidth() : 0; 14526 final int width = mRight - mLeft; 14527 final int height = mBottom - mTop; 14528 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 14529 bounds.left = mScrollX + (mPaddingLeft & inside); 14530 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 14531 bounds.bottom = bounds.top + size; 14532 } 14533 14534 private void getVerticalScrollBarBounds(Rect bounds) { 14535 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 14536 final int size = getVerticalScrollbarWidth(); 14537 int verticalScrollbarPosition = mVerticalScrollbarPosition; 14538 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 14539 verticalScrollbarPosition = isLayoutRtl() ? 14540 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 14541 } 14542 final int width = mRight - mLeft; 14543 final int height = mBottom - mTop; 14544 switch (verticalScrollbarPosition) { 14545 default: 14546 case SCROLLBAR_POSITION_RIGHT: 14547 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 14548 break; 14549 case SCROLLBAR_POSITION_LEFT: 14550 bounds.left = mScrollX + (mUserPaddingLeft & inside); 14551 break; 14552 } 14553 bounds.top = mScrollY + (mPaddingTop & inside); 14554 bounds.right = bounds.left + size; 14555 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 14556 } 14557 14558 /** 14559 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 14560 * scrollbars are painted only if they have been awakened first.</p> 14561 * 14562 * @param canvas the canvas on which to draw the scrollbars 14563 * 14564 * @see #awakenScrollBars(int) 14565 */ 14566 protected final void onDrawScrollBars(Canvas canvas) { 14567 // scrollbars are drawn only when the animation is running 14568 final ScrollabilityCache cache = mScrollCache; 14569 if (cache != null) { 14570 14571 int state = cache.state; 14572 14573 if (state == ScrollabilityCache.OFF) { 14574 return; 14575 } 14576 14577 boolean invalidate = false; 14578 14579 if (state == ScrollabilityCache.FADING) { 14580 // We're fading -- get our fade interpolation 14581 if (cache.interpolatorValues == null) { 14582 cache.interpolatorValues = new float[1]; 14583 } 14584 14585 float[] values = cache.interpolatorValues; 14586 14587 // Stops the animation if we're done 14588 if (cache.scrollBarInterpolator.timeToValues(values) == 14589 Interpolator.Result.FREEZE_END) { 14590 cache.state = ScrollabilityCache.OFF; 14591 } else { 14592 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 14593 } 14594 14595 // This will make the scroll bars inval themselves after 14596 // drawing. We only want this when we're fading so that 14597 // we prevent excessive redraws 14598 invalidate = true; 14599 } else { 14600 // We're just on -- but we may have been fading before so 14601 // reset alpha 14602 cache.scrollBar.mutate().setAlpha(255); 14603 } 14604 14605 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 14606 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 14607 && !isVerticalScrollBarHidden(); 14608 14609 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 14610 final ScrollBarDrawable scrollBar = cache.scrollBar; 14611 14612 if (drawHorizontalScrollBar) { 14613 scrollBar.setParameters(computeHorizontalScrollRange(), 14614 computeHorizontalScrollOffset(), 14615 computeHorizontalScrollExtent(), false); 14616 final Rect bounds = cache.mScrollBarBounds; 14617 getHorizontalScrollBarBounds(bounds); 14618 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14619 bounds.right, bounds.bottom); 14620 if (invalidate) { 14621 invalidate(bounds); 14622 } 14623 } 14624 14625 if (drawVerticalScrollBar) { 14626 scrollBar.setParameters(computeVerticalScrollRange(), 14627 computeVerticalScrollOffset(), 14628 computeVerticalScrollExtent(), true); 14629 final Rect bounds = cache.mScrollBarBounds; 14630 getVerticalScrollBarBounds(bounds); 14631 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 14632 bounds.right, bounds.bottom); 14633 if (invalidate) { 14634 invalidate(bounds); 14635 } 14636 } 14637 } 14638 } 14639 } 14640 14641 /** 14642 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 14643 * FastScroller is visible. 14644 * @return whether to temporarily hide the vertical scrollbar 14645 * @hide 14646 */ 14647 protected boolean isVerticalScrollBarHidden() { 14648 return false; 14649 } 14650 14651 /** 14652 * <p>Draw the horizontal scrollbar if 14653 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 14654 * 14655 * @param canvas the canvas on which to draw the scrollbar 14656 * @param scrollBar the scrollbar's drawable 14657 * 14658 * @see #isHorizontalScrollBarEnabled() 14659 * @see #computeHorizontalScrollRange() 14660 * @see #computeHorizontalScrollExtent() 14661 * @see #computeHorizontalScrollOffset() 14662 * @see android.widget.ScrollBarDrawable 14663 * @hide 14664 */ 14665 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 14666 int l, int t, int r, int b) { 14667 scrollBar.setBounds(l, t, r, b); 14668 scrollBar.draw(canvas); 14669 } 14670 14671 /** 14672 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 14673 * returns true.</p> 14674 * 14675 * @param canvas the canvas on which to draw the scrollbar 14676 * @param scrollBar the scrollbar's drawable 14677 * 14678 * @see #isVerticalScrollBarEnabled() 14679 * @see #computeVerticalScrollRange() 14680 * @see #computeVerticalScrollExtent() 14681 * @see #computeVerticalScrollOffset() 14682 * @see android.widget.ScrollBarDrawable 14683 * @hide 14684 */ 14685 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 14686 int l, int t, int r, int b) { 14687 scrollBar.setBounds(l, t, r, b); 14688 scrollBar.draw(canvas); 14689 } 14690 14691 /** 14692 * Implement this to do your drawing. 14693 * 14694 * @param canvas the canvas on which the background will be drawn 14695 */ 14696 protected void onDraw(Canvas canvas) { 14697 } 14698 14699 /* 14700 * Caller is responsible for calling requestLayout if necessary. 14701 * (This allows addViewInLayout to not request a new layout.) 14702 */ 14703 void assignParent(ViewParent parent) { 14704 if (mParent == null) { 14705 mParent = parent; 14706 } else if (parent == null) { 14707 mParent = null; 14708 } else { 14709 throw new RuntimeException("view " + this + " being added, but" 14710 + " it already has a parent"); 14711 } 14712 } 14713 14714 /** 14715 * This is called when the view is attached to a window. At this point it 14716 * has a Surface and will start drawing. Note that this function is 14717 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 14718 * however it may be called any time before the first onDraw -- including 14719 * before or after {@link #onMeasure(int, int)}. 14720 * 14721 * @see #onDetachedFromWindow() 14722 */ 14723 @CallSuper 14724 protected void onAttachedToWindow() { 14725 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 14726 mParent.requestTransparentRegion(this); 14727 } 14728 14729 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 14730 14731 jumpDrawablesToCurrentState(); 14732 14733 resetSubtreeAccessibilityStateChanged(); 14734 14735 // rebuild, since Outline not maintained while View is detached 14736 rebuildOutline(); 14737 14738 if (isFocused()) { 14739 InputMethodManager imm = InputMethodManager.peekInstance(); 14740 if (imm != null) { 14741 imm.focusIn(this); 14742 } 14743 } 14744 } 14745 14746 /** 14747 * Resolve all RTL related properties. 14748 * 14749 * @return true if resolution of RTL properties has been done 14750 * 14751 * @hide 14752 */ 14753 public boolean resolveRtlPropertiesIfNeeded() { 14754 if (!needRtlPropertiesResolution()) return false; 14755 14756 // Order is important here: LayoutDirection MUST be resolved first 14757 if (!isLayoutDirectionResolved()) { 14758 resolveLayoutDirection(); 14759 resolveLayoutParams(); 14760 } 14761 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 14762 if (!isTextDirectionResolved()) { 14763 resolveTextDirection(); 14764 } 14765 if (!isTextAlignmentResolved()) { 14766 resolveTextAlignment(); 14767 } 14768 // Should resolve Drawables before Padding because we need the layout direction of the 14769 // Drawable to correctly resolve Padding. 14770 if (!areDrawablesResolved()) { 14771 resolveDrawables(); 14772 } 14773 if (!isPaddingResolved()) { 14774 resolvePadding(); 14775 } 14776 onRtlPropertiesChanged(getLayoutDirection()); 14777 return true; 14778 } 14779 14780 /** 14781 * Reset resolution of all RTL related properties. 14782 * 14783 * @hide 14784 */ 14785 public void resetRtlProperties() { 14786 resetResolvedLayoutDirection(); 14787 resetResolvedTextDirection(); 14788 resetResolvedTextAlignment(); 14789 resetResolvedPadding(); 14790 resetResolvedDrawables(); 14791 } 14792 14793 /** 14794 * @see #onScreenStateChanged(int) 14795 */ 14796 void dispatchScreenStateChanged(int screenState) { 14797 onScreenStateChanged(screenState); 14798 } 14799 14800 /** 14801 * This method is called whenever the state of the screen this view is 14802 * attached to changes. A state change will usually occurs when the screen 14803 * turns on or off (whether it happens automatically or the user does it 14804 * manually.) 14805 * 14806 * @param screenState The new state of the screen. Can be either 14807 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 14808 */ 14809 public void onScreenStateChanged(int screenState) { 14810 } 14811 14812 /** 14813 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 14814 */ 14815 private boolean hasRtlSupport() { 14816 return mContext.getApplicationInfo().hasRtlSupport(); 14817 } 14818 14819 /** 14820 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 14821 * RTL not supported) 14822 */ 14823 private boolean isRtlCompatibilityMode() { 14824 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 14825 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 14826 } 14827 14828 /** 14829 * @return true if RTL properties need resolution. 14830 * 14831 */ 14832 private boolean needRtlPropertiesResolution() { 14833 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 14834 } 14835 14836 /** 14837 * Called when any RTL property (layout direction or text direction or text alignment) has 14838 * been changed. 14839 * 14840 * Subclasses need to override this method to take care of cached information that depends on the 14841 * resolved layout direction, or to inform child views that inherit their layout direction. 14842 * 14843 * The default implementation does nothing. 14844 * 14845 * @param layoutDirection the direction of the layout 14846 * 14847 * @see #LAYOUT_DIRECTION_LTR 14848 * @see #LAYOUT_DIRECTION_RTL 14849 */ 14850 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 14851 } 14852 14853 /** 14854 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 14855 * that the parent directionality can and will be resolved before its children. 14856 * 14857 * @return true if resolution has been done, false otherwise. 14858 * 14859 * @hide 14860 */ 14861 public boolean resolveLayoutDirection() { 14862 // Clear any previous layout direction resolution 14863 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14864 14865 if (hasRtlSupport()) { 14866 // Set resolved depending on layout direction 14867 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 14868 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 14869 case LAYOUT_DIRECTION_INHERIT: 14870 // We cannot resolve yet. LTR is by default and let the resolution happen again 14871 // later to get the correct resolved value 14872 if (!canResolveLayoutDirection()) return false; 14873 14874 // Parent has not yet resolved, LTR is still the default 14875 try { 14876 if (!mParent.isLayoutDirectionResolved()) return false; 14877 14878 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 14879 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14880 } 14881 } catch (AbstractMethodError e) { 14882 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14883 " does not fully implement ViewParent", e); 14884 } 14885 break; 14886 case LAYOUT_DIRECTION_RTL: 14887 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14888 break; 14889 case LAYOUT_DIRECTION_LOCALE: 14890 if((LAYOUT_DIRECTION_RTL == 14891 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 14892 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 14893 } 14894 break; 14895 default: 14896 // Nothing to do, LTR by default 14897 } 14898 } 14899 14900 // Set to resolved 14901 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14902 return true; 14903 } 14904 14905 /** 14906 * Check if layout direction resolution can be done. 14907 * 14908 * @return true if layout direction resolution can be done otherwise return false. 14909 */ 14910 public boolean canResolveLayoutDirection() { 14911 switch (getRawLayoutDirection()) { 14912 case LAYOUT_DIRECTION_INHERIT: 14913 if (mParent != null) { 14914 try { 14915 return mParent.canResolveLayoutDirection(); 14916 } catch (AbstractMethodError e) { 14917 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 14918 " does not fully implement ViewParent", e); 14919 } 14920 } 14921 return false; 14922 14923 default: 14924 return true; 14925 } 14926 } 14927 14928 /** 14929 * Reset the resolved layout direction. Layout direction will be resolved during a call to 14930 * {@link #onMeasure(int, int)}. 14931 * 14932 * @hide 14933 */ 14934 public void resetResolvedLayoutDirection() { 14935 // Reset the current resolved bits 14936 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 14937 } 14938 14939 /** 14940 * @return true if the layout direction is inherited. 14941 * 14942 * @hide 14943 */ 14944 public boolean isLayoutDirectionInherited() { 14945 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 14946 } 14947 14948 /** 14949 * @return true if layout direction has been resolved. 14950 */ 14951 public boolean isLayoutDirectionResolved() { 14952 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 14953 } 14954 14955 /** 14956 * Return if padding has been resolved 14957 * 14958 * @hide 14959 */ 14960 boolean isPaddingResolved() { 14961 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 14962 } 14963 14964 /** 14965 * Resolves padding depending on layout direction, if applicable, and 14966 * recomputes internal padding values to adjust for scroll bars. 14967 * 14968 * @hide 14969 */ 14970 public void resolvePadding() { 14971 final int resolvedLayoutDirection = getLayoutDirection(); 14972 14973 if (!isRtlCompatibilityMode()) { 14974 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 14975 // If start / end padding are defined, they will be resolved (hence overriding) to 14976 // left / right or right / left depending on the resolved layout direction. 14977 // If start / end padding are not defined, use the left / right ones. 14978 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 14979 Rect padding = sThreadLocal.get(); 14980 if (padding == null) { 14981 padding = new Rect(); 14982 sThreadLocal.set(padding); 14983 } 14984 mBackground.getPadding(padding); 14985 if (!mLeftPaddingDefined) { 14986 mUserPaddingLeftInitial = padding.left; 14987 } 14988 if (!mRightPaddingDefined) { 14989 mUserPaddingRightInitial = padding.right; 14990 } 14991 } 14992 switch (resolvedLayoutDirection) { 14993 case LAYOUT_DIRECTION_RTL: 14994 if (mUserPaddingStart != UNDEFINED_PADDING) { 14995 mUserPaddingRight = mUserPaddingStart; 14996 } else { 14997 mUserPaddingRight = mUserPaddingRightInitial; 14998 } 14999 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15000 mUserPaddingLeft = mUserPaddingEnd; 15001 } else { 15002 mUserPaddingLeft = mUserPaddingLeftInitial; 15003 } 15004 break; 15005 case LAYOUT_DIRECTION_LTR: 15006 default: 15007 if (mUserPaddingStart != UNDEFINED_PADDING) { 15008 mUserPaddingLeft = mUserPaddingStart; 15009 } else { 15010 mUserPaddingLeft = mUserPaddingLeftInitial; 15011 } 15012 if (mUserPaddingEnd != UNDEFINED_PADDING) { 15013 mUserPaddingRight = mUserPaddingEnd; 15014 } else { 15015 mUserPaddingRight = mUserPaddingRightInitial; 15016 } 15017 } 15018 15019 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 15020 } 15021 15022 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15023 onRtlPropertiesChanged(resolvedLayoutDirection); 15024 15025 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 15026 } 15027 15028 /** 15029 * Reset the resolved layout direction. 15030 * 15031 * @hide 15032 */ 15033 public void resetResolvedPadding() { 15034 resetResolvedPaddingInternal(); 15035 } 15036 15037 /** 15038 * Used when we only want to reset *this* view's padding and not trigger overrides 15039 * in ViewGroup that reset children too. 15040 */ 15041 void resetResolvedPaddingInternal() { 15042 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 15043 } 15044 15045 /** 15046 * This is called when the view is detached from a window. At this point it 15047 * no longer has a surface for drawing. 15048 * 15049 * @see #onAttachedToWindow() 15050 */ 15051 @CallSuper 15052 protected void onDetachedFromWindow() { 15053 } 15054 15055 /** 15056 * This is a framework-internal mirror of onDetachedFromWindow() that's called 15057 * after onDetachedFromWindow(). 15058 * 15059 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 15060 * The super method should be called at the end of the overridden method to ensure 15061 * subclasses are destroyed first 15062 * 15063 * @hide 15064 */ 15065 @CallSuper 15066 protected void onDetachedFromWindowInternal() { 15067 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 15068 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 15069 15070 removeUnsetPressCallback(); 15071 removeLongPressCallback(); 15072 removePerformClickCallback(); 15073 removeSendViewScrolledAccessibilityEventCallback(); 15074 stopNestedScroll(); 15075 15076 // Anything that started animating right before detach should already 15077 // be in its final state when re-attached. 15078 jumpDrawablesToCurrentState(); 15079 15080 destroyDrawingCache(); 15081 15082 cleanupDraw(); 15083 releasePointerCapture(); 15084 mCurrentAnimation = null; 15085 } 15086 15087 private void cleanupDraw() { 15088 resetDisplayList(); 15089 if (mAttachInfo != null) { 15090 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 15091 } 15092 } 15093 15094 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 15095 } 15096 15097 /** 15098 * @return The number of times this view has been attached to a window 15099 */ 15100 protected int getWindowAttachCount() { 15101 return mWindowAttachCount; 15102 } 15103 15104 /** 15105 * Retrieve a unique token identifying the window this view is attached to. 15106 * @return Return the window's token for use in 15107 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 15108 */ 15109 public IBinder getWindowToken() { 15110 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 15111 } 15112 15113 /** 15114 * Retrieve the {@link WindowId} for the window this view is 15115 * currently attached to. 15116 */ 15117 public WindowId getWindowId() { 15118 if (mAttachInfo == null) { 15119 return null; 15120 } 15121 if (mAttachInfo.mWindowId == null) { 15122 try { 15123 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 15124 mAttachInfo.mWindowToken); 15125 mAttachInfo.mWindowId = new WindowId( 15126 mAttachInfo.mIWindowId); 15127 } catch (RemoteException e) { 15128 } 15129 } 15130 return mAttachInfo.mWindowId; 15131 } 15132 15133 /** 15134 * Retrieve a unique token identifying the top-level "real" window of 15135 * the window that this view is attached to. That is, this is like 15136 * {@link #getWindowToken}, except if the window this view in is a panel 15137 * window (attached to another containing window), then the token of 15138 * the containing window is returned instead. 15139 * 15140 * @return Returns the associated window token, either 15141 * {@link #getWindowToken()} or the containing window's token. 15142 */ 15143 public IBinder getApplicationWindowToken() { 15144 AttachInfo ai = mAttachInfo; 15145 if (ai != null) { 15146 IBinder appWindowToken = ai.mPanelParentWindowToken; 15147 if (appWindowToken == null) { 15148 appWindowToken = ai.mWindowToken; 15149 } 15150 return appWindowToken; 15151 } 15152 return null; 15153 } 15154 15155 /** 15156 * Gets the logical display to which the view's window has been attached. 15157 * 15158 * @return The logical display, or null if the view is not currently attached to a window. 15159 */ 15160 public Display getDisplay() { 15161 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 15162 } 15163 15164 /** 15165 * Retrieve private session object this view hierarchy is using to 15166 * communicate with the window manager. 15167 * @return the session object to communicate with the window manager 15168 */ 15169 /*package*/ IWindowSession getWindowSession() { 15170 return mAttachInfo != null ? mAttachInfo.mSession : null; 15171 } 15172 15173 /** 15174 * Return the visibility value of the least visible component passed. 15175 */ 15176 int combineVisibility(int vis1, int vis2) { 15177 // This works because VISIBLE < INVISIBLE < GONE. 15178 return Math.max(vis1, vis2); 15179 } 15180 15181 /** 15182 * @param info the {@link android.view.View.AttachInfo} to associated with 15183 * this view 15184 */ 15185 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 15186 mAttachInfo = info; 15187 if (mOverlay != null) { 15188 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 15189 } 15190 mWindowAttachCount++; 15191 // We will need to evaluate the drawable state at least once. 15192 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15193 if (mFloatingTreeObserver != null) { 15194 info.mTreeObserver.merge(mFloatingTreeObserver); 15195 mFloatingTreeObserver = null; 15196 } 15197 15198 registerPendingFrameMetricsObservers(); 15199 15200 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 15201 mAttachInfo.mScrollContainers.add(this); 15202 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 15203 } 15204 // Transfer all pending runnables. 15205 if (mRunQueue != null) { 15206 mRunQueue.executeActions(info.mHandler); 15207 mRunQueue = null; 15208 } 15209 performCollectViewAttributes(mAttachInfo, visibility); 15210 onAttachedToWindow(); 15211 15212 ListenerInfo li = mListenerInfo; 15213 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15214 li != null ? li.mOnAttachStateChangeListeners : null; 15215 if (listeners != null && listeners.size() > 0) { 15216 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15217 // perform the dispatching. The iterator is a safe guard against listeners that 15218 // could mutate the list by calling the various add/remove methods. This prevents 15219 // the array from being modified while we iterate it. 15220 for (OnAttachStateChangeListener listener : listeners) { 15221 listener.onViewAttachedToWindow(this); 15222 } 15223 } 15224 15225 int vis = info.mWindowVisibility; 15226 if (vis != GONE) { 15227 onWindowVisibilityChanged(vis); 15228 } 15229 15230 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 15231 // As all views in the subtree will already receive dispatchAttachedToWindow 15232 // traversing the subtree again here is not desired. 15233 onVisibilityChanged(this, visibility); 15234 15235 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 15236 // If nobody has evaluated the drawable state yet, then do it now. 15237 refreshDrawableState(); 15238 } 15239 needGlobalAttributesUpdate(false); 15240 } 15241 15242 void dispatchDetachedFromWindow() { 15243 AttachInfo info = mAttachInfo; 15244 if (info != null) { 15245 int vis = info.mWindowVisibility; 15246 if (vis != GONE) { 15247 onWindowVisibilityChanged(GONE); 15248 } 15249 } 15250 15251 onDetachedFromWindow(); 15252 onDetachedFromWindowInternal(); 15253 15254 InputMethodManager imm = InputMethodManager.peekInstance(); 15255 if (imm != null) { 15256 imm.onViewDetachedFromWindow(this); 15257 } 15258 15259 ListenerInfo li = mListenerInfo; 15260 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 15261 li != null ? li.mOnAttachStateChangeListeners : null; 15262 if (listeners != null && listeners.size() > 0) { 15263 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 15264 // perform the dispatching. The iterator is a safe guard against listeners that 15265 // could mutate the list by calling the various add/remove methods. This prevents 15266 // the array from being modified while we iterate it. 15267 for (OnAttachStateChangeListener listener : listeners) { 15268 listener.onViewDetachedFromWindow(this); 15269 } 15270 } 15271 15272 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 15273 mAttachInfo.mScrollContainers.remove(this); 15274 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 15275 } 15276 15277 mAttachInfo = null; 15278 if (mOverlay != null) { 15279 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 15280 } 15281 } 15282 15283 /** 15284 * Cancel any deferred high-level input events that were previously posted to the event queue. 15285 * 15286 * <p>Many views post high-level events such as click handlers to the event queue 15287 * to run deferred in order to preserve a desired user experience - clearing visible 15288 * pressed states before executing, etc. This method will abort any events of this nature 15289 * that are currently in flight.</p> 15290 * 15291 * <p>Custom views that generate their own high-level deferred input events should override 15292 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 15293 * 15294 * <p>This will also cancel pending input events for any child views.</p> 15295 * 15296 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 15297 * This will not impact newer events posted after this call that may occur as a result of 15298 * lower-level input events still waiting in the queue. If you are trying to prevent 15299 * double-submitted events for the duration of some sort of asynchronous transaction 15300 * you should also take other steps to protect against unexpected double inputs e.g. calling 15301 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 15302 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 15303 */ 15304 public final void cancelPendingInputEvents() { 15305 dispatchCancelPendingInputEvents(); 15306 } 15307 15308 /** 15309 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 15310 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 15311 */ 15312 void dispatchCancelPendingInputEvents() { 15313 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 15314 onCancelPendingInputEvents(); 15315 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 15316 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 15317 " did not call through to super.onCancelPendingInputEvents()"); 15318 } 15319 } 15320 15321 /** 15322 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 15323 * a parent view. 15324 * 15325 * <p>This method is responsible for removing any pending high-level input events that were 15326 * posted to the event queue to run later. Custom view classes that post their own deferred 15327 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 15328 * {@link android.os.Handler} should override this method, call 15329 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 15330 * </p> 15331 */ 15332 public void onCancelPendingInputEvents() { 15333 removePerformClickCallback(); 15334 cancelLongPress(); 15335 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 15336 } 15337 15338 /** 15339 * Store this view hierarchy's frozen state into the given container. 15340 * 15341 * @param container The SparseArray in which to save the view's state. 15342 * 15343 * @see #restoreHierarchyState(android.util.SparseArray) 15344 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15345 * @see #onSaveInstanceState() 15346 */ 15347 public void saveHierarchyState(SparseArray<Parcelable> container) { 15348 dispatchSaveInstanceState(container); 15349 } 15350 15351 /** 15352 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 15353 * this view and its children. May be overridden to modify how freezing happens to a 15354 * view's children; for example, some views may want to not store state for their children. 15355 * 15356 * @param container The SparseArray in which to save the view's state. 15357 * 15358 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15359 * @see #saveHierarchyState(android.util.SparseArray) 15360 * @see #onSaveInstanceState() 15361 */ 15362 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 15363 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 15364 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15365 Parcelable state = onSaveInstanceState(); 15366 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15367 throw new IllegalStateException( 15368 "Derived class did not call super.onSaveInstanceState()"); 15369 } 15370 if (state != null) { 15371 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 15372 // + ": " + state); 15373 container.put(mID, state); 15374 } 15375 } 15376 } 15377 15378 /** 15379 * Hook allowing a view to generate a representation of its internal state 15380 * that can later be used to create a new instance with that same state. 15381 * This state should only contain information that is not persistent or can 15382 * not be reconstructed later. For example, you will never store your 15383 * current position on screen because that will be computed again when a 15384 * new instance of the view is placed in its view hierarchy. 15385 * <p> 15386 * Some examples of things you may store here: the current cursor position 15387 * in a text view (but usually not the text itself since that is stored in a 15388 * content provider or other persistent storage), the currently selected 15389 * item in a list view. 15390 * 15391 * @return Returns a Parcelable object containing the view's current dynamic 15392 * state, or null if there is nothing interesting to save. The 15393 * default implementation returns null. 15394 * @see #onRestoreInstanceState(android.os.Parcelable) 15395 * @see #saveHierarchyState(android.util.SparseArray) 15396 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15397 * @see #setSaveEnabled(boolean) 15398 */ 15399 @CallSuper 15400 protected Parcelable onSaveInstanceState() { 15401 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15402 if (mStartActivityRequestWho != null) { 15403 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 15404 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 15405 return state; 15406 } 15407 return BaseSavedState.EMPTY_STATE; 15408 } 15409 15410 /** 15411 * Restore this view hierarchy's frozen state from the given container. 15412 * 15413 * @param container The SparseArray which holds previously frozen states. 15414 * 15415 * @see #saveHierarchyState(android.util.SparseArray) 15416 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15417 * @see #onRestoreInstanceState(android.os.Parcelable) 15418 */ 15419 public void restoreHierarchyState(SparseArray<Parcelable> container) { 15420 dispatchRestoreInstanceState(container); 15421 } 15422 15423 /** 15424 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 15425 * state for this view and its children. May be overridden to modify how restoring 15426 * happens to a view's children; for example, some views may want to not store state 15427 * for their children. 15428 * 15429 * @param container The SparseArray which holds previously saved state. 15430 * 15431 * @see #dispatchSaveInstanceState(android.util.SparseArray) 15432 * @see #restoreHierarchyState(android.util.SparseArray) 15433 * @see #onRestoreInstanceState(android.os.Parcelable) 15434 */ 15435 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 15436 if (mID != NO_ID) { 15437 Parcelable state = container.get(mID); 15438 if (state != null) { 15439 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 15440 // + ": " + state); 15441 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 15442 onRestoreInstanceState(state); 15443 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 15444 throw new IllegalStateException( 15445 "Derived class did not call super.onRestoreInstanceState()"); 15446 } 15447 } 15448 } 15449 } 15450 15451 /** 15452 * Hook allowing a view to re-apply a representation of its internal state that had previously 15453 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 15454 * null state. 15455 * 15456 * @param state The frozen state that had previously been returned by 15457 * {@link #onSaveInstanceState}. 15458 * 15459 * @see #onSaveInstanceState() 15460 * @see #restoreHierarchyState(android.util.SparseArray) 15461 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 15462 */ 15463 @CallSuper 15464 protected void onRestoreInstanceState(Parcelable state) { 15465 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 15466 if (state != null && !(state instanceof AbsSavedState)) { 15467 throw new IllegalArgumentException("Wrong state class, expecting View State but " 15468 + "received " + state.getClass().toString() + " instead. This usually happens " 15469 + "when two views of different type have the same id in the same hierarchy. " 15470 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 15471 + "other views do not use the same id."); 15472 } 15473 if (state != null && state instanceof BaseSavedState) { 15474 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 15475 } 15476 } 15477 15478 /** 15479 * <p>Return the time at which the drawing of the view hierarchy started.</p> 15480 * 15481 * @return the drawing start time in milliseconds 15482 */ 15483 public long getDrawingTime() { 15484 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 15485 } 15486 15487 /** 15488 * <p>Enables or disables the duplication of the parent's state into this view. When 15489 * duplication is enabled, this view gets its drawable state from its parent rather 15490 * than from its own internal properties.</p> 15491 * 15492 * <p>Note: in the current implementation, setting this property to true after the 15493 * view was added to a ViewGroup might have no effect at all. This property should 15494 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 15495 * 15496 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 15497 * property is enabled, an exception will be thrown.</p> 15498 * 15499 * <p>Note: if the child view uses and updates additional states which are unknown to the 15500 * parent, these states should not be affected by this method.</p> 15501 * 15502 * @param enabled True to enable duplication of the parent's drawable state, false 15503 * to disable it. 15504 * 15505 * @see #getDrawableState() 15506 * @see #isDuplicateParentStateEnabled() 15507 */ 15508 public void setDuplicateParentStateEnabled(boolean enabled) { 15509 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 15510 } 15511 15512 /** 15513 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 15514 * 15515 * @return True if this view's drawable state is duplicated from the parent, 15516 * false otherwise 15517 * 15518 * @see #getDrawableState() 15519 * @see #setDuplicateParentStateEnabled(boolean) 15520 */ 15521 public boolean isDuplicateParentStateEnabled() { 15522 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 15523 } 15524 15525 /** 15526 * <p>Specifies the type of layer backing this view. The layer can be 15527 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15528 * {@link #LAYER_TYPE_HARDWARE}.</p> 15529 * 15530 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15531 * instance that controls how the layer is composed on screen. The following 15532 * properties of the paint are taken into account when composing the layer:</p> 15533 * <ul> 15534 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15535 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15536 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15537 * </ul> 15538 * 15539 * <p>If this view has an alpha value set to < 1.0 by calling 15540 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 15541 * by this view's alpha value.</p> 15542 * 15543 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 15544 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 15545 * for more information on when and how to use layers.</p> 15546 * 15547 * @param layerType The type of layer to use with this view, must be one of 15548 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15549 * {@link #LAYER_TYPE_HARDWARE} 15550 * @param paint The paint used to compose the layer. This argument is optional 15551 * and can be null. It is ignored when the layer type is 15552 * {@link #LAYER_TYPE_NONE} 15553 * 15554 * @see #getLayerType() 15555 * @see #LAYER_TYPE_NONE 15556 * @see #LAYER_TYPE_SOFTWARE 15557 * @see #LAYER_TYPE_HARDWARE 15558 * @see #setAlpha(float) 15559 * 15560 * @attr ref android.R.styleable#View_layerType 15561 */ 15562 public void setLayerType(int layerType, Paint paint) { 15563 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 15564 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 15565 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 15566 } 15567 15568 boolean typeChanged = mRenderNode.setLayerType(layerType); 15569 15570 if (!typeChanged) { 15571 setLayerPaint(paint); 15572 return; 15573 } 15574 15575 // Destroy any previous software drawing cache if needed 15576 if (mLayerType == LAYER_TYPE_SOFTWARE) { 15577 destroyDrawingCache(); 15578 } 15579 15580 mLayerType = layerType; 15581 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 15582 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 15583 mRenderNode.setLayerPaint(mLayerPaint); 15584 15585 // draw() behaves differently if we are on a layer, so we need to 15586 // invalidate() here 15587 invalidateParentCaches(); 15588 invalidate(true); 15589 } 15590 15591 /** 15592 * Updates the {@link Paint} object used with the current layer (used only if the current 15593 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 15594 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 15595 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 15596 * ensure that the view gets redrawn immediately. 15597 * 15598 * <p>A layer is associated with an optional {@link android.graphics.Paint} 15599 * instance that controls how the layer is composed on screen. The following 15600 * properties of the paint are taken into account when composing the layer:</p> 15601 * <ul> 15602 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 15603 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 15604 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 15605 * </ul> 15606 * 15607 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 15608 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 15609 * 15610 * @param paint The paint used to compose the layer. This argument is optional 15611 * and can be null. It is ignored when the layer type is 15612 * {@link #LAYER_TYPE_NONE} 15613 * 15614 * @see #setLayerType(int, android.graphics.Paint) 15615 */ 15616 public void setLayerPaint(Paint paint) { 15617 int layerType = getLayerType(); 15618 if (layerType != LAYER_TYPE_NONE) { 15619 mLayerPaint = paint == null ? new Paint() : paint; 15620 if (layerType == LAYER_TYPE_HARDWARE) { 15621 if (mRenderNode.setLayerPaint(mLayerPaint)) { 15622 invalidateViewProperty(false, false); 15623 } 15624 } else { 15625 invalidate(); 15626 } 15627 } 15628 } 15629 15630 /** 15631 * Indicates what type of layer is currently associated with this view. By default 15632 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 15633 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 15634 * for more information on the different types of layers. 15635 * 15636 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 15637 * {@link #LAYER_TYPE_HARDWARE} 15638 * 15639 * @see #setLayerType(int, android.graphics.Paint) 15640 * @see #buildLayer() 15641 * @see #LAYER_TYPE_NONE 15642 * @see #LAYER_TYPE_SOFTWARE 15643 * @see #LAYER_TYPE_HARDWARE 15644 */ 15645 public int getLayerType() { 15646 return mLayerType; 15647 } 15648 15649 /** 15650 * Forces this view's layer to be created and this view to be rendered 15651 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 15652 * invoking this method will have no effect. 15653 * 15654 * This method can for instance be used to render a view into its layer before 15655 * starting an animation. If this view is complex, rendering into the layer 15656 * before starting the animation will avoid skipping frames. 15657 * 15658 * @throws IllegalStateException If this view is not attached to a window 15659 * 15660 * @see #setLayerType(int, android.graphics.Paint) 15661 */ 15662 public void buildLayer() { 15663 if (mLayerType == LAYER_TYPE_NONE) return; 15664 15665 final AttachInfo attachInfo = mAttachInfo; 15666 if (attachInfo == null) { 15667 throw new IllegalStateException("This view must be attached to a window first"); 15668 } 15669 15670 if (getWidth() == 0 || getHeight() == 0) { 15671 return; 15672 } 15673 15674 switch (mLayerType) { 15675 case LAYER_TYPE_HARDWARE: 15676 updateDisplayListIfDirty(); 15677 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 15678 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 15679 } 15680 break; 15681 case LAYER_TYPE_SOFTWARE: 15682 buildDrawingCache(true); 15683 break; 15684 } 15685 } 15686 15687 /** 15688 * Destroys all hardware rendering resources. This method is invoked 15689 * when the system needs to reclaim resources. Upon execution of this 15690 * method, you should free any OpenGL resources created by the view. 15691 * 15692 * Note: you <strong>must</strong> call 15693 * <code>super.destroyHardwareResources()</code> when overriding 15694 * this method. 15695 * 15696 * @hide 15697 */ 15698 @CallSuper 15699 protected void destroyHardwareResources() { 15700 // Although the Layer will be destroyed by RenderNode, we want to release 15701 // the staging display list, which is also a signal to RenderNode that it's 15702 // safe to free its copy of the display list as it knows that we will 15703 // push an updated DisplayList if we try to draw again 15704 resetDisplayList(); 15705 } 15706 15707 /** 15708 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 15709 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 15710 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 15711 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 15712 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 15713 * null.</p> 15714 * 15715 * <p>Enabling the drawing cache is similar to 15716 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 15717 * acceleration is turned off. When hardware acceleration is turned on, enabling the 15718 * drawing cache has no effect on rendering because the system uses a different mechanism 15719 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 15720 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 15721 * for information on how to enable software and hardware layers.</p> 15722 * 15723 * <p>This API can be used to manually generate 15724 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 15725 * {@link #getDrawingCache()}.</p> 15726 * 15727 * @param enabled true to enable the drawing cache, false otherwise 15728 * 15729 * @see #isDrawingCacheEnabled() 15730 * @see #getDrawingCache() 15731 * @see #buildDrawingCache() 15732 * @see #setLayerType(int, android.graphics.Paint) 15733 */ 15734 public void setDrawingCacheEnabled(boolean enabled) { 15735 mCachingFailed = false; 15736 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 15737 } 15738 15739 /** 15740 * <p>Indicates whether the drawing cache is enabled for this view.</p> 15741 * 15742 * @return true if the drawing cache is enabled 15743 * 15744 * @see #setDrawingCacheEnabled(boolean) 15745 * @see #getDrawingCache() 15746 */ 15747 @ViewDebug.ExportedProperty(category = "drawing") 15748 public boolean isDrawingCacheEnabled() { 15749 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 15750 } 15751 15752 /** 15753 * Debugging utility which recursively outputs the dirty state of a view and its 15754 * descendants. 15755 * 15756 * @hide 15757 */ 15758 @SuppressWarnings({"UnusedDeclaration"}) 15759 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 15760 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 15761 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 15762 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 15763 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 15764 if (clear) { 15765 mPrivateFlags &= clearMask; 15766 } 15767 if (this instanceof ViewGroup) { 15768 ViewGroup parent = (ViewGroup) this; 15769 final int count = parent.getChildCount(); 15770 for (int i = 0; i < count; i++) { 15771 final View child = parent.getChildAt(i); 15772 child.outputDirtyFlags(indent + " ", clear, clearMask); 15773 } 15774 } 15775 } 15776 15777 /** 15778 * This method is used by ViewGroup to cause its children to restore or recreate their 15779 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 15780 * to recreate its own display list, which would happen if it went through the normal 15781 * draw/dispatchDraw mechanisms. 15782 * 15783 * @hide 15784 */ 15785 protected void dispatchGetDisplayList() {} 15786 15787 /** 15788 * A view that is not attached or hardware accelerated cannot create a display list. 15789 * This method checks these conditions and returns the appropriate result. 15790 * 15791 * @return true if view has the ability to create a display list, false otherwise. 15792 * 15793 * @hide 15794 */ 15795 public boolean canHaveDisplayList() { 15796 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 15797 } 15798 15799 /** 15800 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 15801 * @hide 15802 */ 15803 @NonNull 15804 public RenderNode updateDisplayListIfDirty() { 15805 final RenderNode renderNode = mRenderNode; 15806 if (!canHaveDisplayList()) { 15807 // can't populate RenderNode, don't try 15808 return renderNode; 15809 } 15810 15811 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 15812 || !renderNode.isValid() 15813 || (mRecreateDisplayList)) { 15814 // Don't need to recreate the display list, just need to tell our 15815 // children to restore/recreate theirs 15816 if (renderNode.isValid() 15817 && !mRecreateDisplayList) { 15818 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15819 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15820 dispatchGetDisplayList(); 15821 15822 return renderNode; // no work needed 15823 } 15824 15825 // If we got here, we're recreating it. Mark it as such to ensure that 15826 // we copy in child display lists into ours in drawChild() 15827 mRecreateDisplayList = true; 15828 15829 int width = mRight - mLeft; 15830 int height = mBottom - mTop; 15831 int layerType = getLayerType(); 15832 15833 final DisplayListCanvas canvas = renderNode.start(width, height); 15834 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 15835 15836 try { 15837 if (layerType == LAYER_TYPE_SOFTWARE) { 15838 buildDrawingCache(true); 15839 Bitmap cache = getDrawingCache(true); 15840 if (cache != null) { 15841 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 15842 } 15843 } else { 15844 computeScroll(); 15845 15846 canvas.translate(-mScrollX, -mScrollY); 15847 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15848 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15849 15850 // Fast path for layouts with no backgrounds 15851 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15852 dispatchDraw(canvas); 15853 if (mOverlay != null && !mOverlay.isEmpty()) { 15854 mOverlay.getOverlayView().draw(canvas); 15855 } 15856 } else { 15857 draw(canvas); 15858 } 15859 } 15860 } finally { 15861 renderNode.end(canvas); 15862 setDisplayListProperties(renderNode); 15863 } 15864 } else { 15865 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 15866 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15867 } 15868 return renderNode; 15869 } 15870 15871 private void resetDisplayList() { 15872 if (mRenderNode.isValid()) { 15873 mRenderNode.discardDisplayList(); 15874 } 15875 15876 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 15877 mBackgroundRenderNode.discardDisplayList(); 15878 } 15879 } 15880 15881 /** 15882 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 15883 * 15884 * @return A non-scaled bitmap representing this view or null if cache is disabled. 15885 * 15886 * @see #getDrawingCache(boolean) 15887 */ 15888 public Bitmap getDrawingCache() { 15889 return getDrawingCache(false); 15890 } 15891 15892 /** 15893 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 15894 * is null when caching is disabled. If caching is enabled and the cache is not ready, 15895 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 15896 * draw from the cache when the cache is enabled. To benefit from the cache, you must 15897 * request the drawing cache by calling this method and draw it on screen if the 15898 * returned bitmap is not null.</p> 15899 * 15900 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15901 * this method will create a bitmap of the same size as this view. Because this bitmap 15902 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15903 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15904 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15905 * size than the view. This implies that your application must be able to handle this 15906 * size.</p> 15907 * 15908 * @param autoScale Indicates whether the generated bitmap should be scaled based on 15909 * the current density of the screen when the application is in compatibility 15910 * mode. 15911 * 15912 * @return A bitmap representing this view or null if cache is disabled. 15913 * 15914 * @see #setDrawingCacheEnabled(boolean) 15915 * @see #isDrawingCacheEnabled() 15916 * @see #buildDrawingCache(boolean) 15917 * @see #destroyDrawingCache() 15918 */ 15919 public Bitmap getDrawingCache(boolean autoScale) { 15920 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 15921 return null; 15922 } 15923 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 15924 buildDrawingCache(autoScale); 15925 } 15926 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 15927 } 15928 15929 /** 15930 * <p>Frees the resources used by the drawing cache. If you call 15931 * {@link #buildDrawingCache()} manually without calling 15932 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15933 * should cleanup the cache with this method afterwards.</p> 15934 * 15935 * @see #setDrawingCacheEnabled(boolean) 15936 * @see #buildDrawingCache() 15937 * @see #getDrawingCache() 15938 */ 15939 public void destroyDrawingCache() { 15940 if (mDrawingCache != null) { 15941 mDrawingCache.recycle(); 15942 mDrawingCache = null; 15943 } 15944 if (mUnscaledDrawingCache != null) { 15945 mUnscaledDrawingCache.recycle(); 15946 mUnscaledDrawingCache = null; 15947 } 15948 } 15949 15950 /** 15951 * Setting a solid background color for the drawing cache's bitmaps will improve 15952 * performance and memory usage. Note, though that this should only be used if this 15953 * view will always be drawn on top of a solid color. 15954 * 15955 * @param color The background color to use for the drawing cache's bitmap 15956 * 15957 * @see #setDrawingCacheEnabled(boolean) 15958 * @see #buildDrawingCache() 15959 * @see #getDrawingCache() 15960 */ 15961 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 15962 if (color != mDrawingCacheBackgroundColor) { 15963 mDrawingCacheBackgroundColor = color; 15964 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 15965 } 15966 } 15967 15968 /** 15969 * @see #setDrawingCacheBackgroundColor(int) 15970 * 15971 * @return The background color to used for the drawing cache's bitmap 15972 */ 15973 @ColorInt 15974 public int getDrawingCacheBackgroundColor() { 15975 return mDrawingCacheBackgroundColor; 15976 } 15977 15978 /** 15979 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 15980 * 15981 * @see #buildDrawingCache(boolean) 15982 */ 15983 public void buildDrawingCache() { 15984 buildDrawingCache(false); 15985 } 15986 15987 /** 15988 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 15989 * 15990 * <p>If you call {@link #buildDrawingCache()} manually without calling 15991 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 15992 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 15993 * 15994 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 15995 * this method will create a bitmap of the same size as this view. Because this bitmap 15996 * will be drawn scaled by the parent ViewGroup, the result on screen might show 15997 * scaling artifacts. To avoid such artifacts, you should call this method by setting 15998 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 15999 * size than the view. This implies that your application must be able to handle this 16000 * size.</p> 16001 * 16002 * <p>You should avoid calling this method when hardware acceleration is enabled. If 16003 * you do not need the drawing cache bitmap, calling this method will increase memory 16004 * usage and cause the view to be rendered in software once, thus negatively impacting 16005 * performance.</p> 16006 * 16007 * @see #getDrawingCache() 16008 * @see #destroyDrawingCache() 16009 */ 16010 public void buildDrawingCache(boolean autoScale) { 16011 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 16012 mDrawingCache == null : mUnscaledDrawingCache == null)) { 16013 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 16014 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 16015 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 16016 } 16017 try { 16018 buildDrawingCacheImpl(autoScale); 16019 } finally { 16020 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 16021 } 16022 } 16023 } 16024 16025 /** 16026 * private, internal implementation of buildDrawingCache, used to enable tracing 16027 */ 16028 private void buildDrawingCacheImpl(boolean autoScale) { 16029 mCachingFailed = false; 16030 16031 int width = mRight - mLeft; 16032 int height = mBottom - mTop; 16033 16034 final AttachInfo attachInfo = mAttachInfo; 16035 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 16036 16037 if (autoScale && scalingRequired) { 16038 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 16039 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 16040 } 16041 16042 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 16043 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 16044 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 16045 16046 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 16047 final long drawingCacheSize = 16048 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 16049 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 16050 if (width > 0 && height > 0) { 16051 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 16052 + " too large to fit into a software layer (or drawing cache), needs " 16053 + projectedBitmapSize + " bytes, only " 16054 + drawingCacheSize + " available"); 16055 } 16056 destroyDrawingCache(); 16057 mCachingFailed = true; 16058 return; 16059 } 16060 16061 boolean clear = true; 16062 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 16063 16064 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 16065 Bitmap.Config quality; 16066 if (!opaque) { 16067 // Never pick ARGB_4444 because it looks awful 16068 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 16069 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 16070 case DRAWING_CACHE_QUALITY_AUTO: 16071 case DRAWING_CACHE_QUALITY_LOW: 16072 case DRAWING_CACHE_QUALITY_HIGH: 16073 default: 16074 quality = Bitmap.Config.ARGB_8888; 16075 break; 16076 } 16077 } else { 16078 // Optimization for translucent windows 16079 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 16080 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 16081 } 16082 16083 // Try to cleanup memory 16084 if (bitmap != null) bitmap.recycle(); 16085 16086 try { 16087 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16088 width, height, quality); 16089 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 16090 if (autoScale) { 16091 mDrawingCache = bitmap; 16092 } else { 16093 mUnscaledDrawingCache = bitmap; 16094 } 16095 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 16096 } catch (OutOfMemoryError e) { 16097 // If there is not enough memory to create the bitmap cache, just 16098 // ignore the issue as bitmap caches are not required to draw the 16099 // view hierarchy 16100 if (autoScale) { 16101 mDrawingCache = null; 16102 } else { 16103 mUnscaledDrawingCache = null; 16104 } 16105 mCachingFailed = true; 16106 return; 16107 } 16108 16109 clear = drawingCacheBackgroundColor != 0; 16110 } 16111 16112 Canvas canvas; 16113 if (attachInfo != null) { 16114 canvas = attachInfo.mCanvas; 16115 if (canvas == null) { 16116 canvas = new Canvas(); 16117 } 16118 canvas.setBitmap(bitmap); 16119 // Temporarily clobber the cached Canvas in case one of our children 16120 // is also using a drawing cache. Without this, the children would 16121 // steal the canvas by attaching their own bitmap to it and bad, bad 16122 // thing would happen (invisible views, corrupted drawings, etc.) 16123 attachInfo.mCanvas = null; 16124 } else { 16125 // This case should hopefully never or seldom happen 16126 canvas = new Canvas(bitmap); 16127 } 16128 16129 if (clear) { 16130 bitmap.eraseColor(drawingCacheBackgroundColor); 16131 } 16132 16133 computeScroll(); 16134 final int restoreCount = canvas.save(); 16135 16136 if (autoScale && scalingRequired) { 16137 final float scale = attachInfo.mApplicationScale; 16138 canvas.scale(scale, scale); 16139 } 16140 16141 canvas.translate(-mScrollX, -mScrollY); 16142 16143 mPrivateFlags |= PFLAG_DRAWN; 16144 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 16145 mLayerType != LAYER_TYPE_NONE) { 16146 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 16147 } 16148 16149 // Fast path for layouts with no backgrounds 16150 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16151 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16152 dispatchDraw(canvas); 16153 if (mOverlay != null && !mOverlay.isEmpty()) { 16154 mOverlay.getOverlayView().draw(canvas); 16155 } 16156 } else { 16157 draw(canvas); 16158 } 16159 16160 canvas.restoreToCount(restoreCount); 16161 canvas.setBitmap(null); 16162 16163 if (attachInfo != null) { 16164 // Restore the cached Canvas for our siblings 16165 attachInfo.mCanvas = canvas; 16166 } 16167 } 16168 16169 /** 16170 * Create a snapshot of the view into a bitmap. We should probably make 16171 * some form of this public, but should think about the API. 16172 */ 16173 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 16174 int width = mRight - mLeft; 16175 int height = mBottom - mTop; 16176 16177 final AttachInfo attachInfo = mAttachInfo; 16178 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 16179 width = (int) ((width * scale) + 0.5f); 16180 height = (int) ((height * scale) + 0.5f); 16181 16182 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 16183 width > 0 ? width : 1, height > 0 ? height : 1, quality); 16184 if (bitmap == null) { 16185 throw new OutOfMemoryError(); 16186 } 16187 16188 Resources resources = getResources(); 16189 if (resources != null) { 16190 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 16191 } 16192 16193 Canvas canvas; 16194 if (attachInfo != null) { 16195 canvas = attachInfo.mCanvas; 16196 if (canvas == null) { 16197 canvas = new Canvas(); 16198 } 16199 canvas.setBitmap(bitmap); 16200 // Temporarily clobber the cached Canvas in case one of our children 16201 // is also using a drawing cache. Without this, the children would 16202 // steal the canvas by attaching their own bitmap to it and bad, bad 16203 // things would happen (invisible views, corrupted drawings, etc.) 16204 attachInfo.mCanvas = null; 16205 } else { 16206 // This case should hopefully never or seldom happen 16207 canvas = new Canvas(bitmap); 16208 } 16209 16210 if ((backgroundColor & 0xff000000) != 0) { 16211 bitmap.eraseColor(backgroundColor); 16212 } 16213 16214 computeScroll(); 16215 final int restoreCount = canvas.save(); 16216 canvas.scale(scale, scale); 16217 canvas.translate(-mScrollX, -mScrollY); 16218 16219 // Temporarily remove the dirty mask 16220 int flags = mPrivateFlags; 16221 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16222 16223 // Fast path for layouts with no backgrounds 16224 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16225 dispatchDraw(canvas); 16226 if (mOverlay != null && !mOverlay.isEmpty()) { 16227 mOverlay.getOverlayView().draw(canvas); 16228 } 16229 } else { 16230 draw(canvas); 16231 } 16232 16233 mPrivateFlags = flags; 16234 16235 canvas.restoreToCount(restoreCount); 16236 canvas.setBitmap(null); 16237 16238 if (attachInfo != null) { 16239 // Restore the cached Canvas for our siblings 16240 attachInfo.mCanvas = canvas; 16241 } 16242 16243 return bitmap; 16244 } 16245 16246 /** 16247 * Indicates whether this View is currently in edit mode. A View is usually 16248 * in edit mode when displayed within a developer tool. For instance, if 16249 * this View is being drawn by a visual user interface builder, this method 16250 * should return true. 16251 * 16252 * Subclasses should check the return value of this method to provide 16253 * different behaviors if their normal behavior might interfere with the 16254 * host environment. For instance: the class spawns a thread in its 16255 * constructor, the drawing code relies on device-specific features, etc. 16256 * 16257 * This method is usually checked in the drawing code of custom widgets. 16258 * 16259 * @return True if this View is in edit mode, false otherwise. 16260 */ 16261 public boolean isInEditMode() { 16262 return false; 16263 } 16264 16265 /** 16266 * If the View draws content inside its padding and enables fading edges, 16267 * it needs to support padding offsets. Padding offsets are added to the 16268 * fading edges to extend the length of the fade so that it covers pixels 16269 * drawn inside the padding. 16270 * 16271 * Subclasses of this class should override this method if they need 16272 * to draw content inside the padding. 16273 * 16274 * @return True if padding offset must be applied, false otherwise. 16275 * 16276 * @see #getLeftPaddingOffset() 16277 * @see #getRightPaddingOffset() 16278 * @see #getTopPaddingOffset() 16279 * @see #getBottomPaddingOffset() 16280 * 16281 * @since CURRENT 16282 */ 16283 protected boolean isPaddingOffsetRequired() { 16284 return false; 16285 } 16286 16287 /** 16288 * Amount by which to extend the left fading region. Called only when 16289 * {@link #isPaddingOffsetRequired()} returns true. 16290 * 16291 * @return The left padding offset in pixels. 16292 * 16293 * @see #isPaddingOffsetRequired() 16294 * 16295 * @since CURRENT 16296 */ 16297 protected int getLeftPaddingOffset() { 16298 return 0; 16299 } 16300 16301 /** 16302 * Amount by which to extend the right fading region. Called only when 16303 * {@link #isPaddingOffsetRequired()} returns true. 16304 * 16305 * @return The right padding offset in pixels. 16306 * 16307 * @see #isPaddingOffsetRequired() 16308 * 16309 * @since CURRENT 16310 */ 16311 protected int getRightPaddingOffset() { 16312 return 0; 16313 } 16314 16315 /** 16316 * Amount by which to extend the top fading region. Called only when 16317 * {@link #isPaddingOffsetRequired()} returns true. 16318 * 16319 * @return The top padding offset in pixels. 16320 * 16321 * @see #isPaddingOffsetRequired() 16322 * 16323 * @since CURRENT 16324 */ 16325 protected int getTopPaddingOffset() { 16326 return 0; 16327 } 16328 16329 /** 16330 * Amount by which to extend the bottom fading region. Called only when 16331 * {@link #isPaddingOffsetRequired()} returns true. 16332 * 16333 * @return The bottom padding offset in pixels. 16334 * 16335 * @see #isPaddingOffsetRequired() 16336 * 16337 * @since CURRENT 16338 */ 16339 protected int getBottomPaddingOffset() { 16340 return 0; 16341 } 16342 16343 /** 16344 * @hide 16345 * @param offsetRequired 16346 */ 16347 protected int getFadeTop(boolean offsetRequired) { 16348 int top = mPaddingTop; 16349 if (offsetRequired) top += getTopPaddingOffset(); 16350 return top; 16351 } 16352 16353 /** 16354 * @hide 16355 * @param offsetRequired 16356 */ 16357 protected int getFadeHeight(boolean offsetRequired) { 16358 int padding = mPaddingTop; 16359 if (offsetRequired) padding += getTopPaddingOffset(); 16360 return mBottom - mTop - mPaddingBottom - padding; 16361 } 16362 16363 /** 16364 * <p>Indicates whether this view is attached to a hardware accelerated 16365 * window or not.</p> 16366 * 16367 * <p>Even if this method returns true, it does not mean that every call 16368 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 16369 * accelerated {@link android.graphics.Canvas}. For instance, if this view 16370 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 16371 * window is hardware accelerated, 16372 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 16373 * return false, and this method will return true.</p> 16374 * 16375 * @return True if the view is attached to a window and the window is 16376 * hardware accelerated; false in any other case. 16377 */ 16378 @ViewDebug.ExportedProperty(category = "drawing") 16379 public boolean isHardwareAccelerated() { 16380 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 16381 } 16382 16383 /** 16384 * Sets a rectangular area on this view to which the view will be clipped 16385 * when it is drawn. Setting the value to null will remove the clip bounds 16386 * and the view will draw normally, using its full bounds. 16387 * 16388 * @param clipBounds The rectangular area, in the local coordinates of 16389 * this view, to which future drawing operations will be clipped. 16390 */ 16391 public void setClipBounds(Rect clipBounds) { 16392 if (clipBounds == mClipBounds 16393 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 16394 return; 16395 } 16396 if (clipBounds != null) { 16397 if (mClipBounds == null) { 16398 mClipBounds = new Rect(clipBounds); 16399 } else { 16400 mClipBounds.set(clipBounds); 16401 } 16402 } else { 16403 mClipBounds = null; 16404 } 16405 mRenderNode.setClipBounds(mClipBounds); 16406 invalidateViewProperty(false, false); 16407 } 16408 16409 /** 16410 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 16411 * 16412 * @return A copy of the current clip bounds if clip bounds are set, 16413 * otherwise null. 16414 */ 16415 public Rect getClipBounds() { 16416 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 16417 } 16418 16419 16420 /** 16421 * Populates an output rectangle with the clip bounds of the view, 16422 * returning {@code true} if successful or {@code false} if the view's 16423 * clip bounds are {@code null}. 16424 * 16425 * @param outRect rectangle in which to place the clip bounds of the view 16426 * @return {@code true} if successful or {@code false} if the view's 16427 * clip bounds are {@code null} 16428 */ 16429 public boolean getClipBounds(Rect outRect) { 16430 if (mClipBounds != null) { 16431 outRect.set(mClipBounds); 16432 return true; 16433 } 16434 return false; 16435 } 16436 16437 /** 16438 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 16439 * case of an active Animation being run on the view. 16440 */ 16441 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 16442 Animation a, boolean scalingRequired) { 16443 Transformation invalidationTransform; 16444 final int flags = parent.mGroupFlags; 16445 final boolean initialized = a.isInitialized(); 16446 if (!initialized) { 16447 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 16448 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 16449 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 16450 onAnimationStart(); 16451 } 16452 16453 final Transformation t = parent.getChildTransformation(); 16454 boolean more = a.getTransformation(drawingTime, t, 1f); 16455 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 16456 if (parent.mInvalidationTransformation == null) { 16457 parent.mInvalidationTransformation = new Transformation(); 16458 } 16459 invalidationTransform = parent.mInvalidationTransformation; 16460 a.getTransformation(drawingTime, invalidationTransform, 1f); 16461 } else { 16462 invalidationTransform = t; 16463 } 16464 16465 if (more) { 16466 if (!a.willChangeBounds()) { 16467 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 16468 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 16469 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 16470 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 16471 // The child need to draw an animation, potentially offscreen, so 16472 // make sure we do not cancel invalidate requests 16473 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16474 parent.invalidate(mLeft, mTop, mRight, mBottom); 16475 } 16476 } else { 16477 if (parent.mInvalidateRegion == null) { 16478 parent.mInvalidateRegion = new RectF(); 16479 } 16480 final RectF region = parent.mInvalidateRegion; 16481 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 16482 invalidationTransform); 16483 16484 // The child need to draw an animation, potentially offscreen, so 16485 // make sure we do not cancel invalidate requests 16486 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 16487 16488 final int left = mLeft + (int) region.left; 16489 final int top = mTop + (int) region.top; 16490 parent.invalidate(left, top, left + (int) (region.width() + .5f), 16491 top + (int) (region.height() + .5f)); 16492 } 16493 } 16494 return more; 16495 } 16496 16497 /** 16498 * This method is called by getDisplayList() when a display list is recorded for a View. 16499 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 16500 */ 16501 void setDisplayListProperties(RenderNode renderNode) { 16502 if (renderNode != null) { 16503 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 16504 renderNode.setClipToBounds(mParent instanceof ViewGroup 16505 && ((ViewGroup) mParent).getClipChildren()); 16506 16507 float alpha = 1; 16508 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 16509 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16510 ViewGroup parentVG = (ViewGroup) mParent; 16511 final Transformation t = parentVG.getChildTransformation(); 16512 if (parentVG.getChildStaticTransformation(this, t)) { 16513 final int transformType = t.getTransformationType(); 16514 if (transformType != Transformation.TYPE_IDENTITY) { 16515 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 16516 alpha = t.getAlpha(); 16517 } 16518 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 16519 renderNode.setStaticMatrix(t.getMatrix()); 16520 } 16521 } 16522 } 16523 } 16524 if (mTransformationInfo != null) { 16525 alpha *= getFinalAlpha(); 16526 if (alpha < 1) { 16527 final int multipliedAlpha = (int) (255 * alpha); 16528 if (onSetAlpha(multipliedAlpha)) { 16529 alpha = 1; 16530 } 16531 } 16532 renderNode.setAlpha(alpha); 16533 } else if (alpha < 1) { 16534 renderNode.setAlpha(alpha); 16535 } 16536 } 16537 } 16538 16539 /** 16540 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 16541 * 16542 * This is where the View specializes rendering behavior based on layer type, 16543 * and hardware acceleration. 16544 */ 16545 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 16546 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 16547 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 16548 * 16549 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 16550 * HW accelerated, it can't handle drawing RenderNodes. 16551 */ 16552 boolean drawingWithRenderNode = mAttachInfo != null 16553 && mAttachInfo.mHardwareAccelerated 16554 && hardwareAcceleratedCanvas; 16555 16556 boolean more = false; 16557 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 16558 final int parentFlags = parent.mGroupFlags; 16559 16560 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 16561 parent.getChildTransformation().clear(); 16562 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16563 } 16564 16565 Transformation transformToApply = null; 16566 boolean concatMatrix = false; 16567 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 16568 final Animation a = getAnimation(); 16569 if (a != null) { 16570 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 16571 concatMatrix = a.willChangeTransformationMatrix(); 16572 if (concatMatrix) { 16573 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16574 } 16575 transformToApply = parent.getChildTransformation(); 16576 } else { 16577 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 16578 // No longer animating: clear out old animation matrix 16579 mRenderNode.setAnimationMatrix(null); 16580 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 16581 } 16582 if (!drawingWithRenderNode 16583 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 16584 final Transformation t = parent.getChildTransformation(); 16585 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 16586 if (hasTransform) { 16587 final int transformType = t.getTransformationType(); 16588 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 16589 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 16590 } 16591 } 16592 } 16593 16594 concatMatrix |= !childHasIdentityMatrix; 16595 16596 // Sets the flag as early as possible to allow draw() implementations 16597 // to call invalidate() successfully when doing animations 16598 mPrivateFlags |= PFLAG_DRAWN; 16599 16600 if (!concatMatrix && 16601 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 16602 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 16603 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 16604 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 16605 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 16606 return more; 16607 } 16608 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 16609 16610 if (hardwareAcceleratedCanvas) { 16611 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 16612 // retain the flag's value temporarily in the mRecreateDisplayList flag 16613 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 16614 mPrivateFlags &= ~PFLAG_INVALIDATED; 16615 } 16616 16617 RenderNode renderNode = null; 16618 Bitmap cache = null; 16619 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 16620 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 16621 if (layerType != LAYER_TYPE_NONE) { 16622 // If not drawing with RenderNode, treat HW layers as SW 16623 layerType = LAYER_TYPE_SOFTWARE; 16624 buildDrawingCache(true); 16625 } 16626 cache = getDrawingCache(true); 16627 } 16628 16629 if (drawingWithRenderNode) { 16630 // Delay getting the display list until animation-driven alpha values are 16631 // set up and possibly passed on to the view 16632 renderNode = updateDisplayListIfDirty(); 16633 if (!renderNode.isValid()) { 16634 // Uncommon, but possible. If a view is removed from the hierarchy during the call 16635 // to getDisplayList(), the display list will be marked invalid and we should not 16636 // try to use it again. 16637 renderNode = null; 16638 drawingWithRenderNode = false; 16639 } 16640 } 16641 16642 int sx = 0; 16643 int sy = 0; 16644 if (!drawingWithRenderNode) { 16645 computeScroll(); 16646 sx = mScrollX; 16647 sy = mScrollY; 16648 } 16649 16650 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 16651 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 16652 16653 int restoreTo = -1; 16654 if (!drawingWithRenderNode || transformToApply != null) { 16655 restoreTo = canvas.save(); 16656 } 16657 if (offsetForScroll) { 16658 canvas.translate(mLeft - sx, mTop - sy); 16659 } else { 16660 if (!drawingWithRenderNode) { 16661 canvas.translate(mLeft, mTop); 16662 } 16663 if (scalingRequired) { 16664 if (drawingWithRenderNode) { 16665 // TODO: Might not need this if we put everything inside the DL 16666 restoreTo = canvas.save(); 16667 } 16668 // mAttachInfo cannot be null, otherwise scalingRequired == false 16669 final float scale = 1.0f / mAttachInfo.mApplicationScale; 16670 canvas.scale(scale, scale); 16671 } 16672 } 16673 16674 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 16675 if (transformToApply != null 16676 || alpha < 1 16677 || !hasIdentityMatrix() 16678 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16679 if (transformToApply != null || !childHasIdentityMatrix) { 16680 int transX = 0; 16681 int transY = 0; 16682 16683 if (offsetForScroll) { 16684 transX = -sx; 16685 transY = -sy; 16686 } 16687 16688 if (transformToApply != null) { 16689 if (concatMatrix) { 16690 if (drawingWithRenderNode) { 16691 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 16692 } else { 16693 // Undo the scroll translation, apply the transformation matrix, 16694 // then redo the scroll translate to get the correct result. 16695 canvas.translate(-transX, -transY); 16696 canvas.concat(transformToApply.getMatrix()); 16697 canvas.translate(transX, transY); 16698 } 16699 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16700 } 16701 16702 float transformAlpha = transformToApply.getAlpha(); 16703 if (transformAlpha < 1) { 16704 alpha *= transformAlpha; 16705 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16706 } 16707 } 16708 16709 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 16710 canvas.translate(-transX, -transY); 16711 canvas.concat(getMatrix()); 16712 canvas.translate(transX, transY); 16713 } 16714 } 16715 16716 // Deal with alpha if it is or used to be <1 16717 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 16718 if (alpha < 1) { 16719 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16720 } else { 16721 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 16722 } 16723 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 16724 if (!drawingWithDrawingCache) { 16725 final int multipliedAlpha = (int) (255 * alpha); 16726 if (!onSetAlpha(multipliedAlpha)) { 16727 if (drawingWithRenderNode) { 16728 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 16729 } else if (layerType == LAYER_TYPE_NONE) { 16730 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 16731 multipliedAlpha); 16732 } 16733 } else { 16734 // Alpha is handled by the child directly, clobber the layer's alpha 16735 mPrivateFlags |= PFLAG_ALPHA_SET; 16736 } 16737 } 16738 } 16739 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16740 onSetAlpha(255); 16741 mPrivateFlags &= ~PFLAG_ALPHA_SET; 16742 } 16743 16744 if (!drawingWithRenderNode) { 16745 // apply clips directly, since RenderNode won't do it for this draw 16746 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 16747 if (offsetForScroll) { 16748 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 16749 } else { 16750 if (!scalingRequired || cache == null) { 16751 canvas.clipRect(0, 0, getWidth(), getHeight()); 16752 } else { 16753 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 16754 } 16755 } 16756 } 16757 16758 if (mClipBounds != null) { 16759 // clip bounds ignore scroll 16760 canvas.clipRect(mClipBounds); 16761 } 16762 } 16763 16764 if (!drawingWithDrawingCache) { 16765 if (drawingWithRenderNode) { 16766 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16767 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 16768 } else { 16769 // Fast path for layouts with no backgrounds 16770 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 16771 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16772 dispatchDraw(canvas); 16773 } else { 16774 draw(canvas); 16775 } 16776 } 16777 } else if (cache != null) { 16778 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 16779 if (layerType == LAYER_TYPE_NONE) { 16780 // no layer paint, use temporary paint to draw bitmap 16781 Paint cachePaint = parent.mCachePaint; 16782 if (cachePaint == null) { 16783 cachePaint = new Paint(); 16784 cachePaint.setDither(false); 16785 parent.mCachePaint = cachePaint; 16786 } 16787 cachePaint.setAlpha((int) (alpha * 255)); 16788 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 16789 } else { 16790 // use layer paint to draw the bitmap, merging the two alphas, but also restore 16791 int layerPaintAlpha = mLayerPaint.getAlpha(); 16792 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 16793 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 16794 mLayerPaint.setAlpha(layerPaintAlpha); 16795 } 16796 } 16797 16798 if (restoreTo >= 0) { 16799 canvas.restoreToCount(restoreTo); 16800 } 16801 16802 if (a != null && !more) { 16803 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 16804 onSetAlpha(255); 16805 } 16806 parent.finishAnimatingView(this, a); 16807 } 16808 16809 if (more && hardwareAcceleratedCanvas) { 16810 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 16811 // alpha animations should cause the child to recreate its display list 16812 invalidate(true); 16813 } 16814 } 16815 16816 mRecreateDisplayList = false; 16817 16818 return more; 16819 } 16820 16821 /** 16822 * Manually render this view (and all of its children) to the given Canvas. 16823 * The view must have already done a full layout before this function is 16824 * called. When implementing a view, implement 16825 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 16826 * If you do need to override this method, call the superclass version. 16827 * 16828 * @param canvas The Canvas to which the View is rendered. 16829 */ 16830 @CallSuper 16831 public void draw(Canvas canvas) { 16832 final int privateFlags = mPrivateFlags; 16833 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 16834 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 16835 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 16836 16837 /* 16838 * Draw traversal performs several drawing steps which must be executed 16839 * in the appropriate order: 16840 * 16841 * 1. Draw the background 16842 * 2. If necessary, save the canvas' layers to prepare for fading 16843 * 3. Draw view's content 16844 * 4. Draw children 16845 * 5. If necessary, draw the fading edges and restore layers 16846 * 6. Draw decorations (scrollbars for instance) 16847 */ 16848 16849 // Step 1, draw the background, if needed 16850 int saveCount; 16851 16852 if (!dirtyOpaque) { 16853 drawBackground(canvas); 16854 } 16855 16856 // skip step 2 & 5 if possible (common case) 16857 final int viewFlags = mViewFlags; 16858 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 16859 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 16860 if (!verticalEdges && !horizontalEdges) { 16861 // Step 3, draw the content 16862 if (!dirtyOpaque) onDraw(canvas); 16863 16864 // Step 4, draw the children 16865 dispatchDraw(canvas); 16866 16867 // Overlay is part of the content and draws beneath Foreground 16868 if (mOverlay != null && !mOverlay.isEmpty()) { 16869 mOverlay.getOverlayView().dispatchDraw(canvas); 16870 } 16871 16872 // Step 6, draw decorations (foreground, scrollbars) 16873 onDrawForeground(canvas); 16874 16875 // we're done... 16876 return; 16877 } 16878 16879 /* 16880 * Here we do the full fledged routine... 16881 * (this is an uncommon case where speed matters less, 16882 * this is why we repeat some of the tests that have been 16883 * done above) 16884 */ 16885 16886 boolean drawTop = false; 16887 boolean drawBottom = false; 16888 boolean drawLeft = false; 16889 boolean drawRight = false; 16890 16891 float topFadeStrength = 0.0f; 16892 float bottomFadeStrength = 0.0f; 16893 float leftFadeStrength = 0.0f; 16894 float rightFadeStrength = 0.0f; 16895 16896 // Step 2, save the canvas' layers 16897 int paddingLeft = mPaddingLeft; 16898 16899 final boolean offsetRequired = isPaddingOffsetRequired(); 16900 if (offsetRequired) { 16901 paddingLeft += getLeftPaddingOffset(); 16902 } 16903 16904 int left = mScrollX + paddingLeft; 16905 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 16906 int top = mScrollY + getFadeTop(offsetRequired); 16907 int bottom = top + getFadeHeight(offsetRequired); 16908 16909 if (offsetRequired) { 16910 right += getRightPaddingOffset(); 16911 bottom += getBottomPaddingOffset(); 16912 } 16913 16914 final ScrollabilityCache scrollabilityCache = mScrollCache; 16915 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 16916 int length = (int) fadeHeight; 16917 16918 // clip the fade length if top and bottom fades overlap 16919 // overlapping fades produce odd-looking artifacts 16920 if (verticalEdges && (top + length > bottom - length)) { 16921 length = (bottom - top) / 2; 16922 } 16923 16924 // also clip horizontal fades if necessary 16925 if (horizontalEdges && (left + length > right - length)) { 16926 length = (right - left) / 2; 16927 } 16928 16929 if (verticalEdges) { 16930 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 16931 drawTop = topFadeStrength * fadeHeight > 1.0f; 16932 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 16933 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 16934 } 16935 16936 if (horizontalEdges) { 16937 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 16938 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 16939 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 16940 drawRight = rightFadeStrength * fadeHeight > 1.0f; 16941 } 16942 16943 saveCount = canvas.getSaveCount(); 16944 16945 int solidColor = getSolidColor(); 16946 if (solidColor == 0) { 16947 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 16948 16949 if (drawTop) { 16950 canvas.saveLayer(left, top, right, top + length, null, flags); 16951 } 16952 16953 if (drawBottom) { 16954 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 16955 } 16956 16957 if (drawLeft) { 16958 canvas.saveLayer(left, top, left + length, bottom, null, flags); 16959 } 16960 16961 if (drawRight) { 16962 canvas.saveLayer(right - length, top, right, bottom, null, flags); 16963 } 16964 } else { 16965 scrollabilityCache.setFadeColor(solidColor); 16966 } 16967 16968 // Step 3, draw the content 16969 if (!dirtyOpaque) onDraw(canvas); 16970 16971 // Step 4, draw the children 16972 dispatchDraw(canvas); 16973 16974 // Step 5, draw the fade effect and restore layers 16975 final Paint p = scrollabilityCache.paint; 16976 final Matrix matrix = scrollabilityCache.matrix; 16977 final Shader fade = scrollabilityCache.shader; 16978 16979 if (drawTop) { 16980 matrix.setScale(1, fadeHeight * topFadeStrength); 16981 matrix.postTranslate(left, top); 16982 fade.setLocalMatrix(matrix); 16983 p.setShader(fade); 16984 canvas.drawRect(left, top, right, top + length, p); 16985 } 16986 16987 if (drawBottom) { 16988 matrix.setScale(1, fadeHeight * bottomFadeStrength); 16989 matrix.postRotate(180); 16990 matrix.postTranslate(left, bottom); 16991 fade.setLocalMatrix(matrix); 16992 p.setShader(fade); 16993 canvas.drawRect(left, bottom - length, right, bottom, p); 16994 } 16995 16996 if (drawLeft) { 16997 matrix.setScale(1, fadeHeight * leftFadeStrength); 16998 matrix.postRotate(-90); 16999 matrix.postTranslate(left, top); 17000 fade.setLocalMatrix(matrix); 17001 p.setShader(fade); 17002 canvas.drawRect(left, top, left + length, bottom, p); 17003 } 17004 17005 if (drawRight) { 17006 matrix.setScale(1, fadeHeight * rightFadeStrength); 17007 matrix.postRotate(90); 17008 matrix.postTranslate(right, top); 17009 fade.setLocalMatrix(matrix); 17010 p.setShader(fade); 17011 canvas.drawRect(right - length, top, right, bottom, p); 17012 } 17013 17014 canvas.restoreToCount(saveCount); 17015 17016 // Overlay is part of the content and draws beneath Foreground 17017 if (mOverlay != null && !mOverlay.isEmpty()) { 17018 mOverlay.getOverlayView().dispatchDraw(canvas); 17019 } 17020 17021 // Step 6, draw decorations (foreground, scrollbars) 17022 onDrawForeground(canvas); 17023 } 17024 17025 /** 17026 * Draws the background onto the specified canvas. 17027 * 17028 * @param canvas Canvas on which to draw the background 17029 */ 17030 private void drawBackground(Canvas canvas) { 17031 final Drawable background = mBackground; 17032 if (background == null) { 17033 return; 17034 } 17035 17036 setBackgroundBounds(); 17037 17038 // Attempt to use a display list if requested. 17039 if (canvas.isHardwareAccelerated() && mAttachInfo != null 17040 && mAttachInfo.mHardwareRenderer != null) { 17041 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 17042 17043 final RenderNode renderNode = mBackgroundRenderNode; 17044 if (renderNode != null && renderNode.isValid()) { 17045 setBackgroundRenderNodeProperties(renderNode); 17046 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 17047 return; 17048 } 17049 } 17050 17051 final int scrollX = mScrollX; 17052 final int scrollY = mScrollY; 17053 if ((scrollX | scrollY) == 0) { 17054 background.draw(canvas); 17055 } else { 17056 canvas.translate(scrollX, scrollY); 17057 background.draw(canvas); 17058 canvas.translate(-scrollX, -scrollY); 17059 } 17060 } 17061 17062 /** 17063 * Sets the correct background bounds and rebuilds the outline, if needed. 17064 * <p/> 17065 * This is called by LayoutLib. 17066 */ 17067 void setBackgroundBounds() { 17068 if (mBackgroundSizeChanged && mBackground != null) { 17069 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 17070 mBackgroundSizeChanged = false; 17071 rebuildOutline(); 17072 } 17073 } 17074 17075 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 17076 renderNode.setTranslationX(mScrollX); 17077 renderNode.setTranslationY(mScrollY); 17078 } 17079 17080 /** 17081 * Creates a new display list or updates the existing display list for the 17082 * specified Drawable. 17083 * 17084 * @param drawable Drawable for which to create a display list 17085 * @param renderNode Existing RenderNode, or {@code null} 17086 * @return A valid display list for the specified drawable 17087 */ 17088 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 17089 if (renderNode == null) { 17090 renderNode = RenderNode.create(drawable.getClass().getName(), this); 17091 } 17092 17093 final Rect bounds = drawable.getBounds(); 17094 final int width = bounds.width(); 17095 final int height = bounds.height(); 17096 final DisplayListCanvas canvas = renderNode.start(width, height); 17097 17098 // Reverse left/top translation done by drawable canvas, which will 17099 // instead be applied by rendernode's LTRB bounds below. This way, the 17100 // drawable's bounds match with its rendernode bounds and its content 17101 // will lie within those bounds in the rendernode tree. 17102 canvas.translate(-bounds.left, -bounds.top); 17103 17104 try { 17105 drawable.draw(canvas); 17106 } finally { 17107 renderNode.end(canvas); 17108 } 17109 17110 // Set up drawable properties that are view-independent. 17111 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 17112 renderNode.setProjectBackwards(drawable.isProjected()); 17113 renderNode.setProjectionReceiver(true); 17114 renderNode.setClipToBounds(false); 17115 return renderNode; 17116 } 17117 17118 /** 17119 * Returns the overlay for this view, creating it if it does not yet exist. 17120 * Adding drawables to the overlay will cause them to be displayed whenever 17121 * the view itself is redrawn. Objects in the overlay should be actively 17122 * managed: remove them when they should not be displayed anymore. The 17123 * overlay will always have the same size as its host view. 17124 * 17125 * <p>Note: Overlays do not currently work correctly with {@link 17126 * SurfaceView} or {@link TextureView}; contents in overlays for these 17127 * types of views may not display correctly.</p> 17128 * 17129 * @return The ViewOverlay object for this view. 17130 * @see ViewOverlay 17131 */ 17132 public ViewOverlay getOverlay() { 17133 if (mOverlay == null) { 17134 mOverlay = new ViewOverlay(mContext, this); 17135 } 17136 return mOverlay; 17137 } 17138 17139 /** 17140 * Override this if your view is known to always be drawn on top of a solid color background, 17141 * and needs to draw fading edges. Returning a non-zero color enables the view system to 17142 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 17143 * should be set to 0xFF. 17144 * 17145 * @see #setVerticalFadingEdgeEnabled(boolean) 17146 * @see #setHorizontalFadingEdgeEnabled(boolean) 17147 * 17148 * @return The known solid color background for this view, or 0 if the color may vary 17149 */ 17150 @ViewDebug.ExportedProperty(category = "drawing") 17151 @ColorInt 17152 public int getSolidColor() { 17153 return 0; 17154 } 17155 17156 /** 17157 * Build a human readable string representation of the specified view flags. 17158 * 17159 * @param flags the view flags to convert to a string 17160 * @return a String representing the supplied flags 17161 */ 17162 private static String printFlags(int flags) { 17163 String output = ""; 17164 int numFlags = 0; 17165 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 17166 output += "TAKES_FOCUS"; 17167 numFlags++; 17168 } 17169 17170 switch (flags & VISIBILITY_MASK) { 17171 case INVISIBLE: 17172 if (numFlags > 0) { 17173 output += " "; 17174 } 17175 output += "INVISIBLE"; 17176 // USELESS HERE numFlags++; 17177 break; 17178 case GONE: 17179 if (numFlags > 0) { 17180 output += " "; 17181 } 17182 output += "GONE"; 17183 // USELESS HERE numFlags++; 17184 break; 17185 default: 17186 break; 17187 } 17188 return output; 17189 } 17190 17191 /** 17192 * Build a human readable string representation of the specified private 17193 * view flags. 17194 * 17195 * @param privateFlags the private view flags to convert to a string 17196 * @return a String representing the supplied flags 17197 */ 17198 private static String printPrivateFlags(int privateFlags) { 17199 String output = ""; 17200 int numFlags = 0; 17201 17202 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 17203 output += "WANTS_FOCUS"; 17204 numFlags++; 17205 } 17206 17207 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 17208 if (numFlags > 0) { 17209 output += " "; 17210 } 17211 output += "FOCUSED"; 17212 numFlags++; 17213 } 17214 17215 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 17216 if (numFlags > 0) { 17217 output += " "; 17218 } 17219 output += "SELECTED"; 17220 numFlags++; 17221 } 17222 17223 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 17224 if (numFlags > 0) { 17225 output += " "; 17226 } 17227 output += "IS_ROOT_NAMESPACE"; 17228 numFlags++; 17229 } 17230 17231 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 17232 if (numFlags > 0) { 17233 output += " "; 17234 } 17235 output += "HAS_BOUNDS"; 17236 numFlags++; 17237 } 17238 17239 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 17240 if (numFlags > 0) { 17241 output += " "; 17242 } 17243 output += "DRAWN"; 17244 // USELESS HERE numFlags++; 17245 } 17246 return output; 17247 } 17248 17249 /** 17250 * <p>Indicates whether or not this view's layout will be requested during 17251 * the next hierarchy layout pass.</p> 17252 * 17253 * @return true if the layout will be forced during next layout pass 17254 */ 17255 public boolean isLayoutRequested() { 17256 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 17257 } 17258 17259 /** 17260 * Return true if o is a ViewGroup that is laying out using optical bounds. 17261 * @hide 17262 */ 17263 public static boolean isLayoutModeOptical(Object o) { 17264 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 17265 } 17266 17267 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 17268 Insets parentInsets = mParent instanceof View ? 17269 ((View) mParent).getOpticalInsets() : Insets.NONE; 17270 Insets childInsets = getOpticalInsets(); 17271 return setFrame( 17272 left + parentInsets.left - childInsets.left, 17273 top + parentInsets.top - childInsets.top, 17274 right + parentInsets.left + childInsets.right, 17275 bottom + parentInsets.top + childInsets.bottom); 17276 } 17277 17278 /** 17279 * Assign a size and position to a view and all of its 17280 * descendants 17281 * 17282 * <p>This is the second phase of the layout mechanism. 17283 * (The first is measuring). In this phase, each parent calls 17284 * layout on all of its children to position them. 17285 * This is typically done using the child measurements 17286 * that were stored in the measure pass().</p> 17287 * 17288 * <p>Derived classes should not override this method. 17289 * Derived classes with children should override 17290 * onLayout. In that method, they should 17291 * call layout on each of their children.</p> 17292 * 17293 * @param l Left position, relative to parent 17294 * @param t Top position, relative to parent 17295 * @param r Right position, relative to parent 17296 * @param b Bottom position, relative to parent 17297 */ 17298 @SuppressWarnings({"unchecked"}) 17299 public void layout(int l, int t, int r, int b) { 17300 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 17301 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 17302 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17303 } 17304 17305 int oldL = mLeft; 17306 int oldT = mTop; 17307 int oldB = mBottom; 17308 int oldR = mRight; 17309 17310 boolean changed = isLayoutModeOptical(mParent) ? 17311 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 17312 17313 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 17314 onLayout(changed, l, t, r, b); 17315 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 17316 17317 ListenerInfo li = mListenerInfo; 17318 if (li != null && li.mOnLayoutChangeListeners != null) { 17319 ArrayList<OnLayoutChangeListener> listenersCopy = 17320 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 17321 int numListeners = listenersCopy.size(); 17322 for (int i = 0; i < numListeners; ++i) { 17323 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 17324 } 17325 } 17326 } 17327 17328 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 17329 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 17330 } 17331 17332 /** 17333 * Called from layout when this view should 17334 * assign a size and position to each of its children. 17335 * 17336 * Derived classes with children should override 17337 * this method and call layout on each of 17338 * their children. 17339 * @param changed This is a new size or position for this view 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 */ 17345 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 17346 } 17347 17348 /** 17349 * Assign a size and position to this view. 17350 * 17351 * This is called from layout. 17352 * 17353 * @param left Left position, relative to parent 17354 * @param top Top position, relative to parent 17355 * @param right Right position, relative to parent 17356 * @param bottom Bottom position, relative to parent 17357 * @return true if the new size and position are different than the 17358 * previous ones 17359 * {@hide} 17360 */ 17361 protected boolean setFrame(int left, int top, int right, int bottom) { 17362 boolean changed = false; 17363 17364 if (DBG) { 17365 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 17366 + right + "," + bottom + ")"); 17367 } 17368 17369 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 17370 changed = true; 17371 17372 // Remember our drawn bit 17373 int drawn = mPrivateFlags & PFLAG_DRAWN; 17374 17375 int oldWidth = mRight - mLeft; 17376 int oldHeight = mBottom - mTop; 17377 int newWidth = right - left; 17378 int newHeight = bottom - top; 17379 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 17380 17381 // Invalidate our old position 17382 invalidate(sizeChanged); 17383 17384 mLeft = left; 17385 mTop = top; 17386 mRight = right; 17387 mBottom = bottom; 17388 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 17389 17390 mPrivateFlags |= PFLAG_HAS_BOUNDS; 17391 17392 17393 if (sizeChanged) { 17394 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 17395 } 17396 17397 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 17398 // If we are visible, force the DRAWN bit to on so that 17399 // this invalidate will go through (at least to our parent). 17400 // This is because someone may have invalidated this view 17401 // before this call to setFrame came in, thereby clearing 17402 // the DRAWN bit. 17403 mPrivateFlags |= PFLAG_DRAWN; 17404 invalidate(sizeChanged); 17405 // parent display list may need to be recreated based on a change in the bounds 17406 // of any child 17407 invalidateParentCaches(); 17408 } 17409 17410 // Reset drawn bit to original value (invalidate turns it off) 17411 mPrivateFlags |= drawn; 17412 17413 mBackgroundSizeChanged = true; 17414 if (mForegroundInfo != null) { 17415 mForegroundInfo.mBoundsChanged = true; 17416 } 17417 17418 notifySubtreeAccessibilityStateChangedIfNeeded(); 17419 } 17420 return changed; 17421 } 17422 17423 /** 17424 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 17425 * @hide 17426 */ 17427 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 17428 setFrame(left, top, right, bottom); 17429 } 17430 17431 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 17432 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 17433 if (mOverlay != null) { 17434 mOverlay.getOverlayView().setRight(newWidth); 17435 mOverlay.getOverlayView().setBottom(newHeight); 17436 } 17437 rebuildOutline(); 17438 } 17439 17440 /** 17441 * Finalize inflating a view from XML. This is called as the last phase 17442 * of inflation, after all child views have been added. 17443 * 17444 * <p>Even if the subclass overrides onFinishInflate, they should always be 17445 * sure to call the super method, so that we get called. 17446 */ 17447 @CallSuper 17448 protected void onFinishInflate() { 17449 } 17450 17451 /** 17452 * Returns the resources associated with this view. 17453 * 17454 * @return Resources object. 17455 */ 17456 public Resources getResources() { 17457 return mResources; 17458 } 17459 17460 /** 17461 * Invalidates the specified Drawable. 17462 * 17463 * @param drawable the drawable to invalidate 17464 */ 17465 @Override 17466 public void invalidateDrawable(@NonNull Drawable drawable) { 17467 if (verifyDrawable(drawable)) { 17468 final Rect dirty = drawable.getDirtyBounds(); 17469 final int scrollX = mScrollX; 17470 final int scrollY = mScrollY; 17471 17472 invalidate(dirty.left + scrollX, dirty.top + scrollY, 17473 dirty.right + scrollX, dirty.bottom + scrollY); 17474 rebuildOutline(); 17475 } 17476 } 17477 17478 /** 17479 * Schedules an action on a drawable to occur at a specified time. 17480 * 17481 * @param who the recipient of the action 17482 * @param what the action to run on the drawable 17483 * @param when the time at which the action must occur. Uses the 17484 * {@link SystemClock#uptimeMillis} timebase. 17485 */ 17486 @Override 17487 public void scheduleDrawable(Drawable who, Runnable what, long when) { 17488 if (verifyDrawable(who) && what != null) { 17489 final long delay = when - SystemClock.uptimeMillis(); 17490 if (mAttachInfo != null) { 17491 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 17492 Choreographer.CALLBACK_ANIMATION, what, who, 17493 Choreographer.subtractFrameDelay(delay)); 17494 } else { 17495 // Postpone the runnable until we know 17496 // on which thread it needs to run. 17497 getRunQueue().postDelayed(what, delay); 17498 } 17499 } 17500 } 17501 17502 /** 17503 * Cancels a scheduled action on a drawable. 17504 * 17505 * @param who the recipient of the action 17506 * @param what the action to cancel 17507 */ 17508 @Override 17509 public void unscheduleDrawable(Drawable who, Runnable what) { 17510 if (verifyDrawable(who) && what != null) { 17511 if (mAttachInfo != null) { 17512 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17513 Choreographer.CALLBACK_ANIMATION, what, who); 17514 } 17515 getRunQueue().removeCallbacks(what); 17516 } 17517 } 17518 17519 /** 17520 * Unschedule any events associated with the given Drawable. This can be 17521 * used when selecting a new Drawable into a view, so that the previous 17522 * one is completely unscheduled. 17523 * 17524 * @param who The Drawable to unschedule. 17525 * 17526 * @see #drawableStateChanged 17527 */ 17528 public void unscheduleDrawable(Drawable who) { 17529 if (mAttachInfo != null && who != null) { 17530 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 17531 Choreographer.CALLBACK_ANIMATION, null, who); 17532 } 17533 } 17534 17535 /** 17536 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 17537 * that the View directionality can and will be resolved before its Drawables. 17538 * 17539 * Will call {@link View#onResolveDrawables} when resolution is done. 17540 * 17541 * @hide 17542 */ 17543 protected void resolveDrawables() { 17544 // Drawables resolution may need to happen before resolving the layout direction (which is 17545 // done only during the measure() call). 17546 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 17547 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 17548 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 17549 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 17550 // direction to be resolved as its resolved value will be the same as its raw value. 17551 if (!isLayoutDirectionResolved() && 17552 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 17553 return; 17554 } 17555 17556 final int layoutDirection = isLayoutDirectionResolved() ? 17557 getLayoutDirection() : getRawLayoutDirection(); 17558 17559 if (mBackground != null) { 17560 mBackground.setLayoutDirection(layoutDirection); 17561 } 17562 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17563 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 17564 } 17565 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 17566 onResolveDrawables(layoutDirection); 17567 } 17568 17569 boolean areDrawablesResolved() { 17570 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 17571 } 17572 17573 /** 17574 * Called when layout direction has been resolved. 17575 * 17576 * The default implementation does nothing. 17577 * 17578 * @param layoutDirection The resolved layout direction. 17579 * 17580 * @see #LAYOUT_DIRECTION_LTR 17581 * @see #LAYOUT_DIRECTION_RTL 17582 * 17583 * @hide 17584 */ 17585 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 17586 } 17587 17588 /** 17589 * @hide 17590 */ 17591 protected void resetResolvedDrawables() { 17592 resetResolvedDrawablesInternal(); 17593 } 17594 17595 void resetResolvedDrawablesInternal() { 17596 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 17597 } 17598 17599 /** 17600 * If your view subclass is displaying its own Drawable objects, it should 17601 * override this function and return true for any Drawable it is 17602 * displaying. This allows animations for those drawables to be 17603 * scheduled. 17604 * 17605 * <p>Be sure to call through to the super class when overriding this 17606 * function. 17607 * 17608 * @param who The Drawable to verify. Return true if it is one you are 17609 * displaying, else return the result of calling through to the 17610 * super class. 17611 * 17612 * @return boolean If true than the Drawable is being displayed in the 17613 * view; else false and it is not allowed to animate. 17614 * 17615 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 17616 * @see #drawableStateChanged() 17617 */ 17618 @CallSuper 17619 protected boolean verifyDrawable(Drawable who) { 17620 // Avoid verifying the scroll bar drawable so that we don't end up in 17621 // an invalidation loop. This effectively prevents the scroll bar 17622 // drawable from triggering invalidations and scheduling runnables. 17623 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who); 17624 } 17625 17626 /** 17627 * This function is called whenever the state of the view changes in such 17628 * a way that it impacts the state of drawables being shown. 17629 * <p> 17630 * If the View has a StateListAnimator, it will also be called to run necessary state 17631 * change animations. 17632 * <p> 17633 * Be sure to call through to the superclass when overriding this function. 17634 * 17635 * @see Drawable#setState(int[]) 17636 */ 17637 @CallSuper 17638 protected void drawableStateChanged() { 17639 final int[] state = getDrawableState(); 17640 boolean changed = false; 17641 17642 final Drawable bg = mBackground; 17643 if (bg != null && bg.isStateful()) { 17644 changed |= bg.setState(state); 17645 } 17646 17647 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 17648 if (fg != null && fg.isStateful()) { 17649 changed |= fg.setState(state); 17650 } 17651 17652 if (mScrollCache != null) { 17653 final Drawable scrollBar = mScrollCache.scrollBar; 17654 if (scrollBar != null && scrollBar.isStateful()) { 17655 changed |= scrollBar.setState(state) 17656 && mScrollCache.state != ScrollabilityCache.OFF; 17657 } 17658 } 17659 17660 if (mStateListAnimator != null) { 17661 mStateListAnimator.setState(state); 17662 } 17663 17664 if (changed) { 17665 invalidate(); 17666 } 17667 } 17668 17669 /** 17670 * This function is called whenever the view hotspot changes and needs to 17671 * be propagated to drawables or child views managed by the view. 17672 * <p> 17673 * Dispatching to child views is handled by 17674 * {@link #dispatchDrawableHotspotChanged(float, float)}. 17675 * <p> 17676 * Be sure to call through to the superclass when overriding this function. 17677 * 17678 * @param x hotspot x coordinate 17679 * @param y hotspot y coordinate 17680 */ 17681 @CallSuper 17682 public void drawableHotspotChanged(float x, float y) { 17683 if (mBackground != null) { 17684 mBackground.setHotspot(x, y); 17685 } 17686 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17687 mForegroundInfo.mDrawable.setHotspot(x, y); 17688 } 17689 17690 dispatchDrawableHotspotChanged(x, y); 17691 } 17692 17693 /** 17694 * Dispatches drawableHotspotChanged to all of this View's children. 17695 * 17696 * @param x hotspot x coordinate 17697 * @param y hotspot y coordinate 17698 * @see #drawableHotspotChanged(float, float) 17699 */ 17700 public void dispatchDrawableHotspotChanged(float x, float y) { 17701 } 17702 17703 /** 17704 * Call this to force a view to update its drawable state. This will cause 17705 * drawableStateChanged to be called on this view. Views that are interested 17706 * in the new state should call getDrawableState. 17707 * 17708 * @see #drawableStateChanged 17709 * @see #getDrawableState 17710 */ 17711 public void refreshDrawableState() { 17712 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 17713 drawableStateChanged(); 17714 17715 ViewParent parent = mParent; 17716 if (parent != null) { 17717 parent.childDrawableStateChanged(this); 17718 } 17719 } 17720 17721 /** 17722 * Return an array of resource IDs of the drawable states representing the 17723 * current state of the view. 17724 * 17725 * @return The current drawable state 17726 * 17727 * @see Drawable#setState(int[]) 17728 * @see #drawableStateChanged() 17729 * @see #onCreateDrawableState(int) 17730 */ 17731 public final int[] getDrawableState() { 17732 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 17733 return mDrawableState; 17734 } else { 17735 mDrawableState = onCreateDrawableState(0); 17736 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 17737 return mDrawableState; 17738 } 17739 } 17740 17741 /** 17742 * Generate the new {@link android.graphics.drawable.Drawable} state for 17743 * this view. This is called by the view 17744 * system when the cached Drawable state is determined to be invalid. To 17745 * retrieve the current state, you should use {@link #getDrawableState}. 17746 * 17747 * @param extraSpace if non-zero, this is the number of extra entries you 17748 * would like in the returned array in which you can place your own 17749 * states. 17750 * 17751 * @return Returns an array holding the current {@link Drawable} state of 17752 * the view. 17753 * 17754 * @see #mergeDrawableStates(int[], int[]) 17755 */ 17756 protected int[] onCreateDrawableState(int extraSpace) { 17757 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 17758 mParent instanceof View) { 17759 return ((View) mParent).onCreateDrawableState(extraSpace); 17760 } 17761 17762 int[] drawableState; 17763 17764 int privateFlags = mPrivateFlags; 17765 17766 int viewStateIndex = 0; 17767 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 17768 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 17769 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 17770 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 17771 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 17772 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 17773 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 17774 ThreadedRenderer.isAvailable()) { 17775 // This is set if HW acceleration is requested, even if the current 17776 // process doesn't allow it. This is just to allow app preview 17777 // windows to better match their app. 17778 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 17779 } 17780 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 17781 17782 final int privateFlags2 = mPrivateFlags2; 17783 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 17784 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 17785 } 17786 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 17787 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 17788 } 17789 17790 drawableState = StateSet.get(viewStateIndex); 17791 17792 //noinspection ConstantIfStatement 17793 if (false) { 17794 Log.i("View", "drawableStateIndex=" + viewStateIndex); 17795 Log.i("View", toString() 17796 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 17797 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 17798 + " fo=" + hasFocus() 17799 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 17800 + " wf=" + hasWindowFocus() 17801 + ": " + Arrays.toString(drawableState)); 17802 } 17803 17804 if (extraSpace == 0) { 17805 return drawableState; 17806 } 17807 17808 final int[] fullState; 17809 if (drawableState != null) { 17810 fullState = new int[drawableState.length + extraSpace]; 17811 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 17812 } else { 17813 fullState = new int[extraSpace]; 17814 } 17815 17816 return fullState; 17817 } 17818 17819 /** 17820 * Merge your own state values in <var>additionalState</var> into the base 17821 * state values <var>baseState</var> that were returned by 17822 * {@link #onCreateDrawableState(int)}. 17823 * 17824 * @param baseState The base state values returned by 17825 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 17826 * own additional state values. 17827 * 17828 * @param additionalState The additional state values you would like 17829 * added to <var>baseState</var>; this array is not modified. 17830 * 17831 * @return As a convenience, the <var>baseState</var> array you originally 17832 * passed into the function is returned. 17833 * 17834 * @see #onCreateDrawableState(int) 17835 */ 17836 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 17837 final int N = baseState.length; 17838 int i = N - 1; 17839 while (i >= 0 && baseState[i] == 0) { 17840 i--; 17841 } 17842 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 17843 return baseState; 17844 } 17845 17846 /** 17847 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 17848 * on all Drawable objects associated with this view. 17849 * <p> 17850 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 17851 * attached to this view. 17852 */ 17853 @CallSuper 17854 public void jumpDrawablesToCurrentState() { 17855 if (mBackground != null) { 17856 mBackground.jumpToCurrentState(); 17857 } 17858 if (mStateListAnimator != null) { 17859 mStateListAnimator.jumpToCurrentState(); 17860 } 17861 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 17862 mForegroundInfo.mDrawable.jumpToCurrentState(); 17863 } 17864 } 17865 17866 /** 17867 * Sets the background color for this view. 17868 * @param color the color of the background 17869 */ 17870 @RemotableViewMethod 17871 public void setBackgroundColor(@ColorInt int color) { 17872 if (mBackground instanceof ColorDrawable) { 17873 ((ColorDrawable) mBackground.mutate()).setColor(color); 17874 computeOpaqueFlags(); 17875 mBackgroundResource = 0; 17876 } else { 17877 setBackground(new ColorDrawable(color)); 17878 } 17879 } 17880 17881 /** 17882 * Set the background to a given resource. The resource should refer to 17883 * a Drawable object or 0 to remove the background. 17884 * @param resid The identifier of the resource. 17885 * 17886 * @attr ref android.R.styleable#View_background 17887 */ 17888 @RemotableViewMethod 17889 public void setBackgroundResource(@DrawableRes int resid) { 17890 if (resid != 0 && resid == mBackgroundResource) { 17891 return; 17892 } 17893 17894 Drawable d = null; 17895 if (resid != 0) { 17896 d = mContext.getDrawable(resid); 17897 } 17898 setBackground(d); 17899 17900 mBackgroundResource = resid; 17901 } 17902 17903 /** 17904 * Set the background to a given Drawable, or remove the background. If the 17905 * background has padding, this View's padding is set to the background's 17906 * padding. However, when a background is removed, this View's padding isn't 17907 * touched. If setting the padding is desired, please use 17908 * {@link #setPadding(int, int, int, int)}. 17909 * 17910 * @param background The Drawable to use as the background, or null to remove the 17911 * background 17912 */ 17913 public void setBackground(Drawable background) { 17914 //noinspection deprecation 17915 setBackgroundDrawable(background); 17916 } 17917 17918 /** 17919 * @deprecated use {@link #setBackground(Drawable)} instead 17920 */ 17921 @Deprecated 17922 public void setBackgroundDrawable(Drawable background) { 17923 computeOpaqueFlags(); 17924 17925 if (background == mBackground) { 17926 return; 17927 } 17928 17929 boolean requestLayout = false; 17930 17931 mBackgroundResource = 0; 17932 17933 /* 17934 * Regardless of whether we're setting a new background or not, we want 17935 * to clear the previous drawable. 17936 */ 17937 if (mBackground != null) { 17938 mBackground.setCallback(null); 17939 unscheduleDrawable(mBackground); 17940 } 17941 17942 if (background != null) { 17943 Rect padding = sThreadLocal.get(); 17944 if (padding == null) { 17945 padding = new Rect(); 17946 sThreadLocal.set(padding); 17947 } 17948 resetResolvedDrawablesInternal(); 17949 background.setLayoutDirection(getLayoutDirection()); 17950 if (background.getPadding(padding)) { 17951 resetResolvedPaddingInternal(); 17952 switch (background.getLayoutDirection()) { 17953 case LAYOUT_DIRECTION_RTL: 17954 mUserPaddingLeftInitial = padding.right; 17955 mUserPaddingRightInitial = padding.left; 17956 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 17957 break; 17958 case LAYOUT_DIRECTION_LTR: 17959 default: 17960 mUserPaddingLeftInitial = padding.left; 17961 mUserPaddingRightInitial = padding.right; 17962 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 17963 } 17964 mLeftPaddingDefined = false; 17965 mRightPaddingDefined = false; 17966 } 17967 17968 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 17969 // if it has a different minimum size, we should layout again 17970 if (mBackground == null 17971 || mBackground.getMinimumHeight() != background.getMinimumHeight() 17972 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 17973 requestLayout = true; 17974 } 17975 17976 background.setCallback(this); 17977 if (background.isStateful()) { 17978 background.setState(getDrawableState()); 17979 } 17980 background.setVisible(getVisibility() == VISIBLE, false); 17981 mBackground = background; 17982 17983 applyBackgroundTint(); 17984 17985 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 17986 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 17987 requestLayout = true; 17988 } 17989 } else { 17990 /* Remove the background */ 17991 mBackground = null; 17992 if ((mViewFlags & WILL_NOT_DRAW) != 0 17993 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 17994 mPrivateFlags |= PFLAG_SKIP_DRAW; 17995 } 17996 17997 /* 17998 * When the background is set, we try to apply its padding to this 17999 * View. When the background is removed, we don't touch this View's 18000 * padding. This is noted in the Javadocs. Hence, we don't need to 18001 * requestLayout(), the invalidate() below is sufficient. 18002 */ 18003 18004 // The old background's minimum size could have affected this 18005 // View's layout, so let's requestLayout 18006 requestLayout = true; 18007 } 18008 18009 computeOpaqueFlags(); 18010 18011 if (requestLayout) { 18012 requestLayout(); 18013 } 18014 18015 mBackgroundSizeChanged = true; 18016 invalidate(true); 18017 } 18018 18019 /** 18020 * Gets the background drawable 18021 * 18022 * @return The drawable used as the background for this view, if any. 18023 * 18024 * @see #setBackground(Drawable) 18025 * 18026 * @attr ref android.R.styleable#View_background 18027 */ 18028 public Drawable getBackground() { 18029 return mBackground; 18030 } 18031 18032 /** 18033 * Applies a tint to the background drawable. Does not modify the current tint 18034 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18035 * <p> 18036 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 18037 * mutate the drawable and apply the specified tint and tint mode using 18038 * {@link Drawable#setTintList(ColorStateList)}. 18039 * 18040 * @param tint the tint to apply, may be {@code null} to clear tint 18041 * 18042 * @attr ref android.R.styleable#View_backgroundTint 18043 * @see #getBackgroundTintList() 18044 * @see Drawable#setTintList(ColorStateList) 18045 */ 18046 public void setBackgroundTintList(@Nullable ColorStateList tint) { 18047 if (mBackgroundTint == null) { 18048 mBackgroundTint = new TintInfo(); 18049 } 18050 mBackgroundTint.mTintList = tint; 18051 mBackgroundTint.mHasTintList = true; 18052 18053 applyBackgroundTint(); 18054 } 18055 18056 /** 18057 * Return the tint applied to the background drawable, if specified. 18058 * 18059 * @return the tint applied to the background drawable 18060 * @attr ref android.R.styleable#View_backgroundTint 18061 * @see #setBackgroundTintList(ColorStateList) 18062 */ 18063 @Nullable 18064 public ColorStateList getBackgroundTintList() { 18065 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 18066 } 18067 18068 /** 18069 * Specifies the blending mode used to apply the tint specified by 18070 * {@link #setBackgroundTintList(ColorStateList)}} to the background 18071 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18072 * 18073 * @param tintMode the blending mode used to apply the tint, may be 18074 * {@code null} to clear tint 18075 * @attr ref android.R.styleable#View_backgroundTintMode 18076 * @see #getBackgroundTintMode() 18077 * @see Drawable#setTintMode(PorterDuff.Mode) 18078 */ 18079 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18080 if (mBackgroundTint == null) { 18081 mBackgroundTint = new TintInfo(); 18082 } 18083 mBackgroundTint.mTintMode = tintMode; 18084 mBackgroundTint.mHasTintMode = true; 18085 18086 applyBackgroundTint(); 18087 } 18088 18089 /** 18090 * Return the blending mode used to apply the tint to the background 18091 * drawable, if specified. 18092 * 18093 * @return the blending mode used to apply the tint to the background 18094 * drawable 18095 * @attr ref android.R.styleable#View_backgroundTintMode 18096 * @see #setBackgroundTintMode(PorterDuff.Mode) 18097 */ 18098 @Nullable 18099 public PorterDuff.Mode getBackgroundTintMode() { 18100 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 18101 } 18102 18103 private void applyBackgroundTint() { 18104 if (mBackground != null && mBackgroundTint != null) { 18105 final TintInfo tintInfo = mBackgroundTint; 18106 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18107 mBackground = mBackground.mutate(); 18108 18109 if (tintInfo.mHasTintList) { 18110 mBackground.setTintList(tintInfo.mTintList); 18111 } 18112 18113 if (tintInfo.mHasTintMode) { 18114 mBackground.setTintMode(tintInfo.mTintMode); 18115 } 18116 18117 // The drawable (or one of its children) may not have been 18118 // stateful before applying the tint, so let's try again. 18119 if (mBackground.isStateful()) { 18120 mBackground.setState(getDrawableState()); 18121 } 18122 } 18123 } 18124 } 18125 18126 /** 18127 * Returns the drawable used as the foreground of this View. The 18128 * foreground drawable, if non-null, is always drawn on top of the view's content. 18129 * 18130 * @return a Drawable or null if no foreground was set 18131 * 18132 * @see #onDrawForeground(Canvas) 18133 */ 18134 public Drawable getForeground() { 18135 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18136 } 18137 18138 /** 18139 * Supply a Drawable that is to be rendered on top of all of the content in the view. 18140 * 18141 * @param foreground the Drawable to be drawn on top of the children 18142 * 18143 * @attr ref android.R.styleable#View_foreground 18144 */ 18145 public void setForeground(Drawable foreground) { 18146 if (mForegroundInfo == null) { 18147 if (foreground == null) { 18148 // Nothing to do. 18149 return; 18150 } 18151 mForegroundInfo = new ForegroundInfo(); 18152 } 18153 18154 if (foreground == mForegroundInfo.mDrawable) { 18155 // Nothing to do 18156 return; 18157 } 18158 18159 if (mForegroundInfo.mDrawable != null) { 18160 mForegroundInfo.mDrawable.setCallback(null); 18161 unscheduleDrawable(mForegroundInfo.mDrawable); 18162 } 18163 18164 mForegroundInfo.mDrawable = foreground; 18165 mForegroundInfo.mBoundsChanged = true; 18166 if (foreground != null) { 18167 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 18168 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 18169 } 18170 foreground.setCallback(this); 18171 foreground.setLayoutDirection(getLayoutDirection()); 18172 if (foreground.isStateful()) { 18173 foreground.setState(getDrawableState()); 18174 } 18175 applyForegroundTint(); 18176 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { 18177 mPrivateFlags |= PFLAG_SKIP_DRAW; 18178 } 18179 requestLayout(); 18180 invalidate(); 18181 } 18182 18183 /** 18184 * Magic bit used to support features of framework-internal window decor implementation details. 18185 * This used to live exclusively in FrameLayout. 18186 * 18187 * @return true if the foreground should draw inside the padding region or false 18188 * if it should draw inset by the view's padding 18189 * @hide internal use only; only used by FrameLayout and internal screen layouts. 18190 */ 18191 public boolean isForegroundInsidePadding() { 18192 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 18193 } 18194 18195 /** 18196 * Describes how the foreground is positioned. 18197 * 18198 * @return foreground gravity. 18199 * 18200 * @see #setForegroundGravity(int) 18201 * 18202 * @attr ref android.R.styleable#View_foregroundGravity 18203 */ 18204 public int getForegroundGravity() { 18205 return mForegroundInfo != null ? mForegroundInfo.mGravity 18206 : Gravity.START | Gravity.TOP; 18207 } 18208 18209 /** 18210 * Describes how the foreground is positioned. Defaults to START and TOP. 18211 * 18212 * @param gravity see {@link android.view.Gravity} 18213 * 18214 * @see #getForegroundGravity() 18215 * 18216 * @attr ref android.R.styleable#View_foregroundGravity 18217 */ 18218 public void setForegroundGravity(int gravity) { 18219 if (mForegroundInfo == null) { 18220 mForegroundInfo = new ForegroundInfo(); 18221 } 18222 18223 if (mForegroundInfo.mGravity != gravity) { 18224 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 18225 gravity |= Gravity.START; 18226 } 18227 18228 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 18229 gravity |= Gravity.TOP; 18230 } 18231 18232 mForegroundInfo.mGravity = gravity; 18233 requestLayout(); 18234 } 18235 } 18236 18237 /** 18238 * Applies a tint to the foreground drawable. Does not modify the current tint 18239 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 18240 * <p> 18241 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 18242 * mutate the drawable and apply the specified tint and tint mode using 18243 * {@link Drawable#setTintList(ColorStateList)}. 18244 * 18245 * @param tint the tint to apply, may be {@code null} to clear tint 18246 * 18247 * @attr ref android.R.styleable#View_foregroundTint 18248 * @see #getForegroundTintList() 18249 * @see Drawable#setTintList(ColorStateList) 18250 */ 18251 public void setForegroundTintList(@Nullable ColorStateList tint) { 18252 if (mForegroundInfo == null) { 18253 mForegroundInfo = new ForegroundInfo(); 18254 } 18255 if (mForegroundInfo.mTintInfo == null) { 18256 mForegroundInfo.mTintInfo = new TintInfo(); 18257 } 18258 mForegroundInfo.mTintInfo.mTintList = tint; 18259 mForegroundInfo.mTintInfo.mHasTintList = true; 18260 18261 applyForegroundTint(); 18262 } 18263 18264 /** 18265 * Return the tint applied to the foreground drawable, if specified. 18266 * 18267 * @return the tint applied to the foreground drawable 18268 * @attr ref android.R.styleable#View_foregroundTint 18269 * @see #setForegroundTintList(ColorStateList) 18270 */ 18271 @Nullable 18272 public ColorStateList getForegroundTintList() { 18273 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18274 ? mForegroundInfo.mTintInfo.mTintList : null; 18275 } 18276 18277 /** 18278 * Specifies the blending mode used to apply the tint specified by 18279 * {@link #setForegroundTintList(ColorStateList)}} to the background 18280 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 18281 * 18282 * @param tintMode the blending mode used to apply the tint, may be 18283 * {@code null} to clear tint 18284 * @attr ref android.R.styleable#View_foregroundTintMode 18285 * @see #getForegroundTintMode() 18286 * @see Drawable#setTintMode(PorterDuff.Mode) 18287 */ 18288 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 18289 if (mForegroundInfo == null) { 18290 mForegroundInfo = new ForegroundInfo(); 18291 } 18292 if (mForegroundInfo.mTintInfo == null) { 18293 mForegroundInfo.mTintInfo = new TintInfo(); 18294 } 18295 mForegroundInfo.mTintInfo.mTintMode = tintMode; 18296 mForegroundInfo.mTintInfo.mHasTintMode = true; 18297 18298 applyForegroundTint(); 18299 } 18300 18301 /** 18302 * Return the blending mode used to apply the tint to the foreground 18303 * drawable, if specified. 18304 * 18305 * @return the blending mode used to apply the tint to the foreground 18306 * drawable 18307 * @attr ref android.R.styleable#View_foregroundTintMode 18308 * @see #setForegroundTintMode(PorterDuff.Mode) 18309 */ 18310 @Nullable 18311 public PorterDuff.Mode getForegroundTintMode() { 18312 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 18313 ? mForegroundInfo.mTintInfo.mTintMode : null; 18314 } 18315 18316 private void applyForegroundTint() { 18317 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 18318 && mForegroundInfo.mTintInfo != null) { 18319 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 18320 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 18321 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 18322 18323 if (tintInfo.mHasTintList) { 18324 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 18325 } 18326 18327 if (tintInfo.mHasTintMode) { 18328 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 18329 } 18330 18331 // The drawable (or one of its children) may not have been 18332 // stateful before applying the tint, so let's try again. 18333 if (mForegroundInfo.mDrawable.isStateful()) { 18334 mForegroundInfo.mDrawable.setState(getDrawableState()); 18335 } 18336 } 18337 } 18338 } 18339 18340 /** 18341 * Draw any foreground content for this view. 18342 * 18343 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 18344 * drawable or other view-specific decorations. The foreground is drawn on top of the 18345 * primary view content.</p> 18346 * 18347 * @param canvas canvas to draw into 18348 */ 18349 public void onDrawForeground(Canvas canvas) { 18350 onDrawScrollIndicators(canvas); 18351 onDrawScrollBars(canvas); 18352 18353 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 18354 if (foreground != null) { 18355 if (mForegroundInfo.mBoundsChanged) { 18356 mForegroundInfo.mBoundsChanged = false; 18357 final Rect selfBounds = mForegroundInfo.mSelfBounds; 18358 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 18359 18360 if (mForegroundInfo.mInsidePadding) { 18361 selfBounds.set(0, 0, getWidth(), getHeight()); 18362 } else { 18363 selfBounds.set(getPaddingLeft(), getPaddingTop(), 18364 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 18365 } 18366 18367 final int ld = getLayoutDirection(); 18368 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 18369 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 18370 foreground.setBounds(overlayBounds); 18371 } 18372 18373 foreground.draw(canvas); 18374 } 18375 } 18376 18377 /** 18378 * Sets the padding. The view may add on the space required to display 18379 * the scrollbars, depending on the style and visibility of the scrollbars. 18380 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 18381 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 18382 * from the values set in this call. 18383 * 18384 * @attr ref android.R.styleable#View_padding 18385 * @attr ref android.R.styleable#View_paddingBottom 18386 * @attr ref android.R.styleable#View_paddingLeft 18387 * @attr ref android.R.styleable#View_paddingRight 18388 * @attr ref android.R.styleable#View_paddingTop 18389 * @param left the left padding in pixels 18390 * @param top the top padding in pixels 18391 * @param right the right padding in pixels 18392 * @param bottom the bottom padding in pixels 18393 */ 18394 public void setPadding(int left, int top, int right, int bottom) { 18395 resetResolvedPaddingInternal(); 18396 18397 mUserPaddingStart = UNDEFINED_PADDING; 18398 mUserPaddingEnd = UNDEFINED_PADDING; 18399 18400 mUserPaddingLeftInitial = left; 18401 mUserPaddingRightInitial = right; 18402 18403 mLeftPaddingDefined = true; 18404 mRightPaddingDefined = true; 18405 18406 internalSetPadding(left, top, right, bottom); 18407 } 18408 18409 /** 18410 * @hide 18411 */ 18412 protected void internalSetPadding(int left, int top, int right, int bottom) { 18413 mUserPaddingLeft = left; 18414 mUserPaddingRight = right; 18415 mUserPaddingBottom = bottom; 18416 18417 final int viewFlags = mViewFlags; 18418 boolean changed = false; 18419 18420 // Common case is there are no scroll bars. 18421 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 18422 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 18423 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 18424 ? 0 : getVerticalScrollbarWidth(); 18425 switch (mVerticalScrollbarPosition) { 18426 case SCROLLBAR_POSITION_DEFAULT: 18427 if (isLayoutRtl()) { 18428 left += offset; 18429 } else { 18430 right += offset; 18431 } 18432 break; 18433 case SCROLLBAR_POSITION_RIGHT: 18434 right += offset; 18435 break; 18436 case SCROLLBAR_POSITION_LEFT: 18437 left += offset; 18438 break; 18439 } 18440 } 18441 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 18442 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 18443 ? 0 : getHorizontalScrollbarHeight(); 18444 } 18445 } 18446 18447 if (mPaddingLeft != left) { 18448 changed = true; 18449 mPaddingLeft = left; 18450 } 18451 if (mPaddingTop != top) { 18452 changed = true; 18453 mPaddingTop = top; 18454 } 18455 if (mPaddingRight != right) { 18456 changed = true; 18457 mPaddingRight = right; 18458 } 18459 if (mPaddingBottom != bottom) { 18460 changed = true; 18461 mPaddingBottom = bottom; 18462 } 18463 18464 if (changed) { 18465 requestLayout(); 18466 invalidateOutline(); 18467 } 18468 } 18469 18470 /** 18471 * Sets the relative padding. The view may add on the space required to display 18472 * the scrollbars, depending on the style and visibility of the scrollbars. 18473 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 18474 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 18475 * from the values set in this call. 18476 * 18477 * @attr ref android.R.styleable#View_padding 18478 * @attr ref android.R.styleable#View_paddingBottom 18479 * @attr ref android.R.styleable#View_paddingStart 18480 * @attr ref android.R.styleable#View_paddingEnd 18481 * @attr ref android.R.styleable#View_paddingTop 18482 * @param start the start padding in pixels 18483 * @param top the top padding in pixels 18484 * @param end the end padding in pixels 18485 * @param bottom the bottom padding in pixels 18486 */ 18487 public void setPaddingRelative(int start, int top, int end, int bottom) { 18488 resetResolvedPaddingInternal(); 18489 18490 mUserPaddingStart = start; 18491 mUserPaddingEnd = end; 18492 mLeftPaddingDefined = true; 18493 mRightPaddingDefined = true; 18494 18495 switch(getLayoutDirection()) { 18496 case LAYOUT_DIRECTION_RTL: 18497 mUserPaddingLeftInitial = end; 18498 mUserPaddingRightInitial = start; 18499 internalSetPadding(end, top, start, bottom); 18500 break; 18501 case LAYOUT_DIRECTION_LTR: 18502 default: 18503 mUserPaddingLeftInitial = start; 18504 mUserPaddingRightInitial = end; 18505 internalSetPadding(start, top, end, bottom); 18506 } 18507 } 18508 18509 /** 18510 * Returns the top padding of this view. 18511 * 18512 * @return the top padding in pixels 18513 */ 18514 public int getPaddingTop() { 18515 return mPaddingTop; 18516 } 18517 18518 /** 18519 * Returns the bottom padding of this view. If there are inset and enabled 18520 * scrollbars, this value may include the space required to display the 18521 * scrollbars as well. 18522 * 18523 * @return the bottom padding in pixels 18524 */ 18525 public int getPaddingBottom() { 18526 return mPaddingBottom; 18527 } 18528 18529 /** 18530 * Returns the left padding of this view. If there are inset and enabled 18531 * scrollbars, this value may include the space required to display the 18532 * scrollbars as well. 18533 * 18534 * @return the left padding in pixels 18535 */ 18536 public int getPaddingLeft() { 18537 if (!isPaddingResolved()) { 18538 resolvePadding(); 18539 } 18540 return mPaddingLeft; 18541 } 18542 18543 /** 18544 * Returns the start padding of this view depending on its resolved layout direction. 18545 * If there are inset and enabled scrollbars, this value may include the space 18546 * required to display the scrollbars as well. 18547 * 18548 * @return the start padding in pixels 18549 */ 18550 public int getPaddingStart() { 18551 if (!isPaddingResolved()) { 18552 resolvePadding(); 18553 } 18554 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18555 mPaddingRight : mPaddingLeft; 18556 } 18557 18558 /** 18559 * Returns the right padding of this view. If there are inset and enabled 18560 * scrollbars, this value may include the space required to display the 18561 * scrollbars as well. 18562 * 18563 * @return the right padding in pixels 18564 */ 18565 public int getPaddingRight() { 18566 if (!isPaddingResolved()) { 18567 resolvePadding(); 18568 } 18569 return mPaddingRight; 18570 } 18571 18572 /** 18573 * Returns the end padding of this view depending on its resolved layout direction. 18574 * If there are inset and enabled scrollbars, this value may include the space 18575 * required to display the scrollbars as well. 18576 * 18577 * @return the end padding in pixels 18578 */ 18579 public int getPaddingEnd() { 18580 if (!isPaddingResolved()) { 18581 resolvePadding(); 18582 } 18583 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 18584 mPaddingLeft : mPaddingRight; 18585 } 18586 18587 /** 18588 * Return if the padding has been set through relative values 18589 * {@link #setPaddingRelative(int, int, int, int)} or through 18590 * @attr ref android.R.styleable#View_paddingStart or 18591 * @attr ref android.R.styleable#View_paddingEnd 18592 * 18593 * @return true if the padding is relative or false if it is not. 18594 */ 18595 public boolean isPaddingRelative() { 18596 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 18597 } 18598 18599 Insets computeOpticalInsets() { 18600 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 18601 } 18602 18603 /** 18604 * @hide 18605 */ 18606 public void resetPaddingToInitialValues() { 18607 if (isRtlCompatibilityMode()) { 18608 mPaddingLeft = mUserPaddingLeftInitial; 18609 mPaddingRight = mUserPaddingRightInitial; 18610 return; 18611 } 18612 if (isLayoutRtl()) { 18613 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 18614 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 18615 } else { 18616 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 18617 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 18618 } 18619 } 18620 18621 /** 18622 * @hide 18623 */ 18624 public Insets getOpticalInsets() { 18625 if (mLayoutInsets == null) { 18626 mLayoutInsets = computeOpticalInsets(); 18627 } 18628 return mLayoutInsets; 18629 } 18630 18631 /** 18632 * Set this view's optical insets. 18633 * 18634 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 18635 * property. Views that compute their own optical insets should call it as part of measurement. 18636 * This method does not request layout. If you are setting optical insets outside of 18637 * measure/layout itself you will want to call requestLayout() yourself. 18638 * </p> 18639 * @hide 18640 */ 18641 public void setOpticalInsets(Insets insets) { 18642 mLayoutInsets = insets; 18643 } 18644 18645 /** 18646 * Changes the selection state of this view. A view can be selected or not. 18647 * Note that selection is not the same as focus. Views are typically 18648 * selected in the context of an AdapterView like ListView or GridView; 18649 * the selected view is the view that is highlighted. 18650 * 18651 * @param selected true if the view must be selected, false otherwise 18652 */ 18653 public void setSelected(boolean selected) { 18654 //noinspection DoubleNegation 18655 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 18656 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 18657 if (!selected) resetPressedState(); 18658 invalidate(true); 18659 refreshDrawableState(); 18660 dispatchSetSelected(selected); 18661 if (selected) { 18662 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 18663 } else { 18664 notifyViewAccessibilityStateChangedIfNeeded( 18665 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 18666 } 18667 } 18668 } 18669 18670 /** 18671 * Dispatch setSelected to all of this View's children. 18672 * 18673 * @see #setSelected(boolean) 18674 * 18675 * @param selected The new selected state 18676 */ 18677 protected void dispatchSetSelected(boolean selected) { 18678 } 18679 18680 /** 18681 * Indicates the selection state of this view. 18682 * 18683 * @return true if the view is selected, false otherwise 18684 */ 18685 @ViewDebug.ExportedProperty 18686 public boolean isSelected() { 18687 return (mPrivateFlags & PFLAG_SELECTED) != 0; 18688 } 18689 18690 /** 18691 * Changes the activated state of this view. A view can be activated or not. 18692 * Note that activation is not the same as selection. Selection is 18693 * a transient property, representing the view (hierarchy) the user is 18694 * currently interacting with. Activation is a longer-term state that the 18695 * user can move views in and out of. For example, in a list view with 18696 * single or multiple selection enabled, the views in the current selection 18697 * set are activated. (Um, yeah, we are deeply sorry about the terminology 18698 * here.) The activated state is propagated down to children of the view it 18699 * is set on. 18700 * 18701 * @param activated true if the view must be activated, false otherwise 18702 */ 18703 public void setActivated(boolean activated) { 18704 //noinspection DoubleNegation 18705 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 18706 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 18707 invalidate(true); 18708 refreshDrawableState(); 18709 dispatchSetActivated(activated); 18710 } 18711 } 18712 18713 /** 18714 * Dispatch setActivated to all of this View's children. 18715 * 18716 * @see #setActivated(boolean) 18717 * 18718 * @param activated The new activated state 18719 */ 18720 protected void dispatchSetActivated(boolean activated) { 18721 } 18722 18723 /** 18724 * Indicates the activation state of this view. 18725 * 18726 * @return true if the view is activated, false otherwise 18727 */ 18728 @ViewDebug.ExportedProperty 18729 public boolean isActivated() { 18730 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 18731 } 18732 18733 /** 18734 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 18735 * observer can be used to get notifications when global events, like 18736 * layout, happen. 18737 * 18738 * The returned ViewTreeObserver observer is not guaranteed to remain 18739 * valid for the lifetime of this View. If the caller of this method keeps 18740 * a long-lived reference to ViewTreeObserver, it should always check for 18741 * the return value of {@link ViewTreeObserver#isAlive()}. 18742 * 18743 * @return The ViewTreeObserver for this view's hierarchy. 18744 */ 18745 public ViewTreeObserver getViewTreeObserver() { 18746 if (mAttachInfo != null) { 18747 return mAttachInfo.mTreeObserver; 18748 } 18749 if (mFloatingTreeObserver == null) { 18750 mFloatingTreeObserver = new ViewTreeObserver(); 18751 } 18752 return mFloatingTreeObserver; 18753 } 18754 18755 /** 18756 * <p>Finds the topmost view in the current view hierarchy.</p> 18757 * 18758 * @return the topmost view containing this view 18759 */ 18760 public View getRootView() { 18761 if (mAttachInfo != null) { 18762 final View v = mAttachInfo.mRootView; 18763 if (v != null) { 18764 return v; 18765 } 18766 } 18767 18768 View parent = this; 18769 18770 while (parent.mParent != null && parent.mParent instanceof View) { 18771 parent = (View) parent.mParent; 18772 } 18773 18774 return parent; 18775 } 18776 18777 /** 18778 * Transforms a motion event from view-local coordinates to on-screen 18779 * coordinates. 18780 * 18781 * @param ev the view-local motion event 18782 * @return false if the transformation could not be applied 18783 * @hide 18784 */ 18785 public boolean toGlobalMotionEvent(MotionEvent ev) { 18786 final AttachInfo info = mAttachInfo; 18787 if (info == null) { 18788 return false; 18789 } 18790 18791 final Matrix m = info.mTmpMatrix; 18792 m.set(Matrix.IDENTITY_MATRIX); 18793 transformMatrixToGlobal(m); 18794 ev.transform(m); 18795 return true; 18796 } 18797 18798 /** 18799 * Transforms a motion event from on-screen coordinates to view-local 18800 * coordinates. 18801 * 18802 * @param ev the on-screen motion event 18803 * @return false if the transformation could not be applied 18804 * @hide 18805 */ 18806 public boolean toLocalMotionEvent(MotionEvent ev) { 18807 final AttachInfo info = mAttachInfo; 18808 if (info == null) { 18809 return false; 18810 } 18811 18812 final Matrix m = info.mTmpMatrix; 18813 m.set(Matrix.IDENTITY_MATRIX); 18814 transformMatrixToLocal(m); 18815 ev.transform(m); 18816 return true; 18817 } 18818 18819 /** 18820 * Modifies the input matrix such that it maps view-local coordinates to 18821 * on-screen coordinates. 18822 * 18823 * @param m input matrix to modify 18824 * @hide 18825 */ 18826 public void transformMatrixToGlobal(Matrix m) { 18827 final ViewParent parent = mParent; 18828 if (parent instanceof View) { 18829 final View vp = (View) parent; 18830 vp.transformMatrixToGlobal(m); 18831 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 18832 } else if (parent instanceof ViewRootImpl) { 18833 final ViewRootImpl vr = (ViewRootImpl) parent; 18834 vr.transformMatrixToGlobal(m); 18835 m.preTranslate(0, -vr.mCurScrollY); 18836 } 18837 18838 m.preTranslate(mLeft, mTop); 18839 18840 if (!hasIdentityMatrix()) { 18841 m.preConcat(getMatrix()); 18842 } 18843 } 18844 18845 /** 18846 * Modifies the input matrix such that it maps on-screen coordinates to 18847 * view-local coordinates. 18848 * 18849 * @param m input matrix to modify 18850 * @hide 18851 */ 18852 public void transformMatrixToLocal(Matrix m) { 18853 final ViewParent parent = mParent; 18854 if (parent instanceof View) { 18855 final View vp = (View) parent; 18856 vp.transformMatrixToLocal(m); 18857 m.postTranslate(vp.mScrollX, vp.mScrollY); 18858 } else if (parent instanceof ViewRootImpl) { 18859 final ViewRootImpl vr = (ViewRootImpl) parent; 18860 vr.transformMatrixToLocal(m); 18861 m.postTranslate(0, vr.mCurScrollY); 18862 } 18863 18864 m.postTranslate(-mLeft, -mTop); 18865 18866 if (!hasIdentityMatrix()) { 18867 m.postConcat(getInverseMatrix()); 18868 } 18869 } 18870 18871 /** 18872 * @hide 18873 */ 18874 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 18875 @ViewDebug.IntToString(from = 0, to = "x"), 18876 @ViewDebug.IntToString(from = 1, to = "y") 18877 }) 18878 public int[] getLocationOnScreen() { 18879 int[] location = new int[2]; 18880 getLocationOnScreen(location); 18881 return location; 18882 } 18883 18884 /** 18885 * <p>Computes the coordinates of this view on the screen. The argument 18886 * must be an array of two integers. After the method returns, the array 18887 * contains the x and y location in that order.</p> 18888 * 18889 * @param outLocation an array of two integers in which to hold the coordinates 18890 */ 18891 public void getLocationOnScreen(@Size(2) int[] outLocation) { 18892 getLocationInWindow(outLocation); 18893 18894 final AttachInfo info = mAttachInfo; 18895 if (info != null) { 18896 outLocation[0] += info.mWindowLeft; 18897 outLocation[1] += info.mWindowTop; 18898 } 18899 } 18900 18901 /** 18902 * <p>Computes the coordinates of this view in its window. The argument 18903 * must be an array of two integers. After the method returns, the array 18904 * contains the x and y location in that order.</p> 18905 * 18906 * @param outLocation an array of two integers in which to hold the coordinates 18907 */ 18908 public void getLocationInWindow(@Size(2) int[] outLocation) { 18909 if (outLocation == null || outLocation.length < 2) { 18910 throw new IllegalArgumentException("outLocation must be an array of two integers"); 18911 } 18912 18913 outLocation[0] = 0; 18914 outLocation[1] = 0; 18915 18916 transformFromViewToWindowSpace(outLocation); 18917 } 18918 18919 /** @hide */ 18920 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 18921 if (inOutLocation == null || inOutLocation.length < 2) { 18922 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 18923 } 18924 18925 if (mAttachInfo == null) { 18926 // When the view is not attached to a window, this method does not make sense 18927 inOutLocation[0] = inOutLocation[1] = 0; 18928 return; 18929 } 18930 18931 float position[] = mAttachInfo.mTmpTransformLocation; 18932 position[0] = inOutLocation[0]; 18933 position[1] = inOutLocation[1]; 18934 18935 if (!hasIdentityMatrix()) { 18936 getMatrix().mapPoints(position); 18937 } 18938 18939 position[0] += mLeft; 18940 position[1] += mTop; 18941 18942 ViewParent viewParent = mParent; 18943 while (viewParent instanceof View) { 18944 final View view = (View) viewParent; 18945 18946 position[0] -= view.mScrollX; 18947 position[1] -= view.mScrollY; 18948 18949 if (!view.hasIdentityMatrix()) { 18950 view.getMatrix().mapPoints(position); 18951 } 18952 18953 position[0] += view.mLeft; 18954 position[1] += view.mTop; 18955 18956 viewParent = view.mParent; 18957 } 18958 18959 if (viewParent instanceof ViewRootImpl) { 18960 // *cough* 18961 final ViewRootImpl vr = (ViewRootImpl) viewParent; 18962 position[1] -= vr.mCurScrollY; 18963 } 18964 18965 inOutLocation[0] = Math.round(position[0]); 18966 inOutLocation[1] = Math.round(position[1]); 18967 } 18968 18969 /** 18970 * {@hide} 18971 * @param id the id of the view to be found 18972 * @return the view of the specified id, null if cannot be found 18973 */ 18974 protected View findViewTraversal(@IdRes int id) { 18975 if (id == mID) { 18976 return this; 18977 } 18978 return null; 18979 } 18980 18981 /** 18982 * {@hide} 18983 * @param tag the tag of the view to be found 18984 * @return the view of specified tag, null if cannot be found 18985 */ 18986 protected View findViewWithTagTraversal(Object tag) { 18987 if (tag != null && tag.equals(mTag)) { 18988 return this; 18989 } 18990 return null; 18991 } 18992 18993 /** 18994 * {@hide} 18995 * @param predicate The predicate to evaluate. 18996 * @param childToSkip If not null, ignores this child during the recursive traversal. 18997 * @return The first view that matches the predicate or null. 18998 */ 18999 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 19000 if (predicate.apply(this)) { 19001 return this; 19002 } 19003 return null; 19004 } 19005 19006 /** 19007 * Look for a child view with the given id. If this view has the given 19008 * id, return this view. 19009 * 19010 * @param id The id to search for. 19011 * @return The view that has the given id in the hierarchy or null 19012 */ 19013 @Nullable 19014 public final View findViewById(@IdRes int id) { 19015 if (id < 0) { 19016 return null; 19017 } 19018 return findViewTraversal(id); 19019 } 19020 19021 /** 19022 * Finds a view by its unuque and stable accessibility id. 19023 * 19024 * @param accessibilityId The searched accessibility id. 19025 * @return The found view. 19026 */ 19027 final View findViewByAccessibilityId(int accessibilityId) { 19028 if (accessibilityId < 0) { 19029 return null; 19030 } 19031 View view = findViewByAccessibilityIdTraversal(accessibilityId); 19032 if (view != null) { 19033 return view.includeForAccessibility() ? view : null; 19034 } 19035 return null; 19036 } 19037 19038 /** 19039 * Performs the traversal to find a view by its unuque and stable accessibility id. 19040 * 19041 * <strong>Note:</strong>This method does not stop at the root namespace 19042 * boundary since the user can touch the screen at an arbitrary location 19043 * potentially crossing the root namespace bounday which will send an 19044 * accessibility event to accessibility services and they should be able 19045 * to obtain the event source. Also accessibility ids are guaranteed to be 19046 * unique in the window. 19047 * 19048 * @param accessibilityId The accessibility id. 19049 * @return The found view. 19050 * 19051 * @hide 19052 */ 19053 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 19054 if (getAccessibilityViewId() == accessibilityId) { 19055 return this; 19056 } 19057 return null; 19058 } 19059 19060 /** 19061 * Look for a child view with the given tag. If this view has the given 19062 * tag, return this view. 19063 * 19064 * @param tag The tag to search for, using "tag.equals(getTag())". 19065 * @return The View that has the given tag in the hierarchy or null 19066 */ 19067 public final View findViewWithTag(Object tag) { 19068 if (tag == null) { 19069 return null; 19070 } 19071 return findViewWithTagTraversal(tag); 19072 } 19073 19074 /** 19075 * {@hide} 19076 * Look for a child view that matches the specified predicate. 19077 * If this view matches the predicate, return this view. 19078 * 19079 * @param predicate The predicate to evaluate. 19080 * @return The first view that matches the predicate or null. 19081 */ 19082 public final View findViewByPredicate(Predicate<View> predicate) { 19083 return findViewByPredicateTraversal(predicate, null); 19084 } 19085 19086 /** 19087 * {@hide} 19088 * Look for a child view that matches the specified predicate, 19089 * starting with the specified view and its descendents and then 19090 * recusively searching the ancestors and siblings of that view 19091 * until this view is reached. 19092 * 19093 * This method is useful in cases where the predicate does not match 19094 * a single unique view (perhaps multiple views use the same id) 19095 * and we are trying to find the view that is "closest" in scope to the 19096 * starting view. 19097 * 19098 * @param start The view to start from. 19099 * @param predicate The predicate to evaluate. 19100 * @return The first view that matches the predicate or null. 19101 */ 19102 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 19103 View childToSkip = null; 19104 for (;;) { 19105 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 19106 if (view != null || start == this) { 19107 return view; 19108 } 19109 19110 ViewParent parent = start.getParent(); 19111 if (parent == null || !(parent instanceof View)) { 19112 return null; 19113 } 19114 19115 childToSkip = start; 19116 start = (View) parent; 19117 } 19118 } 19119 19120 /** 19121 * Sets the identifier for this view. The identifier does not have to be 19122 * unique in this view's hierarchy. The identifier should be a positive 19123 * number. 19124 * 19125 * @see #NO_ID 19126 * @see #getId() 19127 * @see #findViewById(int) 19128 * 19129 * @param id a number used to identify the view 19130 * 19131 * @attr ref android.R.styleable#View_id 19132 */ 19133 public void setId(@IdRes int id) { 19134 mID = id; 19135 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 19136 mID = generateViewId(); 19137 } 19138 } 19139 19140 /** 19141 * {@hide} 19142 * 19143 * @param isRoot true if the view belongs to the root namespace, false 19144 * otherwise 19145 */ 19146 public void setIsRootNamespace(boolean isRoot) { 19147 if (isRoot) { 19148 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 19149 } else { 19150 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 19151 } 19152 } 19153 19154 /** 19155 * {@hide} 19156 * 19157 * @return true if the view belongs to the root namespace, false otherwise 19158 */ 19159 public boolean isRootNamespace() { 19160 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 19161 } 19162 19163 /** 19164 * Returns this view's identifier. 19165 * 19166 * @return a positive integer used to identify the view or {@link #NO_ID} 19167 * if the view has no ID 19168 * 19169 * @see #setId(int) 19170 * @see #findViewById(int) 19171 * @attr ref android.R.styleable#View_id 19172 */ 19173 @IdRes 19174 @ViewDebug.CapturedViewProperty 19175 public int getId() { 19176 return mID; 19177 } 19178 19179 /** 19180 * Returns this view's tag. 19181 * 19182 * @return the Object stored in this view as a tag, or {@code null} if not 19183 * set 19184 * 19185 * @see #setTag(Object) 19186 * @see #getTag(int) 19187 */ 19188 @ViewDebug.ExportedProperty 19189 public Object getTag() { 19190 return mTag; 19191 } 19192 19193 /** 19194 * Sets the tag associated with this view. A tag can be used to mark 19195 * a view in its hierarchy and does not have to be unique within the 19196 * hierarchy. Tags can also be used to store data within a view without 19197 * resorting to another data structure. 19198 * 19199 * @param tag an Object to tag the view with 19200 * 19201 * @see #getTag() 19202 * @see #setTag(int, Object) 19203 */ 19204 public void setTag(final Object tag) { 19205 mTag = tag; 19206 } 19207 19208 /** 19209 * Returns the tag associated with this view and the specified key. 19210 * 19211 * @param key The key identifying the tag 19212 * 19213 * @return the Object stored in this view as a tag, or {@code null} if not 19214 * set 19215 * 19216 * @see #setTag(int, Object) 19217 * @see #getTag() 19218 */ 19219 public Object getTag(int key) { 19220 if (mKeyedTags != null) return mKeyedTags.get(key); 19221 return null; 19222 } 19223 19224 /** 19225 * Sets a tag associated with this view and a key. A tag can be used 19226 * to mark a view in its hierarchy and does not have to be unique within 19227 * the hierarchy. Tags can also be used to store data within a view 19228 * without resorting to another data structure. 19229 * 19230 * The specified key should be an id declared in the resources of the 19231 * application to ensure it is unique (see the <a 19232 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 19233 * Keys identified as belonging to 19234 * the Android framework or not associated with any package will cause 19235 * an {@link IllegalArgumentException} to be thrown. 19236 * 19237 * @param key The key identifying the tag 19238 * @param tag An Object to tag the view with 19239 * 19240 * @throws IllegalArgumentException If they specified key is not valid 19241 * 19242 * @see #setTag(Object) 19243 * @see #getTag(int) 19244 */ 19245 public void setTag(int key, final Object tag) { 19246 // If the package id is 0x00 or 0x01, it's either an undefined package 19247 // or a framework id 19248 if ((key >>> 24) < 2) { 19249 throw new IllegalArgumentException("The key must be an application-specific " 19250 + "resource id."); 19251 } 19252 19253 setKeyedTag(key, tag); 19254 } 19255 19256 /** 19257 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 19258 * framework id. 19259 * 19260 * @hide 19261 */ 19262 public void setTagInternal(int key, Object tag) { 19263 if ((key >>> 24) != 0x1) { 19264 throw new IllegalArgumentException("The key must be a framework-specific " 19265 + "resource id."); 19266 } 19267 19268 setKeyedTag(key, tag); 19269 } 19270 19271 private void setKeyedTag(int key, Object tag) { 19272 if (mKeyedTags == null) { 19273 mKeyedTags = new SparseArray<Object>(2); 19274 } 19275 19276 mKeyedTags.put(key, tag); 19277 } 19278 19279 /** 19280 * Prints information about this view in the log output, with the tag 19281 * {@link #VIEW_LOG_TAG}. 19282 * 19283 * @hide 19284 */ 19285 public void debug() { 19286 debug(0); 19287 } 19288 19289 /** 19290 * Prints information about this view in the log output, with the tag 19291 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 19292 * indentation defined by the <code>depth</code>. 19293 * 19294 * @param depth the indentation level 19295 * 19296 * @hide 19297 */ 19298 protected void debug(int depth) { 19299 String output = debugIndent(depth - 1); 19300 19301 output += "+ " + this; 19302 int id = getId(); 19303 if (id != -1) { 19304 output += " (id=" + id + ")"; 19305 } 19306 Object tag = getTag(); 19307 if (tag != null) { 19308 output += " (tag=" + tag + ")"; 19309 } 19310 Log.d(VIEW_LOG_TAG, output); 19311 19312 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 19313 output = debugIndent(depth) + " FOCUSED"; 19314 Log.d(VIEW_LOG_TAG, output); 19315 } 19316 19317 output = debugIndent(depth); 19318 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 19319 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 19320 + "} "; 19321 Log.d(VIEW_LOG_TAG, output); 19322 19323 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 19324 || mPaddingBottom != 0) { 19325 output = debugIndent(depth); 19326 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 19327 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 19328 Log.d(VIEW_LOG_TAG, output); 19329 } 19330 19331 output = debugIndent(depth); 19332 output += "mMeasureWidth=" + mMeasuredWidth + 19333 " mMeasureHeight=" + mMeasuredHeight; 19334 Log.d(VIEW_LOG_TAG, output); 19335 19336 output = debugIndent(depth); 19337 if (mLayoutParams == null) { 19338 output += "BAD! no layout params"; 19339 } else { 19340 output = mLayoutParams.debug(output); 19341 } 19342 Log.d(VIEW_LOG_TAG, output); 19343 19344 output = debugIndent(depth); 19345 output += "flags={"; 19346 output += View.printFlags(mViewFlags); 19347 output += "}"; 19348 Log.d(VIEW_LOG_TAG, output); 19349 19350 output = debugIndent(depth); 19351 output += "privateFlags={"; 19352 output += View.printPrivateFlags(mPrivateFlags); 19353 output += "}"; 19354 Log.d(VIEW_LOG_TAG, output); 19355 } 19356 19357 /** 19358 * Creates a string of whitespaces used for indentation. 19359 * 19360 * @param depth the indentation level 19361 * @return a String containing (depth * 2 + 3) * 2 white spaces 19362 * 19363 * @hide 19364 */ 19365 protected static String debugIndent(int depth) { 19366 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 19367 for (int i = 0; i < (depth * 2) + 3; i++) { 19368 spaces.append(' ').append(' '); 19369 } 19370 return spaces.toString(); 19371 } 19372 19373 /** 19374 * <p>Return the offset of the widget's text baseline from the widget's top 19375 * boundary. If this widget does not support baseline alignment, this 19376 * method returns -1. </p> 19377 * 19378 * @return the offset of the baseline within the widget's bounds or -1 19379 * if baseline alignment is not supported 19380 */ 19381 @ViewDebug.ExportedProperty(category = "layout") 19382 public int getBaseline() { 19383 return -1; 19384 } 19385 19386 /** 19387 * Returns whether the view hierarchy is currently undergoing a layout pass. This 19388 * information is useful to avoid situations such as calling {@link #requestLayout()} during 19389 * a layout pass. 19390 * 19391 * @return whether the view hierarchy is currently undergoing a layout pass 19392 */ 19393 public boolean isInLayout() { 19394 ViewRootImpl viewRoot = getViewRootImpl(); 19395 return (viewRoot != null && viewRoot.isInLayout()); 19396 } 19397 19398 /** 19399 * Call this when something has changed which has invalidated the 19400 * layout of this view. This will schedule a layout pass of the view 19401 * tree. This should not be called while the view hierarchy is currently in a layout 19402 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 19403 * end of the current layout pass (and then layout will run again) or after the current 19404 * frame is drawn and the next layout occurs. 19405 * 19406 * <p>Subclasses which override this method should call the superclass method to 19407 * handle possible request-during-layout errors correctly.</p> 19408 */ 19409 @CallSuper 19410 public void requestLayout() { 19411 if (mMeasureCache != null) mMeasureCache.clear(); 19412 19413 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 19414 // Only trigger request-during-layout logic if this is the view requesting it, 19415 // not the views in its parent hierarchy 19416 ViewRootImpl viewRoot = getViewRootImpl(); 19417 if (viewRoot != null && viewRoot.isInLayout()) { 19418 if (!viewRoot.requestLayoutDuringLayout(this)) { 19419 return; 19420 } 19421 } 19422 mAttachInfo.mViewRequestingLayout = this; 19423 } 19424 19425 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19426 mPrivateFlags |= PFLAG_INVALIDATED; 19427 19428 if (mParent != null && !mParent.isLayoutRequested()) { 19429 mParent.requestLayout(); 19430 } 19431 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 19432 mAttachInfo.mViewRequestingLayout = null; 19433 } 19434 } 19435 19436 /** 19437 * Forces this view to be laid out during the next layout pass. 19438 * This method does not call requestLayout() or forceLayout() 19439 * on the parent. 19440 */ 19441 public void forceLayout() { 19442 if (mMeasureCache != null) mMeasureCache.clear(); 19443 19444 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 19445 mPrivateFlags |= PFLAG_INVALIDATED; 19446 } 19447 19448 /** 19449 * <p> 19450 * This is called to find out how big a view should be. The parent 19451 * supplies constraint information in the width and height parameters. 19452 * </p> 19453 * 19454 * <p> 19455 * The actual measurement work of a view is performed in 19456 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 19457 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 19458 * </p> 19459 * 19460 * 19461 * @param widthMeasureSpec Horizontal space requirements as imposed by the 19462 * parent 19463 * @param heightMeasureSpec Vertical space requirements as imposed by the 19464 * parent 19465 * 19466 * @see #onMeasure(int, int) 19467 */ 19468 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 19469 boolean optical = isLayoutModeOptical(this); 19470 if (optical != isLayoutModeOptical(mParent)) { 19471 Insets insets = getOpticalInsets(); 19472 int oWidth = insets.left + insets.right; 19473 int oHeight = insets.top + insets.bottom; 19474 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 19475 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 19476 } 19477 19478 // Suppress sign extension for the low bytes 19479 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 19480 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 19481 19482 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19483 19484 // Optimize layout by avoiding an extra EXACTLY pass when the view is 19485 // already measured as the correct size. In API 23 and below, this 19486 // extra pass is required to make LinearLayout re-distribute weight. 19487 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 19488 || heightMeasureSpec != mOldHeightMeasureSpec; 19489 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 19490 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 19491 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 19492 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 19493 final boolean needsLayout = specChanged 19494 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 19495 19496 if (forceLayout || needsLayout) { 19497 // first clears the measured dimension flag 19498 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 19499 19500 resolveRtlPropertiesIfNeeded(); 19501 19502 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 19503 if (cacheIndex < 0 || sIgnoreMeasureCache) { 19504 // measure ourselves, this should set the measured dimension flag back 19505 onMeasure(widthMeasureSpec, heightMeasureSpec); 19506 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19507 } else { 19508 long value = mMeasureCache.valueAt(cacheIndex); 19509 // Casting a long to int drops the high 32 bits, no mask needed 19510 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 19511 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19512 } 19513 19514 // flag not set, setMeasuredDimension() was not invoked, we raise 19515 // an exception to warn the developer 19516 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 19517 throw new IllegalStateException("View with id " + getId() + ": " 19518 + getClass().getName() + "#onMeasure() did not set the" 19519 + " measured dimension by calling" 19520 + " setMeasuredDimension()"); 19521 } 19522 19523 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 19524 } 19525 19526 mOldWidthMeasureSpec = widthMeasureSpec; 19527 mOldHeightMeasureSpec = heightMeasureSpec; 19528 19529 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 19530 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 19531 } 19532 19533 /** 19534 * <p> 19535 * Measure the view and its content to determine the measured width and the 19536 * measured height. This method is invoked by {@link #measure(int, int)} and 19537 * should be overridden by subclasses to provide accurate and efficient 19538 * measurement of their contents. 19539 * </p> 19540 * 19541 * <p> 19542 * <strong>CONTRACT:</strong> When overriding this method, you 19543 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 19544 * measured width and height of this view. Failure to do so will trigger an 19545 * <code>IllegalStateException</code>, thrown by 19546 * {@link #measure(int, int)}. Calling the superclass' 19547 * {@link #onMeasure(int, int)} is a valid use. 19548 * </p> 19549 * 19550 * <p> 19551 * The base class implementation of measure defaults to the background size, 19552 * unless a larger size is allowed by the MeasureSpec. Subclasses should 19553 * override {@link #onMeasure(int, int)} to provide better measurements of 19554 * their content. 19555 * </p> 19556 * 19557 * <p> 19558 * If this method is overridden, it is the subclass's responsibility to make 19559 * sure the measured height and width are at least the view's minimum height 19560 * and width ({@link #getSuggestedMinimumHeight()} and 19561 * {@link #getSuggestedMinimumWidth()}). 19562 * </p> 19563 * 19564 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 19565 * The requirements are encoded with 19566 * {@link android.view.View.MeasureSpec}. 19567 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 19568 * The requirements are encoded with 19569 * {@link android.view.View.MeasureSpec}. 19570 * 19571 * @see #getMeasuredWidth() 19572 * @see #getMeasuredHeight() 19573 * @see #setMeasuredDimension(int, int) 19574 * @see #getSuggestedMinimumHeight() 19575 * @see #getSuggestedMinimumWidth() 19576 * @see android.view.View.MeasureSpec#getMode(int) 19577 * @see android.view.View.MeasureSpec#getSize(int) 19578 */ 19579 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 19580 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 19581 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 19582 } 19583 19584 /** 19585 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 19586 * measured width and measured height. Failing to do so will trigger an 19587 * exception at measurement time.</p> 19588 * 19589 * @param measuredWidth The measured width of this view. May be a complex 19590 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19591 * {@link #MEASURED_STATE_TOO_SMALL}. 19592 * @param measuredHeight The measured height of this view. May be a complex 19593 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19594 * {@link #MEASURED_STATE_TOO_SMALL}. 19595 */ 19596 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 19597 boolean optical = isLayoutModeOptical(this); 19598 if (optical != isLayoutModeOptical(mParent)) { 19599 Insets insets = getOpticalInsets(); 19600 int opticalWidth = insets.left + insets.right; 19601 int opticalHeight = insets.top + insets.bottom; 19602 19603 measuredWidth += optical ? opticalWidth : -opticalWidth; 19604 measuredHeight += optical ? opticalHeight : -opticalHeight; 19605 } 19606 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 19607 } 19608 19609 /** 19610 * Sets the measured dimension without extra processing for things like optical bounds. 19611 * Useful for reapplying consistent values that have already been cooked with adjustments 19612 * for optical bounds, etc. such as those from the measurement cache. 19613 * 19614 * @param measuredWidth The measured width of this view. May be a complex 19615 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19616 * {@link #MEASURED_STATE_TOO_SMALL}. 19617 * @param measuredHeight The measured height of this view. May be a complex 19618 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 19619 * {@link #MEASURED_STATE_TOO_SMALL}. 19620 */ 19621 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 19622 mMeasuredWidth = measuredWidth; 19623 mMeasuredHeight = measuredHeight; 19624 19625 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 19626 } 19627 19628 /** 19629 * Merge two states as returned by {@link #getMeasuredState()}. 19630 * @param curState The current state as returned from a view or the result 19631 * of combining multiple views. 19632 * @param newState The new view state to combine. 19633 * @return Returns a new integer reflecting the combination of the two 19634 * states. 19635 */ 19636 public static int combineMeasuredStates(int curState, int newState) { 19637 return curState | newState; 19638 } 19639 19640 /** 19641 * Version of {@link #resolveSizeAndState(int, int, int)} 19642 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 19643 */ 19644 public static int resolveSize(int size, int measureSpec) { 19645 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 19646 } 19647 19648 /** 19649 * Utility to reconcile a desired size and state, with constraints imposed 19650 * by a MeasureSpec. Will take the desired size, unless a different size 19651 * is imposed by the constraints. The returned value is a compound integer, 19652 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 19653 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 19654 * resulting size is smaller than the size the view wants to be. 19655 * 19656 * @param size How big the view wants to be. 19657 * @param measureSpec Constraints imposed by the parent. 19658 * @param childMeasuredState Size information bit mask for the view's 19659 * children. 19660 * @return Size information bit mask as defined by 19661 * {@link #MEASURED_SIZE_MASK} and 19662 * {@link #MEASURED_STATE_TOO_SMALL}. 19663 */ 19664 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 19665 final int specMode = MeasureSpec.getMode(measureSpec); 19666 final int specSize = MeasureSpec.getSize(measureSpec); 19667 final int result; 19668 switch (specMode) { 19669 case MeasureSpec.AT_MOST: 19670 if (specSize < size) { 19671 result = specSize | MEASURED_STATE_TOO_SMALL; 19672 } else { 19673 result = size; 19674 } 19675 break; 19676 case MeasureSpec.EXACTLY: 19677 result = specSize; 19678 break; 19679 case MeasureSpec.UNSPECIFIED: 19680 default: 19681 result = size; 19682 } 19683 return result | (childMeasuredState & MEASURED_STATE_MASK); 19684 } 19685 19686 /** 19687 * Utility to return a default size. Uses the supplied size if the 19688 * MeasureSpec imposed no constraints. Will get larger if allowed 19689 * by the MeasureSpec. 19690 * 19691 * @param size Default size for this view 19692 * @param measureSpec Constraints imposed by the parent 19693 * @return The size this view should be. 19694 */ 19695 public static int getDefaultSize(int size, int measureSpec) { 19696 int result = size; 19697 int specMode = MeasureSpec.getMode(measureSpec); 19698 int specSize = MeasureSpec.getSize(measureSpec); 19699 19700 switch (specMode) { 19701 case MeasureSpec.UNSPECIFIED: 19702 result = size; 19703 break; 19704 case MeasureSpec.AT_MOST: 19705 case MeasureSpec.EXACTLY: 19706 result = specSize; 19707 break; 19708 } 19709 return result; 19710 } 19711 19712 /** 19713 * Returns the suggested minimum height that the view should use. This 19714 * returns the maximum of the view's minimum height 19715 * and the background's minimum height 19716 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 19717 * <p> 19718 * When being used in {@link #onMeasure(int, int)}, the caller should still 19719 * ensure the returned height is within the requirements of the parent. 19720 * 19721 * @return The suggested minimum height of the view. 19722 */ 19723 protected int getSuggestedMinimumHeight() { 19724 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 19725 19726 } 19727 19728 /** 19729 * Returns the suggested minimum width that the view should use. This 19730 * returns the maximum of the view's minimum width 19731 * and the background's minimum width 19732 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 19733 * <p> 19734 * When being used in {@link #onMeasure(int, int)}, the caller should still 19735 * ensure the returned width is within the requirements of the parent. 19736 * 19737 * @return The suggested minimum width of the view. 19738 */ 19739 protected int getSuggestedMinimumWidth() { 19740 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 19741 } 19742 19743 /** 19744 * Returns the minimum height of the view. 19745 * 19746 * @return the minimum height the view will try to be. 19747 * 19748 * @see #setMinimumHeight(int) 19749 * 19750 * @attr ref android.R.styleable#View_minHeight 19751 */ 19752 public int getMinimumHeight() { 19753 return mMinHeight; 19754 } 19755 19756 /** 19757 * Sets the minimum height of the view. It is not guaranteed the view will 19758 * be able to achieve this minimum height (for example, if its parent layout 19759 * constrains it with less available height). 19760 * 19761 * @param minHeight The minimum height the view will try to be. 19762 * 19763 * @see #getMinimumHeight() 19764 * 19765 * @attr ref android.R.styleable#View_minHeight 19766 */ 19767 @RemotableViewMethod 19768 public void setMinimumHeight(int minHeight) { 19769 mMinHeight = minHeight; 19770 requestLayout(); 19771 } 19772 19773 /** 19774 * Returns the minimum width of the view. 19775 * 19776 * @return the minimum width the view will try to be. 19777 * 19778 * @see #setMinimumWidth(int) 19779 * 19780 * @attr ref android.R.styleable#View_minWidth 19781 */ 19782 public int getMinimumWidth() { 19783 return mMinWidth; 19784 } 19785 19786 /** 19787 * Sets the minimum width of the view. It is not guaranteed the view will 19788 * be able to achieve this minimum width (for example, if its parent layout 19789 * constrains it with less available width). 19790 * 19791 * @param minWidth The minimum width the view will try to be. 19792 * 19793 * @see #getMinimumWidth() 19794 * 19795 * @attr ref android.R.styleable#View_minWidth 19796 */ 19797 public void setMinimumWidth(int minWidth) { 19798 mMinWidth = minWidth; 19799 requestLayout(); 19800 19801 } 19802 19803 /** 19804 * Get the animation currently associated with this view. 19805 * 19806 * @return The animation that is currently playing or 19807 * scheduled to play for this view. 19808 */ 19809 public Animation getAnimation() { 19810 return mCurrentAnimation; 19811 } 19812 19813 /** 19814 * Start the specified animation now. 19815 * 19816 * @param animation the animation to start now 19817 */ 19818 public void startAnimation(Animation animation) { 19819 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 19820 setAnimation(animation); 19821 invalidateParentCaches(); 19822 invalidate(true); 19823 } 19824 19825 /** 19826 * Cancels any animations for this view. 19827 */ 19828 public void clearAnimation() { 19829 if (mCurrentAnimation != null) { 19830 mCurrentAnimation.detach(); 19831 } 19832 mCurrentAnimation = null; 19833 invalidateParentIfNeeded(); 19834 } 19835 19836 /** 19837 * Sets the next animation to play for this view. 19838 * If you want the animation to play immediately, use 19839 * {@link #startAnimation(android.view.animation.Animation)} instead. 19840 * This method provides allows fine-grained 19841 * control over the start time and invalidation, but you 19842 * must make sure that 1) the animation has a start time set, and 19843 * 2) the view's parent (which controls animations on its children) 19844 * will be invalidated when the animation is supposed to 19845 * start. 19846 * 19847 * @param animation The next animation, or null. 19848 */ 19849 public void setAnimation(Animation animation) { 19850 mCurrentAnimation = animation; 19851 19852 if (animation != null) { 19853 // If the screen is off assume the animation start time is now instead of 19854 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 19855 // would cause the animation to start when the screen turns back on 19856 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 19857 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 19858 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 19859 } 19860 animation.reset(); 19861 } 19862 } 19863 19864 /** 19865 * Invoked by a parent ViewGroup to notify the start of the animation 19866 * currently associated with this view. If you override this method, 19867 * always call super.onAnimationStart(); 19868 * 19869 * @see #setAnimation(android.view.animation.Animation) 19870 * @see #getAnimation() 19871 */ 19872 @CallSuper 19873 protected void onAnimationStart() { 19874 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 19875 } 19876 19877 /** 19878 * Invoked by a parent ViewGroup to notify the end of the animation 19879 * currently associated with this view. If you override this method, 19880 * always call super.onAnimationEnd(); 19881 * 19882 * @see #setAnimation(android.view.animation.Animation) 19883 * @see #getAnimation() 19884 */ 19885 @CallSuper 19886 protected void onAnimationEnd() { 19887 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 19888 } 19889 19890 /** 19891 * Invoked if there is a Transform that involves alpha. Subclass that can 19892 * draw themselves with the specified alpha should return true, and then 19893 * respect that alpha when their onDraw() is called. If this returns false 19894 * then the view may be redirected to draw into an offscreen buffer to 19895 * fulfill the request, which will look fine, but may be slower than if the 19896 * subclass handles it internally. The default implementation returns false. 19897 * 19898 * @param alpha The alpha (0..255) to apply to the view's drawing 19899 * @return true if the view can draw with the specified alpha. 19900 */ 19901 protected boolean onSetAlpha(int alpha) { 19902 return false; 19903 } 19904 19905 /** 19906 * This is used by the RootView to perform an optimization when 19907 * the view hierarchy contains one or several SurfaceView. 19908 * SurfaceView is always considered transparent, but its children are not, 19909 * therefore all View objects remove themselves from the global transparent 19910 * region (passed as a parameter to this function). 19911 * 19912 * @param region The transparent region for this ViewAncestor (window). 19913 * 19914 * @return Returns true if the effective visibility of the view at this 19915 * point is opaque, regardless of the transparent region; returns false 19916 * if it is possible for underlying windows to be seen behind the view. 19917 * 19918 * {@hide} 19919 */ 19920 public boolean gatherTransparentRegion(Region region) { 19921 final AttachInfo attachInfo = mAttachInfo; 19922 if (region != null && attachInfo != null) { 19923 final int pflags = mPrivateFlags; 19924 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 19925 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 19926 // remove it from the transparent region. 19927 final int[] location = attachInfo.mTransparentLocation; 19928 getLocationInWindow(location); 19929 region.op(location[0], location[1], location[0] + mRight - mLeft, 19930 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 19931 } else { 19932 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 19933 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 19934 // the background drawable's non-transparent parts from this transparent region. 19935 applyDrawableToTransparentRegion(mBackground, region); 19936 } 19937 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 19938 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 19939 // Similarly, we remove the foreground drawable's non-transparent parts. 19940 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 19941 } 19942 } 19943 } 19944 return true; 19945 } 19946 19947 /** 19948 * Play a sound effect for this view. 19949 * 19950 * <p>The framework will play sound effects for some built in actions, such as 19951 * clicking, but you may wish to play these effects in your widget, 19952 * for instance, for internal navigation. 19953 * 19954 * <p>The sound effect will only be played if sound effects are enabled by the user, and 19955 * {@link #isSoundEffectsEnabled()} is true. 19956 * 19957 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 19958 */ 19959 public void playSoundEffect(int soundConstant) { 19960 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 19961 return; 19962 } 19963 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 19964 } 19965 19966 /** 19967 * BZZZTT!!1! 19968 * 19969 * <p>Provide haptic feedback to the user for this view. 19970 * 19971 * <p>The framework will provide haptic feedback for some built in actions, 19972 * such as long presses, but you may wish to provide feedback for your 19973 * own widget. 19974 * 19975 * <p>The feedback will only be performed if 19976 * {@link #isHapticFeedbackEnabled()} is true. 19977 * 19978 * @param feedbackConstant One of the constants defined in 19979 * {@link HapticFeedbackConstants} 19980 */ 19981 public boolean performHapticFeedback(int feedbackConstant) { 19982 return performHapticFeedback(feedbackConstant, 0); 19983 } 19984 19985 /** 19986 * BZZZTT!!1! 19987 * 19988 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 19989 * 19990 * @param feedbackConstant One of the constants defined in 19991 * {@link HapticFeedbackConstants} 19992 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 19993 */ 19994 public boolean performHapticFeedback(int feedbackConstant, int flags) { 19995 if (mAttachInfo == null) { 19996 return false; 19997 } 19998 //noinspection SimplifiableIfStatement 19999 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 20000 && !isHapticFeedbackEnabled()) { 20001 return false; 20002 } 20003 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 20004 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 20005 } 20006 20007 /** 20008 * Request that the visibility of the status bar or other screen/window 20009 * decorations be changed. 20010 * 20011 * <p>This method is used to put the over device UI into temporary modes 20012 * where the user's attention is focused more on the application content, 20013 * by dimming or hiding surrounding system affordances. This is typically 20014 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 20015 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 20016 * to be placed behind the action bar (and with these flags other system 20017 * affordances) so that smooth transitions between hiding and showing them 20018 * can be done. 20019 * 20020 * <p>Two representative examples of the use of system UI visibility is 20021 * implementing a content browsing application (like a magazine reader) 20022 * and a video playing application. 20023 * 20024 * <p>The first code shows a typical implementation of a View in a content 20025 * browsing application. In this implementation, the application goes 20026 * into a content-oriented mode by hiding the status bar and action bar, 20027 * and putting the navigation elements into lights out mode. The user can 20028 * then interact with content while in this mode. Such an application should 20029 * provide an easy way for the user to toggle out of the mode (such as to 20030 * check information in the status bar or access notifications). In the 20031 * implementation here, this is done simply by tapping on the content. 20032 * 20033 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 20034 * content} 20035 * 20036 * <p>This second code sample shows a typical implementation of a View 20037 * in a video playing application. In this situation, while the video is 20038 * playing the application would like to go into a complete full-screen mode, 20039 * to use as much of the display as possible for the video. When in this state 20040 * the user can not interact with the application; the system intercepts 20041 * touching on the screen to pop the UI out of full screen mode. See 20042 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 20043 * 20044 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 20045 * content} 20046 * 20047 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20048 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20049 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20050 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20051 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20052 */ 20053 public void setSystemUiVisibility(int visibility) { 20054 if (visibility != mSystemUiVisibility) { 20055 mSystemUiVisibility = visibility; 20056 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20057 mParent.recomputeViewAttributes(this); 20058 } 20059 } 20060 } 20061 20062 /** 20063 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 20064 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 20065 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 20066 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 20067 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 20068 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 20069 */ 20070 public int getSystemUiVisibility() { 20071 return mSystemUiVisibility; 20072 } 20073 20074 /** 20075 * Returns the current system UI visibility that is currently set for 20076 * the entire window. This is the combination of the 20077 * {@link #setSystemUiVisibility(int)} values supplied by all of the 20078 * views in the window. 20079 */ 20080 public int getWindowSystemUiVisibility() { 20081 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 20082 } 20083 20084 /** 20085 * Override to find out when the window's requested system UI visibility 20086 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 20087 * This is different from the callbacks received through 20088 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 20089 * in that this is only telling you about the local request of the window, 20090 * not the actual values applied by the system. 20091 */ 20092 public void onWindowSystemUiVisibilityChanged(int visible) { 20093 } 20094 20095 /** 20096 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 20097 * the view hierarchy. 20098 */ 20099 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 20100 onWindowSystemUiVisibilityChanged(visible); 20101 } 20102 20103 /** 20104 * Set a listener to receive callbacks when the visibility of the system bar changes. 20105 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 20106 */ 20107 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 20108 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 20109 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 20110 mParent.recomputeViewAttributes(this); 20111 } 20112 } 20113 20114 /** 20115 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 20116 * the view hierarchy. 20117 */ 20118 public void dispatchSystemUiVisibilityChanged(int visibility) { 20119 ListenerInfo li = mListenerInfo; 20120 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 20121 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 20122 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 20123 } 20124 } 20125 20126 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 20127 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 20128 if (val != mSystemUiVisibility) { 20129 setSystemUiVisibility(val); 20130 return true; 20131 } 20132 return false; 20133 } 20134 20135 /** @hide */ 20136 public void setDisabledSystemUiVisibility(int flags) { 20137 if (mAttachInfo != null) { 20138 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 20139 mAttachInfo.mDisabledSystemUiVisibility = flags; 20140 if (mParent != null) { 20141 mParent.recomputeViewAttributes(this); 20142 } 20143 } 20144 } 20145 } 20146 20147 /** 20148 * Creates an image that the system displays during the drag and drop 20149 * operation. This is called a "drag shadow". The default implementation 20150 * for a DragShadowBuilder based on a View returns an image that has exactly the same 20151 * appearance as the given View. The default also positions the center of the drag shadow 20152 * directly under the touch point. If no View is provided (the constructor with no parameters 20153 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 20154 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 20155 * default is an invisible drag shadow. 20156 * <p> 20157 * You are not required to use the View you provide to the constructor as the basis of the 20158 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 20159 * anything you want as the drag shadow. 20160 * </p> 20161 * <p> 20162 * You pass a DragShadowBuilder object to the system when you start the drag. The system 20163 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 20164 * size and position of the drag shadow. It uses this data to construct a 20165 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 20166 * so that your application can draw the shadow image in the Canvas. 20167 * </p> 20168 * 20169 * <div class="special reference"> 20170 * <h3>Developer Guides</h3> 20171 * <p>For a guide to implementing drag and drop features, read the 20172 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 20173 * </div> 20174 */ 20175 public static class DragShadowBuilder { 20176 private final WeakReference<View> mView; 20177 20178 /** 20179 * Constructs a shadow image builder based on a View. By default, the resulting drag 20180 * shadow will have the same appearance and dimensions as the View, with the touch point 20181 * over the center of the View. 20182 * @param view A View. Any View in scope can be used. 20183 */ 20184 public DragShadowBuilder(View view) { 20185 mView = new WeakReference<View>(view); 20186 } 20187 20188 /** 20189 * Construct a shadow builder object with no associated View. This 20190 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 20191 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 20192 * to supply the drag shadow's dimensions and appearance without 20193 * reference to any View object. If they are not overridden, then the result is an 20194 * invisible drag shadow. 20195 */ 20196 public DragShadowBuilder() { 20197 mView = new WeakReference<View>(null); 20198 } 20199 20200 /** 20201 * Returns the View object that had been passed to the 20202 * {@link #View.DragShadowBuilder(View)} 20203 * constructor. If that View parameter was {@code null} or if the 20204 * {@link #View.DragShadowBuilder()} 20205 * constructor was used to instantiate the builder object, this method will return 20206 * null. 20207 * 20208 * @return The View object associate with this builder object. 20209 */ 20210 @SuppressWarnings({"JavadocReference"}) 20211 final public View getView() { 20212 return mView.get(); 20213 } 20214 20215 /** 20216 * Provides the metrics for the shadow image. These include the dimensions of 20217 * the shadow image, and the point within that shadow that should 20218 * be centered under the touch location while dragging. 20219 * <p> 20220 * The default implementation sets the dimensions of the shadow to be the 20221 * same as the dimensions of the View itself and centers the shadow under 20222 * the touch point. 20223 * </p> 20224 * 20225 * @param shadowSize A {@link android.graphics.Point} containing the width and height 20226 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 20227 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 20228 * image. 20229 * 20230 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 20231 * shadow image that should be underneath the touch point during the drag and drop 20232 * operation. Your application must set {@link android.graphics.Point#x} to the 20233 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 20234 */ 20235 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 20236 final View view = mView.get(); 20237 if (view != null) { 20238 shadowSize.set(view.getWidth(), view.getHeight()); 20239 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 20240 } else { 20241 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 20242 } 20243 } 20244 20245 /** 20246 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 20247 * based on the dimensions it received from the 20248 * {@link #onProvideShadowMetrics(Point, Point)} callback. 20249 * 20250 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 20251 */ 20252 public void onDrawShadow(Canvas canvas) { 20253 final View view = mView.get(); 20254 if (view != null) { 20255 view.draw(canvas); 20256 } else { 20257 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 20258 } 20259 } 20260 } 20261 20262 /** 20263 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 20264 * startDragAndDrop()} for newer platform versions. 20265 */ 20266 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 20267 Object myLocalState, int flags) { 20268 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 20269 } 20270 20271 /** 20272 * Starts a drag and drop operation. When your application calls this method, it passes a 20273 * {@link android.view.View.DragShadowBuilder} object to the system. The 20274 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 20275 * to get metrics for the drag shadow, and then calls the object's 20276 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 20277 * <p> 20278 * Once the system has the drag shadow, it begins the drag and drop operation by sending 20279 * drag events to all the View objects in your application that are currently visible. It does 20280 * this either by calling the View object's drag listener (an implementation of 20281 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 20282 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 20283 * Both are passed a {@link android.view.DragEvent} object that has a 20284 * {@link android.view.DragEvent#getAction()} value of 20285 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 20286 * </p> 20287 * <p> 20288 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 20289 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 20290 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 20291 * to the View the user selected for dragging. 20292 * </p> 20293 * @param data A {@link android.content.ClipData} object pointing to the data to be 20294 * transferred by the drag and drop operation. 20295 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 20296 * drag shadow. 20297 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 20298 * drop operation. This Object is put into every DragEvent object sent by the system during the 20299 * current drag. 20300 * <p> 20301 * myLocalState is a lightweight mechanism for the sending information from the dragged View 20302 * to the target Views. For example, it can contain flags that differentiate between a 20303 * a copy operation and a move operation. 20304 * </p> 20305 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 20306 * so the parameter should be set to 0. 20307 * @return {@code true} if the method completes successfully, or 20308 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 20309 * do a drag, and so no drag operation is in progress. 20310 */ 20311 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 20312 Object myLocalState, int flags) { 20313 if (ViewDebug.DEBUG_DRAG) { 20314 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 20315 } 20316 boolean okay = false; 20317 20318 Point shadowSize = new Point(); 20319 Point shadowTouchPoint = new Point(); 20320 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 20321 20322 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 20323 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 20324 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 20325 } 20326 20327 if (ViewDebug.DEBUG_DRAG) { 20328 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 20329 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 20330 } 20331 if (mAttachInfo.mDragSurface != null) { 20332 mAttachInfo.mDragSurface.release(); 20333 } 20334 mAttachInfo.mDragSurface = new Surface(); 20335 try { 20336 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 20337 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 20338 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 20339 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 20340 if (mAttachInfo.mDragToken != null) { 20341 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20342 try { 20343 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20344 shadowBuilder.onDrawShadow(canvas); 20345 } finally { 20346 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20347 } 20348 20349 final ViewRootImpl root = getViewRootImpl(); 20350 20351 // Cache the local state object for delivery with DragEvents 20352 root.setLocalDragState(myLocalState); 20353 20354 // repurpose 'shadowSize' for the last touch point 20355 root.getLastTouchPoint(shadowSize); 20356 20357 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 20358 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 20359 shadowTouchPoint.x, shadowTouchPoint.y, data); 20360 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 20361 } 20362 } catch (Exception e) { 20363 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 20364 mAttachInfo.mDragSurface.destroy(); 20365 mAttachInfo.mDragSurface = null; 20366 } 20367 20368 return okay; 20369 } 20370 20371 /** 20372 * Cancels an ongoing drag and drop operation. 20373 * <p> 20374 * A {@link android.view.DragEvent} object with 20375 * {@link android.view.DragEvent#getAction()} value of 20376 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 20377 * {@link android.view.DragEvent#getResult()} value of {@code false} 20378 * will be sent to every 20379 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 20380 * even if they are not currently visible. 20381 * </p> 20382 * <p> 20383 * This method can be called on any View in the same window as the View on which 20384 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 20385 * was called. 20386 * </p> 20387 */ 20388 public final void cancelDragAndDrop() { 20389 if (ViewDebug.DEBUG_DRAG) { 20390 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 20391 } 20392 if (mAttachInfo.mDragToken != null) { 20393 try { 20394 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 20395 } catch (Exception e) { 20396 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 20397 } 20398 mAttachInfo.mDragToken = null; 20399 } else { 20400 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 20401 } 20402 } 20403 20404 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 20405 if (ViewDebug.DEBUG_DRAG) { 20406 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 20407 } 20408 if (mAttachInfo.mDragToken != null) { 20409 try { 20410 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 20411 try { 20412 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 20413 shadowBuilder.onDrawShadow(canvas); 20414 } finally { 20415 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 20416 } 20417 } catch (Exception e) { 20418 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 20419 } 20420 } else { 20421 Log.e(VIEW_LOG_TAG, "No active drag"); 20422 } 20423 } 20424 20425 /** 20426 * Starts a move from {startX, startY}, the amount of the movement will be the offset 20427 * between {startX, startY} and the new cursor positon. 20428 * @param startX horizontal coordinate where the move started. 20429 * @param startY vertical coordinate where the move started. 20430 * @return whether moving was started successfully. 20431 * @hide 20432 */ 20433 public final boolean startMovingTask(float startX, float startY) { 20434 if (ViewDebug.DEBUG_POSITIONING) { 20435 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 20436 } 20437 try { 20438 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 20439 } catch (RemoteException e) { 20440 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 20441 } 20442 return false; 20443 } 20444 20445 /** 20446 * Handles drag events sent by the system following a call to 20447 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 20448 * startDragAndDrop()}. 20449 *<p> 20450 * When the system calls this method, it passes a 20451 * {@link android.view.DragEvent} object. A call to 20452 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 20453 * in DragEvent. The method uses these to determine what is happening in the drag and drop 20454 * operation. 20455 * @param event The {@link android.view.DragEvent} sent by the system. 20456 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 20457 * in DragEvent, indicating the type of drag event represented by this object. 20458 * @return {@code true} if the method was successful, otherwise {@code false}. 20459 * <p> 20460 * The method should return {@code true} in response to an action type of 20461 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 20462 * operation. 20463 * </p> 20464 * <p> 20465 * The method should also return {@code true} in response to an action type of 20466 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 20467 * {@code false} if it didn't. 20468 * </p> 20469 */ 20470 public boolean onDragEvent(DragEvent event) { 20471 return false; 20472 } 20473 20474 /** 20475 * Detects if this View is enabled and has a drag event listener. 20476 * If both are true, then it calls the drag event listener with the 20477 * {@link android.view.DragEvent} it received. If the drag event listener returns 20478 * {@code true}, then dispatchDragEvent() returns {@code true}. 20479 * <p> 20480 * For all other cases, the method calls the 20481 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 20482 * method and returns its result. 20483 * </p> 20484 * <p> 20485 * This ensures that a drag event is always consumed, even if the View does not have a drag 20486 * event listener. However, if the View has a listener and the listener returns true, then 20487 * onDragEvent() is not called. 20488 * </p> 20489 */ 20490 public boolean dispatchDragEvent(DragEvent event) { 20491 ListenerInfo li = mListenerInfo; 20492 //noinspection SimplifiableIfStatement 20493 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 20494 && li.mOnDragListener.onDrag(this, event)) { 20495 return true; 20496 } 20497 return onDragEvent(event); 20498 } 20499 20500 boolean canAcceptDrag() { 20501 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 20502 } 20503 20504 /** 20505 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 20506 * it is ever exposed at all. 20507 * @hide 20508 */ 20509 public void onCloseSystemDialogs(String reason) { 20510 } 20511 20512 /** 20513 * Given a Drawable whose bounds have been set to draw into this view, 20514 * update a Region being computed for 20515 * {@link #gatherTransparentRegion(android.graphics.Region)} so 20516 * that any non-transparent parts of the Drawable are removed from the 20517 * given transparent region. 20518 * 20519 * @param dr The Drawable whose transparency is to be applied to the region. 20520 * @param region A Region holding the current transparency information, 20521 * where any parts of the region that are set are considered to be 20522 * transparent. On return, this region will be modified to have the 20523 * transparency information reduced by the corresponding parts of the 20524 * Drawable that are not transparent. 20525 * {@hide} 20526 */ 20527 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 20528 if (DBG) { 20529 Log.i("View", "Getting transparent region for: " + this); 20530 } 20531 final Region r = dr.getTransparentRegion(); 20532 final Rect db = dr.getBounds(); 20533 final AttachInfo attachInfo = mAttachInfo; 20534 if (r != null && attachInfo != null) { 20535 final int w = getRight()-getLeft(); 20536 final int h = getBottom()-getTop(); 20537 if (db.left > 0) { 20538 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 20539 r.op(0, 0, db.left, h, Region.Op.UNION); 20540 } 20541 if (db.right < w) { 20542 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 20543 r.op(db.right, 0, w, h, Region.Op.UNION); 20544 } 20545 if (db.top > 0) { 20546 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 20547 r.op(0, 0, w, db.top, Region.Op.UNION); 20548 } 20549 if (db.bottom < h) { 20550 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 20551 r.op(0, db.bottom, w, h, Region.Op.UNION); 20552 } 20553 final int[] location = attachInfo.mTransparentLocation; 20554 getLocationInWindow(location); 20555 r.translate(location[0], location[1]); 20556 region.op(r, Region.Op.INTERSECT); 20557 } else { 20558 region.op(db, Region.Op.DIFFERENCE); 20559 } 20560 } 20561 20562 private void checkForLongClick(int delayOffset, float x, float y) { 20563 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 20564 mHasPerformedLongPress = false; 20565 20566 if (mPendingCheckForLongPress == null) { 20567 mPendingCheckForLongPress = new CheckForLongPress(); 20568 } 20569 mPendingCheckForLongPress.setAnchor(x, y); 20570 mPendingCheckForLongPress.rememberWindowAttachCount(); 20571 postDelayed(mPendingCheckForLongPress, 20572 ViewConfiguration.getLongPressTimeout() - delayOffset); 20573 } 20574 } 20575 20576 /** 20577 * Inflate a view from an XML resource. This convenience method wraps the {@link 20578 * LayoutInflater} class, which provides a full range of options for view inflation. 20579 * 20580 * @param context The Context object for your activity or application. 20581 * @param resource The resource ID to inflate 20582 * @param root A view group that will be the parent. Used to properly inflate the 20583 * layout_* parameters. 20584 * @see LayoutInflater 20585 */ 20586 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 20587 LayoutInflater factory = LayoutInflater.from(context); 20588 return factory.inflate(resource, root); 20589 } 20590 20591 /** 20592 * Scroll the view with standard behavior for scrolling beyond the normal 20593 * content boundaries. Views that call this method should override 20594 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 20595 * results of an over-scroll operation. 20596 * 20597 * Views can use this method to handle any touch or fling-based scrolling. 20598 * 20599 * @param deltaX Change in X in pixels 20600 * @param deltaY Change in Y in pixels 20601 * @param scrollX Current X scroll value in pixels before applying deltaX 20602 * @param scrollY Current Y scroll value in pixels before applying deltaY 20603 * @param scrollRangeX Maximum content scroll range along the X axis 20604 * @param scrollRangeY Maximum content scroll range along the Y axis 20605 * @param maxOverScrollX Number of pixels to overscroll by in either direction 20606 * along the X axis. 20607 * @param maxOverScrollY Number of pixels to overscroll by in either direction 20608 * along the Y axis. 20609 * @param isTouchEvent true if this scroll operation is the result of a touch event. 20610 * @return true if scrolling was clamped to an over-scroll boundary along either 20611 * axis, false otherwise. 20612 */ 20613 @SuppressWarnings({"UnusedParameters"}) 20614 protected boolean overScrollBy(int deltaX, int deltaY, 20615 int scrollX, int scrollY, 20616 int scrollRangeX, int scrollRangeY, 20617 int maxOverScrollX, int maxOverScrollY, 20618 boolean isTouchEvent) { 20619 final int overScrollMode = mOverScrollMode; 20620 final boolean canScrollHorizontal = 20621 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 20622 final boolean canScrollVertical = 20623 computeVerticalScrollRange() > computeVerticalScrollExtent(); 20624 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 20625 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 20626 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 20627 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 20628 20629 int newScrollX = scrollX + deltaX; 20630 if (!overScrollHorizontal) { 20631 maxOverScrollX = 0; 20632 } 20633 20634 int newScrollY = scrollY + deltaY; 20635 if (!overScrollVertical) { 20636 maxOverScrollY = 0; 20637 } 20638 20639 // Clamp values if at the limits and record 20640 final int left = -maxOverScrollX; 20641 final int right = maxOverScrollX + scrollRangeX; 20642 final int top = -maxOverScrollY; 20643 final int bottom = maxOverScrollY + scrollRangeY; 20644 20645 boolean clampedX = false; 20646 if (newScrollX > right) { 20647 newScrollX = right; 20648 clampedX = true; 20649 } else if (newScrollX < left) { 20650 newScrollX = left; 20651 clampedX = true; 20652 } 20653 20654 boolean clampedY = false; 20655 if (newScrollY > bottom) { 20656 newScrollY = bottom; 20657 clampedY = true; 20658 } else if (newScrollY < top) { 20659 newScrollY = top; 20660 clampedY = true; 20661 } 20662 20663 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 20664 20665 return clampedX || clampedY; 20666 } 20667 20668 /** 20669 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 20670 * respond to the results of an over-scroll operation. 20671 * 20672 * @param scrollX New X scroll value in pixels 20673 * @param scrollY New Y scroll value in pixels 20674 * @param clampedX True if scrollX was clamped to an over-scroll boundary 20675 * @param clampedY True if scrollY was clamped to an over-scroll boundary 20676 */ 20677 protected void onOverScrolled(int scrollX, int scrollY, 20678 boolean clampedX, boolean clampedY) { 20679 // Intentionally empty. 20680 } 20681 20682 /** 20683 * Returns the over-scroll mode for this view. The result will be 20684 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20685 * (allow over-scrolling only if the view content is larger than the container), 20686 * or {@link #OVER_SCROLL_NEVER}. 20687 * 20688 * @return This view's over-scroll mode. 20689 */ 20690 public int getOverScrollMode() { 20691 return mOverScrollMode; 20692 } 20693 20694 /** 20695 * Set the over-scroll mode for this view. Valid over-scroll modes are 20696 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 20697 * (allow over-scrolling only if the view content is larger than the container), 20698 * or {@link #OVER_SCROLL_NEVER}. 20699 * 20700 * Setting the over-scroll mode of a view will have an effect only if the 20701 * view is capable of scrolling. 20702 * 20703 * @param overScrollMode The new over-scroll mode for this view. 20704 */ 20705 public void setOverScrollMode(int overScrollMode) { 20706 if (overScrollMode != OVER_SCROLL_ALWAYS && 20707 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 20708 overScrollMode != OVER_SCROLL_NEVER) { 20709 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 20710 } 20711 mOverScrollMode = overScrollMode; 20712 } 20713 20714 /** 20715 * Enable or disable nested scrolling for this view. 20716 * 20717 * <p>If this property is set to true the view will be permitted to initiate nested 20718 * scrolling operations with a compatible parent view in the current hierarchy. If this 20719 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 20720 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 20721 * the nested scroll.</p> 20722 * 20723 * @param enabled true to enable nested scrolling, false to disable 20724 * 20725 * @see #isNestedScrollingEnabled() 20726 */ 20727 public void setNestedScrollingEnabled(boolean enabled) { 20728 if (enabled) { 20729 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 20730 } else { 20731 stopNestedScroll(); 20732 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 20733 } 20734 } 20735 20736 /** 20737 * Returns true if nested scrolling is enabled for this view. 20738 * 20739 * <p>If nested scrolling is enabled and this View class implementation supports it, 20740 * this view will act as a nested scrolling child view when applicable, forwarding data 20741 * about the scroll operation in progress to a compatible and cooperating nested scrolling 20742 * parent.</p> 20743 * 20744 * @return true if nested scrolling is enabled 20745 * 20746 * @see #setNestedScrollingEnabled(boolean) 20747 */ 20748 public boolean isNestedScrollingEnabled() { 20749 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 20750 PFLAG3_NESTED_SCROLLING_ENABLED; 20751 } 20752 20753 /** 20754 * Begin a nestable scroll operation along the given axes. 20755 * 20756 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 20757 * 20758 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 20759 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 20760 * In the case of touch scrolling the nested scroll will be terminated automatically in 20761 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 20762 * In the event of programmatic scrolling the caller must explicitly call 20763 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 20764 * 20765 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 20766 * If it returns false the caller may ignore the rest of this contract until the next scroll. 20767 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 20768 * 20769 * <p>At each incremental step of the scroll the caller should invoke 20770 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 20771 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 20772 * parent at least partially consumed the scroll and the caller should adjust the amount it 20773 * scrolls by.</p> 20774 * 20775 * <p>After applying the remainder of the scroll delta the caller should invoke 20776 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 20777 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 20778 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 20779 * </p> 20780 * 20781 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 20782 * {@link #SCROLL_AXIS_VERTICAL}. 20783 * @return true if a cooperative parent was found and nested scrolling has been enabled for 20784 * the current gesture. 20785 * 20786 * @see #stopNestedScroll() 20787 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 20788 * @see #dispatchNestedScroll(int, int, int, int, int[]) 20789 */ 20790 public boolean startNestedScroll(int axes) { 20791 if (hasNestedScrollingParent()) { 20792 // Already in progress 20793 return true; 20794 } 20795 if (isNestedScrollingEnabled()) { 20796 ViewParent p = getParent(); 20797 View child = this; 20798 while (p != null) { 20799 try { 20800 if (p.onStartNestedScroll(child, this, axes)) { 20801 mNestedScrollingParent = p; 20802 p.onNestedScrollAccepted(child, this, axes); 20803 return true; 20804 } 20805 } catch (AbstractMethodError e) { 20806 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 20807 "method onStartNestedScroll", e); 20808 // Allow the search upward to continue 20809 } 20810 if (p instanceof View) { 20811 child = (View) p; 20812 } 20813 p = p.getParent(); 20814 } 20815 } 20816 return false; 20817 } 20818 20819 /** 20820 * Stop a nested scroll in progress. 20821 * 20822 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 20823 * 20824 * @see #startNestedScroll(int) 20825 */ 20826 public void stopNestedScroll() { 20827 if (mNestedScrollingParent != null) { 20828 mNestedScrollingParent.onStopNestedScroll(this); 20829 mNestedScrollingParent = null; 20830 } 20831 } 20832 20833 /** 20834 * Returns true if this view has a nested scrolling parent. 20835 * 20836 * <p>The presence of a nested scrolling parent indicates that this view has initiated 20837 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 20838 * 20839 * @return whether this view has a nested scrolling parent 20840 */ 20841 public boolean hasNestedScrollingParent() { 20842 return mNestedScrollingParent != null; 20843 } 20844 20845 /** 20846 * Dispatch one step of a nested scroll in progress. 20847 * 20848 * <p>Implementations of views that support nested scrolling should call this to report 20849 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 20850 * is not currently in progress or nested scrolling is not 20851 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 20852 * 20853 * <p>Compatible View implementations should also call 20854 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 20855 * consuming a component of the scroll event themselves.</p> 20856 * 20857 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 20858 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 20859 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 20860 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 20861 * @param offsetInWindow Optional. If not null, on return this will contain the offset 20862 * in local view coordinates of this view from before this operation 20863 * to after it completes. View implementations may use this to adjust 20864 * expected input coordinate tracking. 20865 * @return true if the event was dispatched, false if it could not be dispatched. 20866 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 20867 */ 20868 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 20869 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 20870 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20871 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 20872 int startX = 0; 20873 int startY = 0; 20874 if (offsetInWindow != null) { 20875 getLocationInWindow(offsetInWindow); 20876 startX = offsetInWindow[0]; 20877 startY = offsetInWindow[1]; 20878 } 20879 20880 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 20881 dxUnconsumed, dyUnconsumed); 20882 20883 if (offsetInWindow != null) { 20884 getLocationInWindow(offsetInWindow); 20885 offsetInWindow[0] -= startX; 20886 offsetInWindow[1] -= startY; 20887 } 20888 return true; 20889 } else if (offsetInWindow != null) { 20890 // No motion, no dispatch. Keep offsetInWindow up to date. 20891 offsetInWindow[0] = 0; 20892 offsetInWindow[1] = 0; 20893 } 20894 } 20895 return false; 20896 } 20897 20898 /** 20899 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 20900 * 20901 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 20902 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 20903 * scrolling operation to consume some or all of the scroll operation before the child view 20904 * consumes it.</p> 20905 * 20906 * @param dx Horizontal scroll distance in pixels 20907 * @param dy Vertical scroll distance in pixels 20908 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 20909 * and consumed[1] the consumed dy. 20910 * @param offsetInWindow Optional. If not null, on return this will contain the offset 20911 * in local view coordinates of this view from before this operation 20912 * to after it completes. View implementations may use this to adjust 20913 * expected input coordinate tracking. 20914 * @return true if the parent consumed some or all of the scroll delta 20915 * @see #dispatchNestedScroll(int, int, int, int, int[]) 20916 */ 20917 public boolean dispatchNestedPreScroll(int dx, int dy, 20918 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 20919 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20920 if (dx != 0 || dy != 0) { 20921 int startX = 0; 20922 int startY = 0; 20923 if (offsetInWindow != null) { 20924 getLocationInWindow(offsetInWindow); 20925 startX = offsetInWindow[0]; 20926 startY = offsetInWindow[1]; 20927 } 20928 20929 if (consumed == null) { 20930 if (mTempNestedScrollConsumed == null) { 20931 mTempNestedScrollConsumed = new int[2]; 20932 } 20933 consumed = mTempNestedScrollConsumed; 20934 } 20935 consumed[0] = 0; 20936 consumed[1] = 0; 20937 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 20938 20939 if (offsetInWindow != null) { 20940 getLocationInWindow(offsetInWindow); 20941 offsetInWindow[0] -= startX; 20942 offsetInWindow[1] -= startY; 20943 } 20944 return consumed[0] != 0 || consumed[1] != 0; 20945 } else if (offsetInWindow != null) { 20946 offsetInWindow[0] = 0; 20947 offsetInWindow[1] = 0; 20948 } 20949 } 20950 return false; 20951 } 20952 20953 /** 20954 * Dispatch a fling to a nested scrolling parent. 20955 * 20956 * <p>This method should be used to indicate that a nested scrolling child has detected 20957 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 20958 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 20959 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 20960 * along a scrollable axis.</p> 20961 * 20962 * <p>If a nested scrolling child view would normally fling but it is at the edge of 20963 * its own content, it can use this method to delegate the fling to its nested scrolling 20964 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 20965 * 20966 * @param velocityX Horizontal fling velocity in pixels per second 20967 * @param velocityY Vertical fling velocity in pixels per second 20968 * @param consumed true if the child consumed the fling, false otherwise 20969 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 20970 */ 20971 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 20972 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 20973 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 20974 } 20975 return false; 20976 } 20977 20978 /** 20979 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 20980 * 20981 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 20982 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 20983 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 20984 * before the child view consumes it. If this method returns <code>true</code>, a nested 20985 * parent view consumed the fling and this view should not scroll as a result.</p> 20986 * 20987 * <p>For a better user experience, only one view in a nested scrolling chain should consume 20988 * the fling at a time. If a parent view consumed the fling this method will return false. 20989 * Custom view implementations should account for this in two ways:</p> 20990 * 20991 * <ul> 20992 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 20993 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 20994 * position regardless.</li> 20995 * <li>If a nested parent does consume the fling, this view should not scroll at all, 20996 * even to settle back to a valid idle position.</li> 20997 * </ul> 20998 * 20999 * <p>Views should also not offer fling velocities to nested parent views along an axis 21000 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 21001 * should not offer a horizontal fling velocity to its parents since scrolling along that 21002 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 21003 * 21004 * @param velocityX Horizontal fling velocity in pixels per second 21005 * @param velocityY Vertical fling velocity in pixels per second 21006 * @return true if a nested scrolling parent consumed the fling 21007 */ 21008 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 21009 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 21010 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 21011 } 21012 return false; 21013 } 21014 21015 /** 21016 * Gets a scale factor that determines the distance the view should scroll 21017 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 21018 * @return The vertical scroll scale factor. 21019 * @hide 21020 */ 21021 protected float getVerticalScrollFactor() { 21022 if (mVerticalScrollFactor == 0) { 21023 TypedValue outValue = new TypedValue(); 21024 if (!mContext.getTheme().resolveAttribute( 21025 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 21026 throw new IllegalStateException( 21027 "Expected theme to define listPreferredItemHeight."); 21028 } 21029 mVerticalScrollFactor = outValue.getDimension( 21030 mContext.getResources().getDisplayMetrics()); 21031 } 21032 return mVerticalScrollFactor; 21033 } 21034 21035 /** 21036 * Gets a scale factor that determines the distance the view should scroll 21037 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 21038 * @return The horizontal scroll scale factor. 21039 * @hide 21040 */ 21041 protected float getHorizontalScrollFactor() { 21042 // TODO: Should use something else. 21043 return getVerticalScrollFactor(); 21044 } 21045 21046 /** 21047 * Return the value specifying the text direction or policy that was set with 21048 * {@link #setTextDirection(int)}. 21049 * 21050 * @return the defined text direction. It can be one of: 21051 * 21052 * {@link #TEXT_DIRECTION_INHERIT}, 21053 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21054 * {@link #TEXT_DIRECTION_ANY_RTL}, 21055 * {@link #TEXT_DIRECTION_LTR}, 21056 * {@link #TEXT_DIRECTION_RTL}, 21057 * {@link #TEXT_DIRECTION_LOCALE}, 21058 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21059 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21060 * 21061 * @attr ref android.R.styleable#View_textDirection 21062 * 21063 * @hide 21064 */ 21065 @ViewDebug.ExportedProperty(category = "text", mapping = { 21066 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21067 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21068 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21069 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21070 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21071 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21072 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21073 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21074 }) 21075 public int getRawTextDirection() { 21076 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 21077 } 21078 21079 /** 21080 * Set the text direction. 21081 * 21082 * @param textDirection the direction to set. Should be one of: 21083 * 21084 * {@link #TEXT_DIRECTION_INHERIT}, 21085 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21086 * {@link #TEXT_DIRECTION_ANY_RTL}, 21087 * {@link #TEXT_DIRECTION_LTR}, 21088 * {@link #TEXT_DIRECTION_RTL}, 21089 * {@link #TEXT_DIRECTION_LOCALE} 21090 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21091 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 21092 * 21093 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 21094 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 21095 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 21096 * 21097 * @attr ref android.R.styleable#View_textDirection 21098 */ 21099 public void setTextDirection(int textDirection) { 21100 if (getRawTextDirection() != textDirection) { 21101 // Reset the current text direction and the resolved one 21102 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 21103 resetResolvedTextDirection(); 21104 // Set the new text direction 21105 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 21106 // Do resolution 21107 resolveTextDirection(); 21108 // Notify change 21109 onRtlPropertiesChanged(getLayoutDirection()); 21110 // Refresh 21111 requestLayout(); 21112 invalidate(true); 21113 } 21114 } 21115 21116 /** 21117 * Return the resolved text direction. 21118 * 21119 * @return the resolved text direction. Returns one of: 21120 * 21121 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 21122 * {@link #TEXT_DIRECTION_ANY_RTL}, 21123 * {@link #TEXT_DIRECTION_LTR}, 21124 * {@link #TEXT_DIRECTION_RTL}, 21125 * {@link #TEXT_DIRECTION_LOCALE}, 21126 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 21127 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 21128 * 21129 * @attr ref android.R.styleable#View_textDirection 21130 */ 21131 @ViewDebug.ExportedProperty(category = "text", mapping = { 21132 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 21133 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 21134 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 21135 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 21136 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 21137 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 21138 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 21139 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 21140 }) 21141 public int getTextDirection() { 21142 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 21143 } 21144 21145 /** 21146 * Resolve the text direction. 21147 * 21148 * @return true if resolution has been done, false otherwise. 21149 * 21150 * @hide 21151 */ 21152 public boolean resolveTextDirection() { 21153 // Reset any previous text direction resolution 21154 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21155 21156 if (hasRtlSupport()) { 21157 // Set resolved text direction flag depending on text direction flag 21158 final int textDirection = getRawTextDirection(); 21159 switch(textDirection) { 21160 case TEXT_DIRECTION_INHERIT: 21161 if (!canResolveTextDirection()) { 21162 // We cannot do the resolution if there is no parent, so use the default one 21163 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21164 // Resolution will need to happen again later 21165 return false; 21166 } 21167 21168 // Parent has not yet resolved, so we still return the default 21169 try { 21170 if (!mParent.isTextDirectionResolved()) { 21171 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21172 // Resolution will need to happen again later 21173 return false; 21174 } 21175 } catch (AbstractMethodError e) { 21176 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21177 " does not fully implement ViewParent", e); 21178 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 21179 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21180 return true; 21181 } 21182 21183 // Set current resolved direction to the same value as the parent's one 21184 int parentResolvedDirection; 21185 try { 21186 parentResolvedDirection = mParent.getTextDirection(); 21187 } catch (AbstractMethodError e) { 21188 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21189 " does not fully implement ViewParent", e); 21190 parentResolvedDirection = TEXT_DIRECTION_LTR; 21191 } 21192 switch (parentResolvedDirection) { 21193 case TEXT_DIRECTION_FIRST_STRONG: 21194 case TEXT_DIRECTION_ANY_RTL: 21195 case TEXT_DIRECTION_LTR: 21196 case TEXT_DIRECTION_RTL: 21197 case TEXT_DIRECTION_LOCALE: 21198 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21199 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21200 mPrivateFlags2 |= 21201 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21202 break; 21203 default: 21204 // Default resolved direction is "first strong" heuristic 21205 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21206 } 21207 break; 21208 case TEXT_DIRECTION_FIRST_STRONG: 21209 case TEXT_DIRECTION_ANY_RTL: 21210 case TEXT_DIRECTION_LTR: 21211 case TEXT_DIRECTION_RTL: 21212 case TEXT_DIRECTION_LOCALE: 21213 case TEXT_DIRECTION_FIRST_STRONG_LTR: 21214 case TEXT_DIRECTION_FIRST_STRONG_RTL: 21215 // Resolved direction is the same as text direction 21216 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 21217 break; 21218 default: 21219 // Default resolved direction is "first strong" heuristic 21220 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21221 } 21222 } else { 21223 // Default resolved direction is "first strong" heuristic 21224 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21225 } 21226 21227 // Set to resolved 21228 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 21229 return true; 21230 } 21231 21232 /** 21233 * Check if text direction resolution can be done. 21234 * 21235 * @return true if text direction resolution can be done otherwise return false. 21236 */ 21237 public boolean canResolveTextDirection() { 21238 switch (getRawTextDirection()) { 21239 case TEXT_DIRECTION_INHERIT: 21240 if (mParent != null) { 21241 try { 21242 return mParent.canResolveTextDirection(); 21243 } catch (AbstractMethodError e) { 21244 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21245 " does not fully implement ViewParent", e); 21246 } 21247 } 21248 return false; 21249 21250 default: 21251 return true; 21252 } 21253 } 21254 21255 /** 21256 * Reset resolved text direction. Text direction will be resolved during a call to 21257 * {@link #onMeasure(int, int)}. 21258 * 21259 * @hide 21260 */ 21261 public void resetResolvedTextDirection() { 21262 // Reset any previous text direction resolution 21263 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 21264 // Set to default value 21265 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 21266 } 21267 21268 /** 21269 * @return true if text direction is inherited. 21270 * 21271 * @hide 21272 */ 21273 public boolean isTextDirectionInherited() { 21274 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 21275 } 21276 21277 /** 21278 * @return true if text direction is resolved. 21279 */ 21280 public boolean isTextDirectionResolved() { 21281 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 21282 } 21283 21284 /** 21285 * Return the value specifying the text alignment or policy that was set with 21286 * {@link #setTextAlignment(int)}. 21287 * 21288 * @return the defined text alignment. It can be one of: 21289 * 21290 * {@link #TEXT_ALIGNMENT_INHERIT}, 21291 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21292 * {@link #TEXT_ALIGNMENT_CENTER}, 21293 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21294 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21295 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21296 * {@link #TEXT_ALIGNMENT_VIEW_END} 21297 * 21298 * @attr ref android.R.styleable#View_textAlignment 21299 * 21300 * @hide 21301 */ 21302 @ViewDebug.ExportedProperty(category = "text", mapping = { 21303 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21304 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21305 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21306 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21307 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21308 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21309 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21310 }) 21311 @TextAlignment 21312 public int getRawTextAlignment() { 21313 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 21314 } 21315 21316 /** 21317 * Set the text alignment. 21318 * 21319 * @param textAlignment The text alignment to set. Should be one of 21320 * 21321 * {@link #TEXT_ALIGNMENT_INHERIT}, 21322 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21323 * {@link #TEXT_ALIGNMENT_CENTER}, 21324 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21325 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21326 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21327 * {@link #TEXT_ALIGNMENT_VIEW_END} 21328 * 21329 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 21330 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 21331 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 21332 * 21333 * @attr ref android.R.styleable#View_textAlignment 21334 */ 21335 public void setTextAlignment(@TextAlignment int textAlignment) { 21336 if (textAlignment != getRawTextAlignment()) { 21337 // Reset the current and resolved text alignment 21338 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 21339 resetResolvedTextAlignment(); 21340 // Set the new text alignment 21341 mPrivateFlags2 |= 21342 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 21343 // Do resolution 21344 resolveTextAlignment(); 21345 // Notify change 21346 onRtlPropertiesChanged(getLayoutDirection()); 21347 // Refresh 21348 requestLayout(); 21349 invalidate(true); 21350 } 21351 } 21352 21353 /** 21354 * Return the resolved text alignment. 21355 * 21356 * @return the resolved text alignment. Returns one of: 21357 * 21358 * {@link #TEXT_ALIGNMENT_GRAVITY}, 21359 * {@link #TEXT_ALIGNMENT_CENTER}, 21360 * {@link #TEXT_ALIGNMENT_TEXT_START}, 21361 * {@link #TEXT_ALIGNMENT_TEXT_END}, 21362 * {@link #TEXT_ALIGNMENT_VIEW_START}, 21363 * {@link #TEXT_ALIGNMENT_VIEW_END} 21364 * 21365 * @attr ref android.R.styleable#View_textAlignment 21366 */ 21367 @ViewDebug.ExportedProperty(category = "text", mapping = { 21368 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 21369 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 21370 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 21371 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 21372 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 21373 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 21374 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 21375 }) 21376 @TextAlignment 21377 public int getTextAlignment() { 21378 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 21379 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 21380 } 21381 21382 /** 21383 * Resolve the text alignment. 21384 * 21385 * @return true if resolution has been done, false otherwise. 21386 * 21387 * @hide 21388 */ 21389 public boolean resolveTextAlignment() { 21390 // Reset any previous text alignment resolution 21391 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21392 21393 if (hasRtlSupport()) { 21394 // Set resolved text alignment flag depending on text alignment flag 21395 final int textAlignment = getRawTextAlignment(); 21396 switch (textAlignment) { 21397 case TEXT_ALIGNMENT_INHERIT: 21398 // Check if we can resolve the text alignment 21399 if (!canResolveTextAlignment()) { 21400 // We cannot do the resolution if there is no parent so use the default 21401 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21402 // Resolution will need to happen again later 21403 return false; 21404 } 21405 21406 // Parent has not yet resolved, so we still return the default 21407 try { 21408 if (!mParent.isTextAlignmentResolved()) { 21409 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21410 // Resolution will need to happen again later 21411 return false; 21412 } 21413 } catch (AbstractMethodError e) { 21414 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21415 " does not fully implement ViewParent", e); 21416 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 21417 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21418 return true; 21419 } 21420 21421 int parentResolvedTextAlignment; 21422 try { 21423 parentResolvedTextAlignment = mParent.getTextAlignment(); 21424 } catch (AbstractMethodError e) { 21425 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21426 " does not fully implement ViewParent", e); 21427 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 21428 } 21429 switch (parentResolvedTextAlignment) { 21430 case TEXT_ALIGNMENT_GRAVITY: 21431 case TEXT_ALIGNMENT_TEXT_START: 21432 case TEXT_ALIGNMENT_TEXT_END: 21433 case TEXT_ALIGNMENT_CENTER: 21434 case TEXT_ALIGNMENT_VIEW_START: 21435 case TEXT_ALIGNMENT_VIEW_END: 21436 // Resolved text alignment is the same as the parent resolved 21437 // text alignment 21438 mPrivateFlags2 |= 21439 (parentResolvedTextAlignment << 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 break; 21446 case TEXT_ALIGNMENT_GRAVITY: 21447 case TEXT_ALIGNMENT_TEXT_START: 21448 case TEXT_ALIGNMENT_TEXT_END: 21449 case TEXT_ALIGNMENT_CENTER: 21450 case TEXT_ALIGNMENT_VIEW_START: 21451 case TEXT_ALIGNMENT_VIEW_END: 21452 // Resolved text alignment is the same as text alignment 21453 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 21454 break; 21455 default: 21456 // Use default resolved text alignment 21457 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21458 } 21459 } else { 21460 // Use default resolved text alignment 21461 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21462 } 21463 21464 // Set the resolved 21465 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21466 return true; 21467 } 21468 21469 /** 21470 * Check if text alignment resolution can be done. 21471 * 21472 * @return true if text alignment resolution can be done otherwise return false. 21473 */ 21474 public boolean canResolveTextAlignment() { 21475 switch (getRawTextAlignment()) { 21476 case TEXT_DIRECTION_INHERIT: 21477 if (mParent != null) { 21478 try { 21479 return mParent.canResolveTextAlignment(); 21480 } catch (AbstractMethodError e) { 21481 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 21482 " does not fully implement ViewParent", e); 21483 } 21484 } 21485 return false; 21486 21487 default: 21488 return true; 21489 } 21490 } 21491 21492 /** 21493 * Reset resolved text alignment. Text alignment will be resolved during a call to 21494 * {@link #onMeasure(int, int)}. 21495 * 21496 * @hide 21497 */ 21498 public void resetResolvedTextAlignment() { 21499 // Reset any previous text alignment resolution 21500 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 21501 // Set to default 21502 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 21503 } 21504 21505 /** 21506 * @return true if text alignment is inherited. 21507 * 21508 * @hide 21509 */ 21510 public boolean isTextAlignmentInherited() { 21511 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 21512 } 21513 21514 /** 21515 * @return true if text alignment is resolved. 21516 */ 21517 public boolean isTextAlignmentResolved() { 21518 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 21519 } 21520 21521 /** 21522 * Generate a value suitable for use in {@link #setId(int)}. 21523 * This value will not collide with ID values generated at build time by aapt for R.id. 21524 * 21525 * @return a generated ID value 21526 */ 21527 public static int generateViewId() { 21528 for (;;) { 21529 final int result = sNextGeneratedId.get(); 21530 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 21531 int newValue = result + 1; 21532 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 21533 if (sNextGeneratedId.compareAndSet(result, newValue)) { 21534 return result; 21535 } 21536 } 21537 } 21538 21539 /** 21540 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 21541 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 21542 * a normal View or a ViewGroup with 21543 * {@link android.view.ViewGroup#isTransitionGroup()} true. 21544 * @hide 21545 */ 21546 public void captureTransitioningViews(List<View> transitioningViews) { 21547 if (getVisibility() == View.VISIBLE) { 21548 transitioningViews.add(this); 21549 } 21550 } 21551 21552 /** 21553 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 21554 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 21555 * @hide 21556 */ 21557 public void findNamedViews(Map<String, View> namedElements) { 21558 if (getVisibility() == VISIBLE || mGhostView != null) { 21559 String transitionName = getTransitionName(); 21560 if (transitionName != null) { 21561 namedElements.put(transitionName, this); 21562 } 21563 } 21564 } 21565 21566 /** 21567 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 21568 * The default implementation does not care the location or event types, but some subclasses 21569 * may use it (such as WebViews). 21570 * @param event The MotionEvent from a mouse 21571 * @param x The x position of the event, local to the view 21572 * @param y The y position of the event, local to the view 21573 * @see PointerIcon 21574 */ 21575 public PointerIcon getPointerIcon(MotionEvent event, float x, float y) { 21576 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 21577 return PointerIcon.getSystemIcon(mContext, PointerIcon.STYLE_ARROW); 21578 } 21579 return mPointerIcon; 21580 } 21581 21582 /** 21583 * Set the pointer icon for the current view. 21584 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 21585 */ 21586 public void setPointerIcon(PointerIcon pointerIcon) { 21587 mPointerIcon = pointerIcon; 21588 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 21589 return; 21590 } 21591 try { 21592 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 21593 } catch (RemoteException e) { 21594 } 21595 } 21596 21597 /** 21598 * Request capturing further mouse events. 21599 * 21600 * When the view captures, the mouse pointer icon will disappear and will not change its 21601 * position. Further mouse events will come to the capturing view, and the mouse movements 21602 * will can be detected through {@link MotionEvent#AXIS_RELATIVE_X} and 21603 * {@link MotionEvent#AXIS_RELATIVE_Y}. Non-mouse events (touchscreens, or stylus) will not 21604 * be affected. 21605 * 21606 * The capture will be released through {@link #releasePointerCapture()}, or will be lost 21607 * automatically when the view or containing window disappear. 21608 * 21609 * @return true when succeeds. 21610 * @see #releasePointerCapture() 21611 * @see #hasPointerCapture() 21612 */ 21613 public void setPointerCapture() { 21614 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21615 if (viewRootImpl != null) { 21616 viewRootImpl.setPointerCapture(this); 21617 } 21618 } 21619 21620 21621 /** 21622 * Release the current capture of mouse events. 21623 * 21624 * If the view does not have the capture, it will do nothing. 21625 * @see #setPointerCapture() 21626 * @see #hasPointerCapture() 21627 */ 21628 public void releasePointerCapture() { 21629 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21630 if (viewRootImpl != null) { 21631 viewRootImpl.releasePointerCapture(this); 21632 } 21633 } 21634 21635 /** 21636 * Checks the capture status of mouse events. 21637 * 21638 * @return true if the view has the capture. 21639 * @see #setPointerCapture() 21640 * @see #hasPointerCapture() 21641 */ 21642 public boolean hasPointerCapture() { 21643 final ViewRootImpl viewRootImpl = getViewRootImpl(); 21644 return (viewRootImpl != null) && viewRootImpl.hasPointerCapture(this); 21645 } 21646 21647 // 21648 // Properties 21649 // 21650 /** 21651 * A Property wrapper around the <code>alpha</code> functionality handled by the 21652 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 21653 */ 21654 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 21655 @Override 21656 public void setValue(View object, float value) { 21657 object.setAlpha(value); 21658 } 21659 21660 @Override 21661 public Float get(View object) { 21662 return object.getAlpha(); 21663 } 21664 }; 21665 21666 /** 21667 * A Property wrapper around the <code>translationX</code> functionality handled by the 21668 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 21669 */ 21670 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 21671 @Override 21672 public void setValue(View object, float value) { 21673 object.setTranslationX(value); 21674 } 21675 21676 @Override 21677 public Float get(View object) { 21678 return object.getTranslationX(); 21679 } 21680 }; 21681 21682 /** 21683 * A Property wrapper around the <code>translationY</code> functionality handled by the 21684 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 21685 */ 21686 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 21687 @Override 21688 public void setValue(View object, float value) { 21689 object.setTranslationY(value); 21690 } 21691 21692 @Override 21693 public Float get(View object) { 21694 return object.getTranslationY(); 21695 } 21696 }; 21697 21698 /** 21699 * A Property wrapper around the <code>translationZ</code> functionality handled by the 21700 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 21701 */ 21702 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 21703 @Override 21704 public void setValue(View object, float value) { 21705 object.setTranslationZ(value); 21706 } 21707 21708 @Override 21709 public Float get(View object) { 21710 return object.getTranslationZ(); 21711 } 21712 }; 21713 21714 /** 21715 * A Property wrapper around the <code>x</code> functionality handled by the 21716 * {@link View#setX(float)} and {@link View#getX()} methods. 21717 */ 21718 public static final Property<View, Float> X = new FloatProperty<View>("x") { 21719 @Override 21720 public void setValue(View object, float value) { 21721 object.setX(value); 21722 } 21723 21724 @Override 21725 public Float get(View object) { 21726 return object.getX(); 21727 } 21728 }; 21729 21730 /** 21731 * A Property wrapper around the <code>y</code> functionality handled by the 21732 * {@link View#setY(float)} and {@link View#getY()} methods. 21733 */ 21734 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 21735 @Override 21736 public void setValue(View object, float value) { 21737 object.setY(value); 21738 } 21739 21740 @Override 21741 public Float get(View object) { 21742 return object.getY(); 21743 } 21744 }; 21745 21746 /** 21747 * A Property wrapper around the <code>z</code> functionality handled by the 21748 * {@link View#setZ(float)} and {@link View#getZ()} methods. 21749 */ 21750 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 21751 @Override 21752 public void setValue(View object, float value) { 21753 object.setZ(value); 21754 } 21755 21756 @Override 21757 public Float get(View object) { 21758 return object.getZ(); 21759 } 21760 }; 21761 21762 /** 21763 * A Property wrapper around the <code>rotation</code> functionality handled by the 21764 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 21765 */ 21766 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 21767 @Override 21768 public void setValue(View object, float value) { 21769 object.setRotation(value); 21770 } 21771 21772 @Override 21773 public Float get(View object) { 21774 return object.getRotation(); 21775 } 21776 }; 21777 21778 /** 21779 * A Property wrapper around the <code>rotationX</code> functionality handled by the 21780 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 21781 */ 21782 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 21783 @Override 21784 public void setValue(View object, float value) { 21785 object.setRotationX(value); 21786 } 21787 21788 @Override 21789 public Float get(View object) { 21790 return object.getRotationX(); 21791 } 21792 }; 21793 21794 /** 21795 * A Property wrapper around the <code>rotationY</code> functionality handled by the 21796 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 21797 */ 21798 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 21799 @Override 21800 public void setValue(View object, float value) { 21801 object.setRotationY(value); 21802 } 21803 21804 @Override 21805 public Float get(View object) { 21806 return object.getRotationY(); 21807 } 21808 }; 21809 21810 /** 21811 * A Property wrapper around the <code>scaleX</code> functionality handled by the 21812 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 21813 */ 21814 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 21815 @Override 21816 public void setValue(View object, float value) { 21817 object.setScaleX(value); 21818 } 21819 21820 @Override 21821 public Float get(View object) { 21822 return object.getScaleX(); 21823 } 21824 }; 21825 21826 /** 21827 * A Property wrapper around the <code>scaleY</code> functionality handled by the 21828 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 21829 */ 21830 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 21831 @Override 21832 public void setValue(View object, float value) { 21833 object.setScaleY(value); 21834 } 21835 21836 @Override 21837 public Float get(View object) { 21838 return object.getScaleY(); 21839 } 21840 }; 21841 21842 /** 21843 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 21844 * Each MeasureSpec represents a requirement for either the width or the height. 21845 * A MeasureSpec is comprised of a size and a mode. There are three possible 21846 * modes: 21847 * <dl> 21848 * <dt>UNSPECIFIED</dt> 21849 * <dd> 21850 * The parent has not imposed any constraint on the child. It can be whatever size 21851 * it wants. 21852 * </dd> 21853 * 21854 * <dt>EXACTLY</dt> 21855 * <dd> 21856 * The parent has determined an exact size for the child. The child is going to be 21857 * given those bounds regardless of how big it wants to be. 21858 * </dd> 21859 * 21860 * <dt>AT_MOST</dt> 21861 * <dd> 21862 * The child can be as large as it wants up to the specified size. 21863 * </dd> 21864 * </dl> 21865 * 21866 * MeasureSpecs are implemented as ints to reduce object allocation. This class 21867 * is provided to pack and unpack the <size, mode> tuple into the int. 21868 */ 21869 public static class MeasureSpec { 21870 private static final int MODE_SHIFT = 30; 21871 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 21872 21873 /** @hide */ 21874 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 21875 @Retention(RetentionPolicy.SOURCE) 21876 public @interface MeasureSpecMode {} 21877 21878 /** 21879 * Measure specification mode: The parent has not imposed any constraint 21880 * on the child. It can be whatever size it wants. 21881 */ 21882 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 21883 21884 /** 21885 * Measure specification mode: The parent has determined an exact size 21886 * for the child. The child is going to be given those bounds regardless 21887 * of how big it wants to be. 21888 */ 21889 public static final int EXACTLY = 1 << MODE_SHIFT; 21890 21891 /** 21892 * Measure specification mode: The child can be as large as it wants up 21893 * to the specified size. 21894 */ 21895 public static final int AT_MOST = 2 << MODE_SHIFT; 21896 21897 /** 21898 * Creates a measure specification based on the supplied size and mode. 21899 * 21900 * The mode must always be one of the following: 21901 * <ul> 21902 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 21903 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 21904 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 21905 * </ul> 21906 * 21907 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 21908 * implementation was such that the order of arguments did not matter 21909 * and overflow in either value could impact the resulting MeasureSpec. 21910 * {@link android.widget.RelativeLayout} was affected by this bug. 21911 * Apps targeting API levels greater than 17 will get the fixed, more strict 21912 * behavior.</p> 21913 * 21914 * @param size the size of the measure specification 21915 * @param mode the mode of the measure specification 21916 * @return the measure specification based on size and mode 21917 */ 21918 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 21919 @MeasureSpecMode int mode) { 21920 if (sUseBrokenMakeMeasureSpec) { 21921 return size + mode; 21922 } else { 21923 return (size & ~MODE_MASK) | (mode & MODE_MASK); 21924 } 21925 } 21926 21927 /** 21928 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 21929 * will automatically get a size of 0. Older apps expect this. 21930 * 21931 * @hide internal use only for compatibility with system widgets and older apps 21932 */ 21933 public static int makeSafeMeasureSpec(int size, int mode) { 21934 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 21935 return 0; 21936 } 21937 return makeMeasureSpec(size, mode); 21938 } 21939 21940 /** 21941 * Extracts the mode from the supplied measure specification. 21942 * 21943 * @param measureSpec the measure specification to extract the mode from 21944 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 21945 * {@link android.view.View.MeasureSpec#AT_MOST} or 21946 * {@link android.view.View.MeasureSpec#EXACTLY} 21947 */ 21948 @MeasureSpecMode 21949 public static int getMode(int measureSpec) { 21950 //noinspection ResourceType 21951 return (measureSpec & MODE_MASK); 21952 } 21953 21954 /** 21955 * Extracts the size from the supplied measure specification. 21956 * 21957 * @param measureSpec the measure specification to extract the size from 21958 * @return the size in pixels defined in the supplied measure specification 21959 */ 21960 public static int getSize(int measureSpec) { 21961 return (measureSpec & ~MODE_MASK); 21962 } 21963 21964 static int adjust(int measureSpec, int delta) { 21965 final int mode = getMode(measureSpec); 21966 int size = getSize(measureSpec); 21967 if (mode == UNSPECIFIED) { 21968 // No need to adjust size for UNSPECIFIED mode. 21969 return makeMeasureSpec(size, UNSPECIFIED); 21970 } 21971 size += delta; 21972 if (size < 0) { 21973 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 21974 ") spec: " + toString(measureSpec) + " delta: " + delta); 21975 size = 0; 21976 } 21977 return makeMeasureSpec(size, mode); 21978 } 21979 21980 /** 21981 * Returns a String representation of the specified measure 21982 * specification. 21983 * 21984 * @param measureSpec the measure specification to convert to a String 21985 * @return a String with the following format: "MeasureSpec: MODE SIZE" 21986 */ 21987 public static String toString(int measureSpec) { 21988 int mode = getMode(measureSpec); 21989 int size = getSize(measureSpec); 21990 21991 StringBuilder sb = new StringBuilder("MeasureSpec: "); 21992 21993 if (mode == UNSPECIFIED) 21994 sb.append("UNSPECIFIED "); 21995 else if (mode == EXACTLY) 21996 sb.append("EXACTLY "); 21997 else if (mode == AT_MOST) 21998 sb.append("AT_MOST "); 21999 else 22000 sb.append(mode).append(" "); 22001 22002 sb.append(size); 22003 return sb.toString(); 22004 } 22005 } 22006 22007 private final class CheckForLongPress implements Runnable { 22008 private int mOriginalWindowAttachCount; 22009 private float mX; 22010 private float mY; 22011 22012 @Override 22013 public void run() { 22014 if (isPressed() && (mParent != null) 22015 && mOriginalWindowAttachCount == mWindowAttachCount) { 22016 if (performLongClick(mX, mY)) { 22017 mHasPerformedLongPress = true; 22018 } 22019 } 22020 } 22021 22022 public void setAnchor(float x, float y) { 22023 mX = x; 22024 mY = y; 22025 } 22026 22027 public void rememberWindowAttachCount() { 22028 mOriginalWindowAttachCount = mWindowAttachCount; 22029 } 22030 } 22031 22032 private final class CheckForTap implements Runnable { 22033 public float x; 22034 public float y; 22035 22036 @Override 22037 public void run() { 22038 mPrivateFlags &= ~PFLAG_PREPRESSED; 22039 setPressed(true, x, y); 22040 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 22041 } 22042 } 22043 22044 private final class PerformClick implements Runnable { 22045 @Override 22046 public void run() { 22047 performClick(); 22048 } 22049 } 22050 22051 /** 22052 * This method returns a ViewPropertyAnimator object, which can be used to animate 22053 * specific properties on this View. 22054 * 22055 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 22056 */ 22057 public ViewPropertyAnimator animate() { 22058 if (mAnimator == null) { 22059 mAnimator = new ViewPropertyAnimator(this); 22060 } 22061 return mAnimator; 22062 } 22063 22064 /** 22065 * Sets the name of the View to be used to identify Views in Transitions. 22066 * Names should be unique in the View hierarchy. 22067 * 22068 * @param transitionName The name of the View to uniquely identify it for Transitions. 22069 */ 22070 public final void setTransitionName(String transitionName) { 22071 mTransitionName = transitionName; 22072 } 22073 22074 /** 22075 * Returns the name of the View to be used to identify Views in Transitions. 22076 * Names should be unique in the View hierarchy. 22077 * 22078 * <p>This returns null if the View has not been given a name.</p> 22079 * 22080 * @return The name used of the View to be used to identify Views in Transitions or null 22081 * if no name has been given. 22082 */ 22083 @ViewDebug.ExportedProperty 22084 public String getTransitionName() { 22085 return mTransitionName; 22086 } 22087 22088 /** 22089 * @hide 22090 */ 22091 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data) { 22092 // Do nothing. 22093 } 22094 22095 /** 22096 * Interface definition for a callback to be invoked when a hardware key event is 22097 * dispatched to this view. The callback will be invoked before the key event is 22098 * given to the view. This is only useful for hardware keyboards; a software input 22099 * method has no obligation to trigger this listener. 22100 */ 22101 public interface OnKeyListener { 22102 /** 22103 * Called when a hardware key is dispatched to a view. This allows listeners to 22104 * get a chance to respond before the target view. 22105 * <p>Key presses in software keyboards will generally NOT trigger this method, 22106 * although some may elect to do so in some situations. Do not assume a 22107 * software input method has to be key-based; even if it is, it may use key presses 22108 * in a different way than you expect, so there is no way to reliably catch soft 22109 * input key presses. 22110 * 22111 * @param v The view the key has been dispatched to. 22112 * @param keyCode The code for the physical key that was pressed 22113 * @param event The KeyEvent object containing full information about 22114 * the event. 22115 * @return True if the listener has consumed the event, false otherwise. 22116 */ 22117 boolean onKey(View v, int keyCode, KeyEvent event); 22118 } 22119 22120 /** 22121 * Interface definition for a callback to be invoked when a touch event is 22122 * dispatched to this view. The callback will be invoked before the touch 22123 * event is given to the view. 22124 */ 22125 public interface OnTouchListener { 22126 /** 22127 * Called when a touch event is dispatched to a view. This allows listeners to 22128 * get a chance to respond before the target view. 22129 * 22130 * @param v The view the touch event has been dispatched to. 22131 * @param event The MotionEvent object containing full information about 22132 * the event. 22133 * @return True if the listener has consumed the event, false otherwise. 22134 */ 22135 boolean onTouch(View v, MotionEvent event); 22136 } 22137 22138 /** 22139 * Interface definition for a callback to be invoked when a hover event is 22140 * dispatched to this view. The callback will be invoked before the hover 22141 * event is given to the view. 22142 */ 22143 public interface OnHoverListener { 22144 /** 22145 * Called when a hover event is dispatched to a view. This allows listeners to 22146 * get a chance to respond before the target view. 22147 * 22148 * @param v The view the hover event has been dispatched to. 22149 * @param event The MotionEvent object containing full information about 22150 * the event. 22151 * @return True if the listener has consumed the event, false otherwise. 22152 */ 22153 boolean onHover(View v, MotionEvent event); 22154 } 22155 22156 /** 22157 * Interface definition for a callback to be invoked when a generic motion event is 22158 * dispatched to this view. The callback will be invoked before the generic motion 22159 * event is given to the view. 22160 */ 22161 public interface OnGenericMotionListener { 22162 /** 22163 * Called when a generic motion event is dispatched to a view. This allows listeners to 22164 * get a chance to respond before the target view. 22165 * 22166 * @param v The view the generic motion event has been dispatched to. 22167 * @param event The MotionEvent object containing full information about 22168 * the event. 22169 * @return True if the listener has consumed the event, false otherwise. 22170 */ 22171 boolean onGenericMotion(View v, MotionEvent event); 22172 } 22173 22174 /** 22175 * Interface definition for a callback to be invoked when a view has been clicked and held. 22176 */ 22177 public interface OnLongClickListener { 22178 /** 22179 * Called when a view has been clicked and held. 22180 * 22181 * @param v The view that was clicked and held. 22182 * 22183 * @return true if the callback consumed the long click, false otherwise. 22184 */ 22185 boolean onLongClick(View v); 22186 } 22187 22188 /** 22189 * Interface definition for a callback to be invoked when a drag is being dispatched 22190 * to this view. The callback will be invoked before the hosting view's own 22191 * onDrag(event) method. If the listener wants to fall back to the hosting view's 22192 * onDrag(event) behavior, it should return 'false' from this callback. 22193 * 22194 * <div class="special reference"> 22195 * <h3>Developer Guides</h3> 22196 * <p>For a guide to implementing drag and drop features, read the 22197 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22198 * </div> 22199 */ 22200 public interface OnDragListener { 22201 /** 22202 * Called when a drag event is dispatched to a view. This allows listeners 22203 * to get a chance to override base View behavior. 22204 * 22205 * @param v The View that received the drag event. 22206 * @param event The {@link android.view.DragEvent} object for the drag event. 22207 * @return {@code true} if the drag event was handled successfully, or {@code false} 22208 * if the drag event was not handled. Note that {@code false} will trigger the View 22209 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 22210 */ 22211 boolean onDrag(View v, DragEvent event); 22212 } 22213 22214 /** 22215 * Interface definition for a callback to be invoked when the focus state of 22216 * a view changed. 22217 */ 22218 public interface OnFocusChangeListener { 22219 /** 22220 * Called when the focus state of a view has changed. 22221 * 22222 * @param v The view whose state has changed. 22223 * @param hasFocus The new focus state of v. 22224 */ 22225 void onFocusChange(View v, boolean hasFocus); 22226 } 22227 22228 /** 22229 * Interface definition for a callback to be invoked when a view is clicked. 22230 */ 22231 public interface OnClickListener { 22232 /** 22233 * Called when a view has been clicked. 22234 * 22235 * @param v The view that was clicked. 22236 */ 22237 void onClick(View v); 22238 } 22239 22240 /** 22241 * Interface definition for a callback to be invoked when a view is context clicked. 22242 */ 22243 public interface OnContextClickListener { 22244 /** 22245 * Called when a view is context clicked. 22246 * 22247 * @param v The view that has been context clicked. 22248 * @return true if the callback consumed the context click, false otherwise. 22249 */ 22250 boolean onContextClick(View v); 22251 } 22252 22253 /** 22254 * Interface definition for a callback to be invoked when the context menu 22255 * for this view is being built. 22256 */ 22257 public interface OnCreateContextMenuListener { 22258 /** 22259 * Called when the context menu for this view is being built. It is not 22260 * safe to hold onto the menu after this method returns. 22261 * 22262 * @param menu The context menu that is being built 22263 * @param v The view for which the context menu is being built 22264 * @param menuInfo Extra information about the item for which the 22265 * context menu should be shown. This information will vary 22266 * depending on the class of v. 22267 */ 22268 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 22269 } 22270 22271 /** 22272 * Interface definition for a callback to be invoked when the status bar changes 22273 * visibility. This reports <strong>global</strong> changes to the system UI 22274 * state, not what the application is requesting. 22275 * 22276 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 22277 */ 22278 public interface OnSystemUiVisibilityChangeListener { 22279 /** 22280 * Called when the status bar changes visibility because of a call to 22281 * {@link View#setSystemUiVisibility(int)}. 22282 * 22283 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22284 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 22285 * This tells you the <strong>global</strong> state of these UI visibility 22286 * flags, not what your app is currently applying. 22287 */ 22288 public void onSystemUiVisibilityChange(int visibility); 22289 } 22290 22291 /** 22292 * Interface definition for a callback to be invoked when this view is attached 22293 * or detached from its window. 22294 */ 22295 public interface OnAttachStateChangeListener { 22296 /** 22297 * Called when the view is attached to a window. 22298 * @param v The view that was attached 22299 */ 22300 public void onViewAttachedToWindow(View v); 22301 /** 22302 * Called when the view is detached from a window. 22303 * @param v The view that was detached 22304 */ 22305 public void onViewDetachedFromWindow(View v); 22306 } 22307 22308 /** 22309 * Listener for applying window insets on a view in a custom way. 22310 * 22311 * <p>Apps may choose to implement this interface if they want to apply custom policy 22312 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 22313 * is set, its 22314 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 22315 * method will be called instead of the View's own 22316 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 22317 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 22318 * the View's normal behavior as part of its own.</p> 22319 */ 22320 public interface OnApplyWindowInsetsListener { 22321 /** 22322 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 22323 * on a View, this listener method will be called instead of the view's own 22324 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 22325 * 22326 * @param v The view applying window insets 22327 * @param insets The insets to apply 22328 * @return The insets supplied, minus any insets that were consumed 22329 */ 22330 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 22331 } 22332 22333 private final class UnsetPressedState implements Runnable { 22334 @Override 22335 public void run() { 22336 setPressed(false); 22337 } 22338 } 22339 22340 /** 22341 * Base class for derived classes that want to save and restore their own 22342 * state in {@link android.view.View#onSaveInstanceState()}. 22343 */ 22344 public static class BaseSavedState extends AbsSavedState { 22345 String mStartActivityRequestWhoSaved; 22346 22347 /** 22348 * Constructor used when reading from a parcel. Reads the state of the superclass. 22349 * 22350 * @param source 22351 */ 22352 public BaseSavedState(Parcel source) { 22353 super(source); 22354 mStartActivityRequestWhoSaved = source.readString(); 22355 } 22356 22357 /** 22358 * Constructor called by derived classes when creating their SavedState objects 22359 * 22360 * @param superState The state of the superclass of this view 22361 */ 22362 public BaseSavedState(Parcelable superState) { 22363 super(superState); 22364 } 22365 22366 @Override 22367 public void writeToParcel(Parcel out, int flags) { 22368 super.writeToParcel(out, flags); 22369 out.writeString(mStartActivityRequestWhoSaved); 22370 } 22371 22372 public static final Parcelable.Creator<BaseSavedState> CREATOR = 22373 new Parcelable.Creator<BaseSavedState>() { 22374 public BaseSavedState createFromParcel(Parcel in) { 22375 return new BaseSavedState(in); 22376 } 22377 22378 public BaseSavedState[] newArray(int size) { 22379 return new BaseSavedState[size]; 22380 } 22381 }; 22382 } 22383 22384 /** 22385 * A set of information given to a view when it is attached to its parent 22386 * window. 22387 */ 22388 final static class AttachInfo { 22389 interface Callbacks { 22390 void playSoundEffect(int effectId); 22391 boolean performHapticFeedback(int effectId, boolean always); 22392 } 22393 22394 /** 22395 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 22396 * to a Handler. This class contains the target (View) to invalidate and 22397 * the coordinates of the dirty rectangle. 22398 * 22399 * For performance purposes, this class also implements a pool of up to 22400 * POOL_LIMIT objects that get reused. This reduces memory allocations 22401 * whenever possible. 22402 */ 22403 static class InvalidateInfo { 22404 private static final int POOL_LIMIT = 10; 22405 22406 private static final SynchronizedPool<InvalidateInfo> sPool = 22407 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 22408 22409 View target; 22410 22411 int left; 22412 int top; 22413 int right; 22414 int bottom; 22415 22416 public static InvalidateInfo obtain() { 22417 InvalidateInfo instance = sPool.acquire(); 22418 return (instance != null) ? instance : new InvalidateInfo(); 22419 } 22420 22421 public void recycle() { 22422 target = null; 22423 sPool.release(this); 22424 } 22425 } 22426 22427 final IWindowSession mSession; 22428 22429 final IWindow mWindow; 22430 22431 final IBinder mWindowToken; 22432 22433 final Display mDisplay; 22434 22435 final Callbacks mRootCallbacks; 22436 22437 IWindowId mIWindowId; 22438 WindowId mWindowId; 22439 22440 /** 22441 * The top view of the hierarchy. 22442 */ 22443 View mRootView; 22444 22445 IBinder mPanelParentWindowToken; 22446 22447 boolean mHardwareAccelerated; 22448 boolean mHardwareAccelerationRequested; 22449 ThreadedRenderer mHardwareRenderer; 22450 List<RenderNode> mPendingAnimatingRenderNodes; 22451 22452 /** 22453 * The state of the display to which the window is attached, as reported 22454 * by {@link Display#getState()}. Note that the display state constants 22455 * declared by {@link Display} do not exactly line up with the screen state 22456 * constants declared by {@link View} (there are more display states than 22457 * screen states). 22458 */ 22459 int mDisplayState = Display.STATE_UNKNOWN; 22460 22461 /** 22462 * Scale factor used by the compatibility mode 22463 */ 22464 float mApplicationScale; 22465 22466 /** 22467 * Indicates whether the application is in compatibility mode 22468 */ 22469 boolean mScalingRequired; 22470 22471 /** 22472 * Left position of this view's window 22473 */ 22474 int mWindowLeft; 22475 22476 /** 22477 * Top position of this view's window 22478 */ 22479 int mWindowTop; 22480 22481 /** 22482 * Indicates whether views need to use 32-bit drawing caches 22483 */ 22484 boolean mUse32BitDrawingCache; 22485 22486 /** 22487 * For windows that are full-screen but using insets to layout inside 22488 * of the screen areas, these are the current insets to appear inside 22489 * the overscan area of the display. 22490 */ 22491 final Rect mOverscanInsets = new Rect(); 22492 22493 /** 22494 * For windows that are full-screen but using insets to layout inside 22495 * of the screen decorations, these are the current insets for the 22496 * content of the window. 22497 */ 22498 final Rect mContentInsets = new Rect(); 22499 22500 /** 22501 * For windows that are full-screen but using insets to layout inside 22502 * of the screen decorations, these are the current insets for the 22503 * actual visible parts of the window. 22504 */ 22505 final Rect mVisibleInsets = new Rect(); 22506 22507 /** 22508 * For windows that are full-screen but using insets to layout inside 22509 * of the screen decorations, these are the current insets for the 22510 * stable system windows. 22511 */ 22512 final Rect mStableInsets = new Rect(); 22513 22514 /** 22515 * For windows that include areas that are not covered by real surface these are the outsets 22516 * for real surface. 22517 */ 22518 final Rect mOutsets = new Rect(); 22519 22520 /** 22521 * In multi-window we force show the navigation bar. Because we don't want that the surface 22522 * size changes in this mode, we instead have a flag whether the navigation bar size should 22523 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 22524 */ 22525 boolean mAlwaysConsumeNavBar; 22526 22527 /** 22528 * The internal insets given by this window. This value is 22529 * supplied by the client (through 22530 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 22531 * be given to the window manager when changed to be used in laying 22532 * out windows behind it. 22533 */ 22534 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 22535 = new ViewTreeObserver.InternalInsetsInfo(); 22536 22537 /** 22538 * Set to true when mGivenInternalInsets is non-empty. 22539 */ 22540 boolean mHasNonEmptyGivenInternalInsets; 22541 22542 /** 22543 * All views in the window's hierarchy that serve as scroll containers, 22544 * used to determine if the window can be resized or must be panned 22545 * to adjust for a soft input area. 22546 */ 22547 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 22548 22549 final KeyEvent.DispatcherState mKeyDispatchState 22550 = new KeyEvent.DispatcherState(); 22551 22552 /** 22553 * Indicates whether the view's window currently has the focus. 22554 */ 22555 boolean mHasWindowFocus; 22556 22557 /** 22558 * The current visibility of the window. 22559 */ 22560 int mWindowVisibility; 22561 22562 /** 22563 * Indicates the time at which drawing started to occur. 22564 */ 22565 long mDrawingTime; 22566 22567 /** 22568 * Indicates whether or not ignoring the DIRTY_MASK flags. 22569 */ 22570 boolean mIgnoreDirtyState; 22571 22572 /** 22573 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 22574 * to avoid clearing that flag prematurely. 22575 */ 22576 boolean mSetIgnoreDirtyState = false; 22577 22578 /** 22579 * Indicates whether the view's window is currently in touch mode. 22580 */ 22581 boolean mInTouchMode; 22582 22583 /** 22584 * Indicates whether the view has requested unbuffered input dispatching for the current 22585 * event stream. 22586 */ 22587 boolean mUnbufferedDispatchRequested; 22588 22589 /** 22590 * Indicates that ViewAncestor should trigger a global layout change 22591 * the next time it performs a traversal 22592 */ 22593 boolean mRecomputeGlobalAttributes; 22594 22595 /** 22596 * Always report new attributes at next traversal. 22597 */ 22598 boolean mForceReportNewAttributes; 22599 22600 /** 22601 * Set during a traveral if any views want to keep the screen on. 22602 */ 22603 boolean mKeepScreenOn; 22604 22605 /** 22606 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 22607 */ 22608 int mSystemUiVisibility; 22609 22610 /** 22611 * Hack to force certain system UI visibility flags to be cleared. 22612 */ 22613 int mDisabledSystemUiVisibility; 22614 22615 /** 22616 * Last global system UI visibility reported by the window manager. 22617 */ 22618 int mGlobalSystemUiVisibility; 22619 22620 /** 22621 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 22622 * attached. 22623 */ 22624 boolean mHasSystemUiListeners; 22625 22626 /** 22627 * Set if the window has requested to extend into the overscan region 22628 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 22629 */ 22630 boolean mOverscanRequested; 22631 22632 /** 22633 * Set if the visibility of any views has changed. 22634 */ 22635 boolean mViewVisibilityChanged; 22636 22637 /** 22638 * Set to true if a view has been scrolled. 22639 */ 22640 boolean mViewScrollChanged; 22641 22642 /** 22643 * Set to true if high contrast mode enabled 22644 */ 22645 boolean mHighContrastText; 22646 22647 /** 22648 * Set to true if a pointer event is currently being handled. 22649 */ 22650 boolean mHandlingPointerEvent; 22651 22652 /** 22653 * Global to the view hierarchy used as a temporary for dealing with 22654 * x/y points in the transparent region computations. 22655 */ 22656 final int[] mTransparentLocation = new int[2]; 22657 22658 /** 22659 * Global to the view hierarchy used as a temporary for dealing with 22660 * x/y points in the ViewGroup.invalidateChild implementation. 22661 */ 22662 final int[] mInvalidateChildLocation = new int[2]; 22663 22664 /** 22665 * Global to the view hierarchy used as a temporary for dealng with 22666 * computing absolute on-screen location. 22667 */ 22668 final int[] mTmpLocation = new int[2]; 22669 22670 /** 22671 * Global to the view hierarchy used as a temporary for dealing with 22672 * x/y location when view is transformed. 22673 */ 22674 final float[] mTmpTransformLocation = new float[2]; 22675 22676 /** 22677 * The view tree observer used to dispatch global events like 22678 * layout, pre-draw, touch mode change, etc. 22679 */ 22680 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 22681 22682 /** 22683 * A Canvas used by the view hierarchy to perform bitmap caching. 22684 */ 22685 Canvas mCanvas; 22686 22687 /** 22688 * The view root impl. 22689 */ 22690 final ViewRootImpl mViewRootImpl; 22691 22692 /** 22693 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 22694 * handler can be used to pump events in the UI events queue. 22695 */ 22696 final Handler mHandler; 22697 22698 /** 22699 * Temporary for use in computing invalidate rectangles while 22700 * calling up the hierarchy. 22701 */ 22702 final Rect mTmpInvalRect = new Rect(); 22703 22704 /** 22705 * Temporary for use in computing hit areas with transformed views 22706 */ 22707 final RectF mTmpTransformRect = new RectF(); 22708 22709 /** 22710 * Temporary for use in computing hit areas with transformed views 22711 */ 22712 final RectF mTmpTransformRect1 = new RectF(); 22713 22714 /** 22715 * Temporary list of rectanges. 22716 */ 22717 final List<RectF> mTmpRectList = new ArrayList<>(); 22718 22719 /** 22720 * Temporary for use in transforming invalidation rect 22721 */ 22722 final Matrix mTmpMatrix = new Matrix(); 22723 22724 /** 22725 * Temporary for use in transforming invalidation rect 22726 */ 22727 final Transformation mTmpTransformation = new Transformation(); 22728 22729 /** 22730 * Temporary for use in querying outlines from OutlineProviders 22731 */ 22732 final Outline mTmpOutline = new Outline(); 22733 22734 /** 22735 * Temporary list for use in collecting focusable descendents of a view. 22736 */ 22737 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 22738 22739 /** 22740 * The id of the window for accessibility purposes. 22741 */ 22742 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 22743 22744 /** 22745 * Flags related to accessibility processing. 22746 * 22747 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 22748 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 22749 */ 22750 int mAccessibilityFetchFlags; 22751 22752 /** 22753 * The drawable for highlighting accessibility focus. 22754 */ 22755 Drawable mAccessibilityFocusDrawable; 22756 22757 /** 22758 * Show where the margins, bounds and layout bounds are for each view. 22759 */ 22760 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 22761 22762 /** 22763 * Point used to compute visible regions. 22764 */ 22765 final Point mPoint = new Point(); 22766 22767 /** 22768 * Used to track which View originated a requestLayout() call, used when 22769 * requestLayout() is called during layout. 22770 */ 22771 View mViewRequestingLayout; 22772 22773 /** 22774 * Used to track views that need (at least) a partial relayout at their current size 22775 * during the next traversal. 22776 */ 22777 List<View> mPartialLayoutViews = new ArrayList<>(); 22778 22779 /** 22780 * Swapped with mPartialLayoutViews during layout to avoid concurrent 22781 * modification. Lazily assigned during ViewRootImpl layout. 22782 */ 22783 List<View> mEmptyPartialLayoutViews; 22784 22785 /** 22786 * Used to track the identity of the current drag operation. 22787 */ 22788 IBinder mDragToken; 22789 22790 /** 22791 * The drag shadow surface for the current drag operation. 22792 */ 22793 public Surface mDragSurface; 22794 22795 /** 22796 * Creates a new set of attachment information with the specified 22797 * events handler and thread. 22798 * 22799 * @param handler the events handler the view must use 22800 */ 22801 AttachInfo(IWindowSession session, IWindow window, Display display, 22802 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 22803 mSession = session; 22804 mWindow = window; 22805 mWindowToken = window.asBinder(); 22806 mDisplay = display; 22807 mViewRootImpl = viewRootImpl; 22808 mHandler = handler; 22809 mRootCallbacks = effectPlayer; 22810 } 22811 } 22812 22813 /** 22814 * <p>ScrollabilityCache holds various fields used by a View when scrolling 22815 * is supported. This avoids keeping too many unused fields in most 22816 * instances of View.</p> 22817 */ 22818 private static class ScrollabilityCache implements Runnable { 22819 22820 /** 22821 * Scrollbars are not visible 22822 */ 22823 public static final int OFF = 0; 22824 22825 /** 22826 * Scrollbars are visible 22827 */ 22828 public static final int ON = 1; 22829 22830 /** 22831 * Scrollbars are fading away 22832 */ 22833 public static final int FADING = 2; 22834 22835 public boolean fadeScrollBars; 22836 22837 public int fadingEdgeLength; 22838 public int scrollBarDefaultDelayBeforeFade; 22839 public int scrollBarFadeDuration; 22840 22841 public int scrollBarSize; 22842 public ScrollBarDrawable scrollBar; 22843 public float[] interpolatorValues; 22844 public View host; 22845 22846 public final Paint paint; 22847 public final Matrix matrix; 22848 public Shader shader; 22849 22850 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 22851 22852 private static final float[] OPAQUE = { 255 }; 22853 private static final float[] TRANSPARENT = { 0.0f }; 22854 22855 /** 22856 * When fading should start. This time moves into the future every time 22857 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 22858 */ 22859 public long fadeStartTime; 22860 22861 22862 /** 22863 * The current state of the scrollbars: ON, OFF, or FADING 22864 */ 22865 public int state = OFF; 22866 22867 private int mLastColor; 22868 22869 public final Rect mScrollBarBounds = new Rect(); 22870 22871 public static final int NOT_DRAGGING = 0; 22872 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 22873 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 22874 public int mScrollBarDraggingState = NOT_DRAGGING; 22875 22876 public float mScrollBarDraggingPos = 0; 22877 22878 public ScrollabilityCache(ViewConfiguration configuration, View host) { 22879 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 22880 scrollBarSize = configuration.getScaledScrollBarSize(); 22881 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 22882 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 22883 22884 paint = new Paint(); 22885 matrix = new Matrix(); 22886 // use use a height of 1, and then wack the matrix each time we 22887 // actually use it. 22888 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 22889 paint.setShader(shader); 22890 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 22891 22892 this.host = host; 22893 } 22894 22895 public void setFadeColor(int color) { 22896 if (color != mLastColor) { 22897 mLastColor = color; 22898 22899 if (color != 0) { 22900 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 22901 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 22902 paint.setShader(shader); 22903 // Restore the default transfer mode (src_over) 22904 paint.setXfermode(null); 22905 } else { 22906 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 22907 paint.setShader(shader); 22908 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 22909 } 22910 } 22911 } 22912 22913 public void run() { 22914 long now = AnimationUtils.currentAnimationTimeMillis(); 22915 if (now >= fadeStartTime) { 22916 22917 // the animation fades the scrollbars out by changing 22918 // the opacity (alpha) from fully opaque to fully 22919 // transparent 22920 int nextFrame = (int) now; 22921 int framesCount = 0; 22922 22923 Interpolator interpolator = scrollBarInterpolator; 22924 22925 // Start opaque 22926 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 22927 22928 // End transparent 22929 nextFrame += scrollBarFadeDuration; 22930 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 22931 22932 state = FADING; 22933 22934 // Kick off the fade animation 22935 host.invalidate(true); 22936 } 22937 } 22938 } 22939 22940 /** 22941 * Resuable callback for sending 22942 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 22943 */ 22944 private class SendViewScrolledAccessibilityEvent implements Runnable { 22945 public volatile boolean mIsPending; 22946 22947 public void run() { 22948 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 22949 mIsPending = false; 22950 } 22951 } 22952 22953 /** 22954 * <p> 22955 * This class represents a delegate that can be registered in a {@link View} 22956 * to enhance accessibility support via composition rather via inheritance. 22957 * It is specifically targeted to widget developers that extend basic View 22958 * classes i.e. classes in package android.view, that would like their 22959 * applications to be backwards compatible. 22960 * </p> 22961 * <div class="special reference"> 22962 * <h3>Developer Guides</h3> 22963 * <p>For more information about making applications accessible, read the 22964 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 22965 * developer guide.</p> 22966 * </div> 22967 * <p> 22968 * A scenario in which a developer would like to use an accessibility delegate 22969 * is overriding a method introduced in a later API version then the minimal API 22970 * version supported by the application. For example, the method 22971 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 22972 * in API version 4 when the accessibility APIs were first introduced. If a 22973 * developer would like his application to run on API version 4 devices (assuming 22974 * all other APIs used by the application are version 4 or lower) and take advantage 22975 * of this method, instead of overriding the method which would break the application's 22976 * backwards compatibility, he can override the corresponding method in this 22977 * delegate and register the delegate in the target View if the API version of 22978 * the system is high enough i.e. the API version is same or higher to the API 22979 * version that introduced 22980 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 22981 * </p> 22982 * <p> 22983 * Here is an example implementation: 22984 * </p> 22985 * <code><pre><p> 22986 * if (Build.VERSION.SDK_INT >= 14) { 22987 * // If the API version is equal of higher than the version in 22988 * // which onInitializeAccessibilityNodeInfo was introduced we 22989 * // register a delegate with a customized implementation. 22990 * View view = findViewById(R.id.view_id); 22991 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 22992 * public void onInitializeAccessibilityNodeInfo(View host, 22993 * AccessibilityNodeInfo info) { 22994 * // Let the default implementation populate the info. 22995 * super.onInitializeAccessibilityNodeInfo(host, info); 22996 * // Set some other information. 22997 * info.setEnabled(host.isEnabled()); 22998 * } 22999 * }); 23000 * } 23001 * </code></pre></p> 23002 * <p> 23003 * This delegate contains methods that correspond to the accessibility methods 23004 * in View. If a delegate has been specified the implementation in View hands 23005 * off handling to the corresponding method in this delegate. The default 23006 * implementation the delegate methods behaves exactly as the corresponding 23007 * method in View for the case of no accessibility delegate been set. Hence, 23008 * to customize the behavior of a View method, clients can override only the 23009 * corresponding delegate method without altering the behavior of the rest 23010 * accessibility related methods of the host view. 23011 * </p> 23012 * <p> 23013 * <strong>Note:</strong> On platform versions prior to 23014 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 23015 * views in the {@code android.widget.*} package are called <i>before</i> 23016 * host methods. This prevents certain properties such as class name from 23017 * being modified by overriding 23018 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 23019 * as any changes will be overwritten by the host class. 23020 * <p> 23021 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 23022 * methods are called <i>after</i> host methods, which all properties to be 23023 * modified without being overwritten by the host class. 23024 */ 23025 public static class AccessibilityDelegate { 23026 23027 /** 23028 * Sends an accessibility event of the given type. If accessibility is not 23029 * enabled this method has no effect. 23030 * <p> 23031 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 23032 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 23033 * been set. 23034 * </p> 23035 * 23036 * @param host The View hosting the delegate. 23037 * @param eventType The type of the event to send. 23038 * 23039 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 23040 */ 23041 public void sendAccessibilityEvent(View host, int eventType) { 23042 host.sendAccessibilityEventInternal(eventType); 23043 } 23044 23045 /** 23046 * Performs the specified accessibility action on the view. For 23047 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 23048 * <p> 23049 * The default implementation behaves as 23050 * {@link View#performAccessibilityAction(int, Bundle) 23051 * View#performAccessibilityAction(int, Bundle)} for the case of 23052 * no accessibility delegate been set. 23053 * </p> 23054 * 23055 * @param action The action to perform. 23056 * @return Whether the action was performed. 23057 * 23058 * @see View#performAccessibilityAction(int, Bundle) 23059 * View#performAccessibilityAction(int, Bundle) 23060 */ 23061 public boolean performAccessibilityAction(View host, int action, Bundle args) { 23062 return host.performAccessibilityActionInternal(action, args); 23063 } 23064 23065 /** 23066 * Sends an accessibility event. This method behaves exactly as 23067 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 23068 * empty {@link AccessibilityEvent} and does not perform a check whether 23069 * accessibility is enabled. 23070 * <p> 23071 * The default implementation behaves as 23072 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23073 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 23074 * the case of no accessibility delegate been set. 23075 * </p> 23076 * 23077 * @param host The View hosting the delegate. 23078 * @param event The event to send. 23079 * 23080 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23081 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 23082 */ 23083 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 23084 host.sendAccessibilityEventUncheckedInternal(event); 23085 } 23086 23087 /** 23088 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 23089 * to its children for adding their text content to the event. 23090 * <p> 23091 * The default implementation behaves as 23092 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23093 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 23094 * the case of no accessibility delegate been set. 23095 * </p> 23096 * 23097 * @param host The View hosting the delegate. 23098 * @param event The event. 23099 * @return True if the event population was completed. 23100 * 23101 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23102 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 23103 */ 23104 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23105 return host.dispatchPopulateAccessibilityEventInternal(event); 23106 } 23107 23108 /** 23109 * Gives a chance to the host View to populate the accessibility event with its 23110 * text content. 23111 * <p> 23112 * The default implementation behaves as 23113 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 23114 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 23115 * the case of no accessibility delegate been set. 23116 * </p> 23117 * 23118 * @param host The View hosting the delegate. 23119 * @param event The accessibility event which to populate. 23120 * 23121 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 23122 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 23123 */ 23124 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 23125 host.onPopulateAccessibilityEventInternal(event); 23126 } 23127 23128 /** 23129 * Initializes an {@link AccessibilityEvent} with information about the 23130 * the host View which is the event source. 23131 * <p> 23132 * The default implementation behaves as 23133 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 23134 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 23135 * the case of no accessibility delegate been set. 23136 * </p> 23137 * 23138 * @param host The View hosting the delegate. 23139 * @param event The event to initialize. 23140 * 23141 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 23142 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 23143 */ 23144 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 23145 host.onInitializeAccessibilityEventInternal(event); 23146 } 23147 23148 /** 23149 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 23150 * <p> 23151 * The default implementation behaves as 23152 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23153 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 23154 * the case of no accessibility delegate been set. 23155 * </p> 23156 * 23157 * @param host The View hosting the delegate. 23158 * @param info The instance to initialize. 23159 * 23160 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23161 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 23162 */ 23163 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 23164 host.onInitializeAccessibilityNodeInfoInternal(info); 23165 } 23166 23167 /** 23168 * Called when a child of the host View has requested sending an 23169 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 23170 * to augment the event. 23171 * <p> 23172 * The default implementation behaves as 23173 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23174 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 23175 * the case of no accessibility delegate been set. 23176 * </p> 23177 * 23178 * @param host The View hosting the delegate. 23179 * @param child The child which requests sending the event. 23180 * @param event The event to be sent. 23181 * @return True if the event should be sent 23182 * 23183 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23184 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 23185 */ 23186 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 23187 AccessibilityEvent event) { 23188 return host.onRequestSendAccessibilityEventInternal(child, event); 23189 } 23190 23191 /** 23192 * Gets the provider for managing a virtual view hierarchy rooted at this View 23193 * and reported to {@link android.accessibilityservice.AccessibilityService}s 23194 * that explore the window content. 23195 * <p> 23196 * The default implementation behaves as 23197 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 23198 * the case of no accessibility delegate been set. 23199 * </p> 23200 * 23201 * @return The provider. 23202 * 23203 * @see AccessibilityNodeProvider 23204 */ 23205 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 23206 return null; 23207 } 23208 23209 /** 23210 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 23211 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 23212 * This method is responsible for obtaining an accessibility node info from a 23213 * pool of reusable instances and calling 23214 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 23215 * view to initialize the former. 23216 * <p> 23217 * <strong>Note:</strong> The client is responsible for recycling the obtained 23218 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 23219 * creation. 23220 * </p> 23221 * <p> 23222 * The default implementation behaves as 23223 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 23224 * the case of no accessibility delegate been set. 23225 * </p> 23226 * @return A populated {@link AccessibilityNodeInfo}. 23227 * 23228 * @see AccessibilityNodeInfo 23229 * 23230 * @hide 23231 */ 23232 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 23233 return host.createAccessibilityNodeInfoInternal(); 23234 } 23235 } 23236 23237 private class MatchIdPredicate implements Predicate<View> { 23238 public int mId; 23239 23240 @Override 23241 public boolean apply(View view) { 23242 return (view.mID == mId); 23243 } 23244 } 23245 23246 private class MatchLabelForPredicate implements Predicate<View> { 23247 private int mLabeledId; 23248 23249 @Override 23250 public boolean apply(View view) { 23251 return (view.mLabelForId == mLabeledId); 23252 } 23253 } 23254 23255 private class SendViewStateChangedAccessibilityEvent implements Runnable { 23256 private int mChangeTypes = 0; 23257 private boolean mPosted; 23258 private boolean mPostedWithDelay; 23259 private long mLastEventTimeMillis; 23260 23261 @Override 23262 public void run() { 23263 mPosted = false; 23264 mPostedWithDelay = false; 23265 mLastEventTimeMillis = SystemClock.uptimeMillis(); 23266 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 23267 final AccessibilityEvent event = AccessibilityEvent.obtain(); 23268 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 23269 event.setContentChangeTypes(mChangeTypes); 23270 sendAccessibilityEventUnchecked(event); 23271 } 23272 mChangeTypes = 0; 23273 } 23274 23275 public void runOrPost(int changeType) { 23276 mChangeTypes |= changeType; 23277 23278 // If this is a live region or the child of a live region, collect 23279 // all events from this frame and send them on the next frame. 23280 if (inLiveRegion()) { 23281 // If we're already posted with a delay, remove that. 23282 if (mPostedWithDelay) { 23283 removeCallbacks(this); 23284 mPostedWithDelay = false; 23285 } 23286 // Only post if we're not already posted. 23287 if (!mPosted) { 23288 post(this); 23289 mPosted = true; 23290 } 23291 return; 23292 } 23293 23294 if (mPosted) { 23295 return; 23296 } 23297 23298 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 23299 final long minEventIntevalMillis = 23300 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 23301 if (timeSinceLastMillis >= minEventIntevalMillis) { 23302 removeCallbacks(this); 23303 run(); 23304 } else { 23305 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 23306 mPostedWithDelay = true; 23307 } 23308 } 23309 } 23310 23311 private boolean inLiveRegion() { 23312 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23313 return true; 23314 } 23315 23316 ViewParent parent = getParent(); 23317 while (parent instanceof View) { 23318 if (((View) parent).getAccessibilityLiveRegion() 23319 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 23320 return true; 23321 } 23322 parent = parent.getParent(); 23323 } 23324 23325 return false; 23326 } 23327 23328 /** 23329 * Dump all private flags in readable format, useful for documentation and 23330 * sanity checking. 23331 */ 23332 private static void dumpFlags() { 23333 final HashMap<String, String> found = Maps.newHashMap(); 23334 try { 23335 for (Field field : View.class.getDeclaredFields()) { 23336 final int modifiers = field.getModifiers(); 23337 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 23338 if (field.getType().equals(int.class)) { 23339 final int value = field.getInt(null); 23340 dumpFlag(found, field.getName(), value); 23341 } else if (field.getType().equals(int[].class)) { 23342 final int[] values = (int[]) field.get(null); 23343 for (int i = 0; i < values.length; i++) { 23344 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 23345 } 23346 } 23347 } 23348 } 23349 } catch (IllegalAccessException e) { 23350 throw new RuntimeException(e); 23351 } 23352 23353 final ArrayList<String> keys = Lists.newArrayList(); 23354 keys.addAll(found.keySet()); 23355 Collections.sort(keys); 23356 for (String key : keys) { 23357 Log.d(VIEW_LOG_TAG, found.get(key)); 23358 } 23359 } 23360 23361 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 23362 // Sort flags by prefix, then by bits, always keeping unique keys 23363 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 23364 final int prefix = name.indexOf('_'); 23365 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 23366 final String output = bits + " " + name; 23367 found.put(key, output); 23368 } 23369 23370 /** {@hide} */ 23371 public void encode(@NonNull ViewHierarchyEncoder stream) { 23372 stream.beginObject(this); 23373 encodeProperties(stream); 23374 stream.endObject(); 23375 } 23376 23377 /** {@hide} */ 23378 @CallSuper 23379 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 23380 Object resolveId = ViewDebug.resolveId(getContext(), mID); 23381 if (resolveId instanceof String) { 23382 stream.addProperty("id", (String) resolveId); 23383 } else { 23384 stream.addProperty("id", mID); 23385 } 23386 23387 stream.addProperty("misc:transformation.alpha", 23388 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 23389 stream.addProperty("misc:transitionName", getTransitionName()); 23390 23391 // layout 23392 stream.addProperty("layout:left", mLeft); 23393 stream.addProperty("layout:right", mRight); 23394 stream.addProperty("layout:top", mTop); 23395 stream.addProperty("layout:bottom", mBottom); 23396 stream.addProperty("layout:width", getWidth()); 23397 stream.addProperty("layout:height", getHeight()); 23398 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 23399 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 23400 stream.addProperty("layout:hasTransientState", hasTransientState()); 23401 stream.addProperty("layout:baseline", getBaseline()); 23402 23403 // layout params 23404 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 23405 if (layoutParams != null) { 23406 stream.addPropertyKey("layoutParams"); 23407 layoutParams.encode(stream); 23408 } 23409 23410 // scrolling 23411 stream.addProperty("scrolling:scrollX", mScrollX); 23412 stream.addProperty("scrolling:scrollY", mScrollY); 23413 23414 // padding 23415 stream.addProperty("padding:paddingLeft", mPaddingLeft); 23416 stream.addProperty("padding:paddingRight", mPaddingRight); 23417 stream.addProperty("padding:paddingTop", mPaddingTop); 23418 stream.addProperty("padding:paddingBottom", mPaddingBottom); 23419 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 23420 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 23421 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 23422 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 23423 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 23424 23425 // measurement 23426 stream.addProperty("measurement:minHeight", mMinHeight); 23427 stream.addProperty("measurement:minWidth", mMinWidth); 23428 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 23429 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 23430 23431 // drawing 23432 stream.addProperty("drawing:elevation", getElevation()); 23433 stream.addProperty("drawing:translationX", getTranslationX()); 23434 stream.addProperty("drawing:translationY", getTranslationY()); 23435 stream.addProperty("drawing:translationZ", getTranslationZ()); 23436 stream.addProperty("drawing:rotation", getRotation()); 23437 stream.addProperty("drawing:rotationX", getRotationX()); 23438 stream.addProperty("drawing:rotationY", getRotationY()); 23439 stream.addProperty("drawing:scaleX", getScaleX()); 23440 stream.addProperty("drawing:scaleY", getScaleY()); 23441 stream.addProperty("drawing:pivotX", getPivotX()); 23442 stream.addProperty("drawing:pivotY", getPivotY()); 23443 stream.addProperty("drawing:opaque", isOpaque()); 23444 stream.addProperty("drawing:alpha", getAlpha()); 23445 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 23446 stream.addProperty("drawing:shadow", hasShadow()); 23447 stream.addProperty("drawing:solidColor", getSolidColor()); 23448 stream.addProperty("drawing:layerType", mLayerType); 23449 stream.addProperty("drawing:willNotDraw", willNotDraw()); 23450 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 23451 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 23452 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 23453 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 23454 23455 // focus 23456 stream.addProperty("focus:hasFocus", hasFocus()); 23457 stream.addProperty("focus:isFocused", isFocused()); 23458 stream.addProperty("focus:isFocusable", isFocusable()); 23459 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 23460 23461 stream.addProperty("misc:clickable", isClickable()); 23462 stream.addProperty("misc:pressed", isPressed()); 23463 stream.addProperty("misc:selected", isSelected()); 23464 stream.addProperty("misc:touchMode", isInTouchMode()); 23465 stream.addProperty("misc:hovered", isHovered()); 23466 stream.addProperty("misc:activated", isActivated()); 23467 23468 stream.addProperty("misc:visibility", getVisibility()); 23469 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 23470 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 23471 23472 stream.addProperty("misc:enabled", isEnabled()); 23473 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 23474 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 23475 23476 // theme attributes 23477 Resources.Theme theme = getContext().getTheme(); 23478 if (theme != null) { 23479 stream.addPropertyKey("theme"); 23480 theme.encode(stream); 23481 } 23482 23483 // view attribute information 23484 int n = mAttributes != null ? mAttributes.length : 0; 23485 stream.addProperty("meta:__attrCount__", n/2); 23486 for (int i = 0; i < n; i += 2) { 23487 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 23488 } 23489 23490 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 23491 23492 // text 23493 stream.addProperty("text:textDirection", getTextDirection()); 23494 stream.addProperty("text:textAlignment", getTextAlignment()); 23495 23496 // accessibility 23497 CharSequence contentDescription = getContentDescription(); 23498 stream.addProperty("accessibility:contentDescription", 23499 contentDescription == null ? "" : contentDescription.toString()); 23500 stream.addProperty("accessibility:labelFor", getLabelFor()); 23501 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 23502 } 23503} 23504