View.java revision 3709761c9f96c55ae037cfe1fbf546a5b619a025
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 static java.lang.Math.max; 20 21import android.animation.AnimatorInflater; 22import android.animation.StateListAnimator; 23import android.annotation.CallSuper; 24import android.annotation.ColorInt; 25import android.annotation.DrawableRes; 26import android.annotation.FloatRange; 27import android.annotation.IdRes; 28import android.annotation.IntDef; 29import android.annotation.IntRange; 30import android.annotation.LayoutRes; 31import android.annotation.NonNull; 32import android.annotation.Nullable; 33import android.annotation.Size; 34import android.annotation.TestApi; 35import android.annotation.UiThread; 36import android.content.ClipData; 37import android.content.Context; 38import android.content.ContextWrapper; 39import android.content.Intent; 40import android.content.res.ColorStateList; 41import android.content.res.Configuration; 42import android.content.res.Resources; 43import android.content.res.TypedArray; 44import android.graphics.Bitmap; 45import android.graphics.Canvas; 46import android.graphics.Color; 47import android.graphics.Insets; 48import android.graphics.Interpolator; 49import android.graphics.LinearGradient; 50import android.graphics.Matrix; 51import android.graphics.Outline; 52import android.graphics.Paint; 53import android.graphics.PixelFormat; 54import android.graphics.Point; 55import android.graphics.PorterDuff; 56import android.graphics.PorterDuffXfermode; 57import android.graphics.Rect; 58import android.graphics.RectF; 59import android.graphics.Region; 60import android.graphics.Shader; 61import android.graphics.drawable.ColorDrawable; 62import android.graphics.drawable.Drawable; 63import android.hardware.display.DisplayManagerGlobal; 64import android.net.Uri; 65import android.os.Build; 66import android.os.Bundle; 67import android.os.Handler; 68import android.os.IBinder; 69import android.os.Parcel; 70import android.os.Parcelable; 71import android.os.RemoteException; 72import android.os.SystemClock; 73import android.os.SystemProperties; 74import android.os.Trace; 75import android.text.TextUtils; 76import android.util.AttributeSet; 77import android.util.FloatProperty; 78import android.util.LayoutDirection; 79import android.util.Log; 80import android.util.LongSparseLongArray; 81import android.util.Pools.SynchronizedPool; 82import android.util.Property; 83import android.util.SparseArray; 84import android.util.StateSet; 85import android.util.SuperNotCalledException; 86import android.util.TypedValue; 87import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 88import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 89import android.view.AccessibilityIterators.TextSegmentIterator; 90import android.view.AccessibilityIterators.WordTextSegmentIterator; 91import android.view.ContextMenu.ContextMenuInfo; 92import android.view.accessibility.AccessibilityEvent; 93import android.view.accessibility.AccessibilityEventSource; 94import android.view.accessibility.AccessibilityManager; 95import android.view.accessibility.AccessibilityNodeInfo; 96import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; 97import android.view.accessibility.AccessibilityNodeProvider; 98import android.view.accessibility.AccessibilityWindowInfo; 99import android.view.animation.Animation; 100import android.view.animation.AnimationUtils; 101import android.view.animation.Transformation; 102import android.view.autofill.AutofillManager; 103import android.view.autofill.AutofillValue; 104import android.view.inputmethod.EditorInfo; 105import android.view.inputmethod.InputConnection; 106import android.view.inputmethod.InputMethodManager; 107import android.widget.Checkable; 108import android.widget.FrameLayout; 109import android.widget.ScrollBarDrawable; 110 111import com.android.internal.R; 112import com.android.internal.util.Preconditions; 113import com.android.internal.view.TooltipPopup; 114import com.android.internal.view.menu.MenuBuilder; 115import com.android.internal.widget.ScrollBarUtils; 116 117import com.google.android.collect.Lists; 118import com.google.android.collect.Maps; 119 120import java.lang.annotation.Retention; 121import java.lang.annotation.RetentionPolicy; 122import java.lang.ref.WeakReference; 123import java.lang.reflect.Field; 124import java.lang.reflect.InvocationTargetException; 125import java.lang.reflect.Method; 126import java.lang.reflect.Modifier; 127import java.util.ArrayList; 128import java.util.Arrays; 129import java.util.Collection; 130import java.util.Collections; 131import java.util.HashMap; 132import java.util.List; 133import java.util.Locale; 134import java.util.Map; 135import java.util.concurrent.CopyOnWriteArrayList; 136import java.util.concurrent.atomic.AtomicInteger; 137import java.util.function.Predicate; 138 139/** 140 * <p> 141 * This class represents the basic building block for user interface components. A View 142 * occupies a rectangular area on the screen and is responsible for drawing and 143 * event handling. View is the base class for <em>widgets</em>, which are 144 * used to create interactive UI components (buttons, text fields, etc.). The 145 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 146 * are invisible containers that hold other Views (or other ViewGroups) and define 147 * their layout properties. 148 * </p> 149 * 150 * <div class="special reference"> 151 * <h3>Developer Guides</h3> 152 * <p>For information about using this class to develop your application's user interface, 153 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 154 * </div> 155 * 156 * <a name="Using"></a> 157 * <h3>Using Views</h3> 158 * <p> 159 * All of the views in a window are arranged in a single tree. You can add views 160 * either from code or by specifying a tree of views in one or more XML layout 161 * files. There are many specialized subclasses of views that act as controls or 162 * are capable of displaying text, images, or other content. 163 * </p> 164 * <p> 165 * Once you have created a tree of views, there are typically a few types of 166 * common operations you may wish to perform: 167 * <ul> 168 * <li><strong>Set properties:</strong> for example setting the text of a 169 * {@link android.widget.TextView}. The available properties and the methods 170 * that set them will vary among the different subclasses of views. Note that 171 * properties that are known at build time can be set in the XML layout 172 * files.</li> 173 * <li><strong>Set focus:</strong> The framework will handle moving focus in 174 * response to user input. To force focus to a specific view, call 175 * {@link #requestFocus}.</li> 176 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 177 * that will be notified when something interesting happens to the view. For 178 * example, all views will let you set a listener to be notified when the view 179 * gains or loses focus. You can register such a listener using 180 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 181 * Other view subclasses offer more specialized listeners. For example, a Button 182 * exposes a listener to notify clients when the button is clicked.</li> 183 * <li><strong>Set visibility:</strong> You can hide or show views using 184 * {@link #setVisibility(int)}.</li> 185 * </ul> 186 * </p> 187 * <p><em> 188 * Note: The Android framework is responsible for measuring, laying out and 189 * drawing views. You should not call methods that perform these actions on 190 * views yourself unless you are actually implementing a 191 * {@link android.view.ViewGroup}. 192 * </em></p> 193 * 194 * <a name="Lifecycle"></a> 195 * <h3>Implementing a Custom View</h3> 196 * 197 * <p> 198 * To implement a custom view, you will usually begin by providing overrides for 199 * some of the standard methods that the framework calls on all views. You do 200 * not need to override all of these methods. In fact, you can start by just 201 * overriding {@link #onDraw(android.graphics.Canvas)}. 202 * <table border="2" width="85%" align="center" cellpadding="5"> 203 * <thead> 204 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 205 * </thead> 206 * 207 * <tbody> 208 * <tr> 209 * <td rowspan="2">Creation</td> 210 * <td>Constructors</td> 211 * <td>There is a form of the constructor that are called when the view 212 * is created from code and a form that is called when the view is 213 * inflated from a layout file. The second form should parse and apply 214 * any attributes defined in the layout file. 215 * </td> 216 * </tr> 217 * <tr> 218 * <td><code>{@link #onFinishInflate()}</code></td> 219 * <td>Called after a view and all of its children has been inflated 220 * from XML.</td> 221 * </tr> 222 * 223 * <tr> 224 * <td rowspan="3">Layout</td> 225 * <td><code>{@link #onMeasure(int, int)}</code></td> 226 * <td>Called to determine the size requirements for this view and all 227 * of its children. 228 * </td> 229 * </tr> 230 * <tr> 231 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 232 * <td>Called when this view should assign a size and position to all 233 * of its children. 234 * </td> 235 * </tr> 236 * <tr> 237 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 238 * <td>Called when the size of this view has changed. 239 * </td> 240 * </tr> 241 * 242 * <tr> 243 * <td>Drawing</td> 244 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 245 * <td>Called when the view should render its content. 246 * </td> 247 * </tr> 248 * 249 * <tr> 250 * <td rowspan="4">Event processing</td> 251 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 252 * <td>Called when a new hardware key event occurs. 253 * </td> 254 * </tr> 255 * <tr> 256 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 257 * <td>Called when a hardware key up event occurs. 258 * </td> 259 * </tr> 260 * <tr> 261 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 262 * <td>Called when a trackball motion event occurs. 263 * </td> 264 * </tr> 265 * <tr> 266 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 267 * <td>Called when a touch screen motion event occurs. 268 * </td> 269 * </tr> 270 * 271 * <tr> 272 * <td rowspan="2">Focus</td> 273 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 274 * <td>Called when the view gains or loses focus. 275 * </td> 276 * </tr> 277 * 278 * <tr> 279 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 280 * <td>Called when the window containing the view gains or loses focus. 281 * </td> 282 * </tr> 283 * 284 * <tr> 285 * <td rowspan="3">Attaching</td> 286 * <td><code>{@link #onAttachedToWindow()}</code></td> 287 * <td>Called when the view is attached to a window. 288 * </td> 289 * </tr> 290 * 291 * <tr> 292 * <td><code>{@link #onDetachedFromWindow}</code></td> 293 * <td>Called when the view is detached from its window. 294 * </td> 295 * </tr> 296 * 297 * <tr> 298 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 299 * <td>Called when the visibility of the window containing the view 300 * has changed. 301 * </td> 302 * </tr> 303 * </tbody> 304 * 305 * </table> 306 * </p> 307 * 308 * <a name="IDs"></a> 309 * <h3>IDs</h3> 310 * Views may have an integer id associated with them. These ids are typically 311 * assigned in the layout XML files, and are used to find specific views within 312 * the view tree. A common pattern is to: 313 * <ul> 314 * <li>Define a Button in the layout file and assign it a unique ID. 315 * <pre> 316 * <Button 317 * android:id="@+id/my_button" 318 * android:layout_width="wrap_content" 319 * android:layout_height="wrap_content" 320 * android:text="@string/my_button_text"/> 321 * </pre></li> 322 * <li>From the onCreate method of an Activity, find the Button 323 * <pre class="prettyprint"> 324 * Button myButton = (Button) findViewById(R.id.my_button); 325 * </pre></li> 326 * </ul> 327 * <p> 328 * View IDs need not be unique throughout the tree, but it is good practice to 329 * ensure that they are at least unique within the part of the tree you are 330 * searching. 331 * </p> 332 * 333 * <a name="Position"></a> 334 * <h3>Position</h3> 335 * <p> 336 * The geometry of a view is that of a rectangle. A view has a location, 337 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 338 * two dimensions, expressed as a width and a height. The unit for location 339 * and dimensions is the pixel. 340 * </p> 341 * 342 * <p> 343 * It is possible to retrieve the location of a view by invoking the methods 344 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 345 * coordinate of the rectangle representing the view. The latter returns the 346 * top, or Y, coordinate of the rectangle representing the view. These methods 347 * both return the location of the view relative to its parent. For instance, 348 * when getLeft() returns 20, that means the view is located 20 pixels to the 349 * right of the left edge of its direct parent. 350 * </p> 351 * 352 * <p> 353 * In addition, several convenience methods are offered to avoid unnecessary 354 * computations, namely {@link #getRight()} and {@link #getBottom()}. 355 * These methods return the coordinates of the right and bottom edges of the 356 * rectangle representing the view. For instance, calling {@link #getRight()} 357 * is similar to the following computation: <code>getLeft() + getWidth()</code> 358 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 359 * </p> 360 * 361 * <a name="SizePaddingMargins"></a> 362 * <h3>Size, padding and margins</h3> 363 * <p> 364 * The size of a view is expressed with a width and a height. A view actually 365 * possess two pairs of width and height values. 366 * </p> 367 * 368 * <p> 369 * The first pair is known as <em>measured width</em> and 370 * <em>measured height</em>. These dimensions define how big a view wants to be 371 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 372 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 373 * and {@link #getMeasuredHeight()}. 374 * </p> 375 * 376 * <p> 377 * The second pair is simply known as <em>width</em> and <em>height</em>, or 378 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 379 * dimensions define the actual size of the view on screen, at drawing time and 380 * after layout. These values may, but do not have to, be different from the 381 * measured width and height. The width and height can be obtained by calling 382 * {@link #getWidth()} and {@link #getHeight()}. 383 * </p> 384 * 385 * <p> 386 * To measure its dimensions, a view takes into account its padding. The padding 387 * is expressed in pixels for the left, top, right and bottom parts of the view. 388 * Padding can be used to offset the content of the view by a specific amount of 389 * pixels. For instance, a left padding of 2 will push the view's content by 390 * 2 pixels to the right of the left edge. Padding can be set using the 391 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 392 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 393 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 394 * {@link #getPaddingEnd()}. 395 * </p> 396 * 397 * <p> 398 * Even though a view can define a padding, it does not provide any support for 399 * margins. However, view groups provide such a support. Refer to 400 * {@link android.view.ViewGroup} and 401 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 402 * </p> 403 * 404 * <a name="Layout"></a> 405 * <h3>Layout</h3> 406 * <p> 407 * Layout is a two pass process: a measure pass and a layout pass. The measuring 408 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 409 * of the view tree. Each view pushes dimension specifications down the tree 410 * during the recursion. At the end of the measure pass, every view has stored 411 * its measurements. The second pass happens in 412 * {@link #layout(int,int,int,int)} and is also top-down. During 413 * this pass each parent is responsible for positioning all of its children 414 * using the sizes computed in the measure pass. 415 * </p> 416 * 417 * <p> 418 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 419 * {@link #getMeasuredHeight()} values must be set, along with those for all of 420 * that view's descendants. A view's measured width and measured height values 421 * must respect the constraints imposed by the view's parents. This guarantees 422 * that at the end of the measure pass, all parents accept all of their 423 * children's measurements. A parent view may call measure() more than once on 424 * its children. For example, the parent may measure each child once with 425 * unspecified dimensions to find out how big they want to be, then call 426 * measure() on them again with actual numbers if the sum of all the children's 427 * unconstrained sizes is too big or too small. 428 * </p> 429 * 430 * <p> 431 * The measure pass uses two classes to communicate dimensions. The 432 * {@link MeasureSpec} class is used by views to tell their parents how they 433 * want to be measured and positioned. The base LayoutParams class just 434 * describes how big the view wants to be for both width and height. For each 435 * dimension, it can specify one of: 436 * <ul> 437 * <li> an exact number 438 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 439 * (minus padding) 440 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 441 * enclose its content (plus padding). 442 * </ul> 443 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 444 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 445 * an X and Y value. 446 * </p> 447 * 448 * <p> 449 * MeasureSpecs are used to push requirements down the tree from parent to 450 * child. A MeasureSpec can be in one of three modes: 451 * <ul> 452 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 453 * of a child view. For example, a LinearLayout may call measure() on its child 454 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 455 * tall the child view wants to be given a width of 240 pixels. 456 * <li>EXACTLY: This is used by the parent to impose an exact size on the 457 * child. The child must use this size, and guarantee that all of its 458 * descendants will fit within this size. 459 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 460 * child. The child must guarantee that it and all of its descendants will fit 461 * within this size. 462 * </ul> 463 * </p> 464 * 465 * <p> 466 * To initiate a layout, call {@link #requestLayout}. This method is typically 467 * called by a view on itself when it believes that is can no longer fit within 468 * its current bounds. 469 * </p> 470 * 471 * <a name="Drawing"></a> 472 * <h3>Drawing</h3> 473 * <p> 474 * Drawing is handled by walking the tree and recording the drawing commands of 475 * any View that needs to update. After this, the drawing commands of the 476 * entire tree are issued to screen, clipped to the newly damaged area. 477 * </p> 478 * 479 * <p> 480 * The tree is largely recorded and drawn in order, with parents drawn before 481 * (i.e., behind) their children, with siblings drawn in the order they appear 482 * in the tree. If you set a background drawable for a View, then the View will 483 * draw it before calling back to its <code>onDraw()</code> method. The child 484 * drawing order can be overridden with 485 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 486 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 487 * </p> 488 * 489 * <p> 490 * To force a view to draw, call {@link #invalidate()}. 491 * </p> 492 * 493 * <a name="EventHandlingThreading"></a> 494 * <h3>Event Handling and Threading</h3> 495 * <p> 496 * The basic cycle of a view is as follows: 497 * <ol> 498 * <li>An event comes in and is dispatched to the appropriate view. The view 499 * handles the event and notifies any listeners.</li> 500 * <li>If in the course of processing the event, the view's bounds may need 501 * to be changed, the view will call {@link #requestLayout()}.</li> 502 * <li>Similarly, if in the course of processing the event the view's appearance 503 * may need to be changed, the view will call {@link #invalidate()}.</li> 504 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 505 * the framework will take care of measuring, laying out, and drawing the tree 506 * as appropriate.</li> 507 * </ol> 508 * </p> 509 * 510 * <p><em>Note: The entire view tree is single threaded. You must always be on 511 * the UI thread when calling any method on any view.</em> 512 * If you are doing work on other threads and want to update the state of a view 513 * from that thread, you should use a {@link Handler}. 514 * </p> 515 * 516 * <a name="FocusHandling"></a> 517 * <h3>Focus Handling</h3> 518 * <p> 519 * The framework will handle routine focus movement in response to user input. 520 * This includes changing the focus as views are removed or hidden, or as new 521 * views become available. Views indicate their willingness to take focus 522 * through the {@link #isFocusable} method. To change whether a view can take 523 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 524 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 525 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 526 * </p> 527 * <p> 528 * Focus movement is based on an algorithm which finds the nearest neighbor in a 529 * given direction. In rare cases, the default algorithm may not match the 530 * intended behavior of the developer. In these situations, you can provide 531 * explicit overrides by using these XML attributes in the layout file: 532 * <pre> 533 * nextFocusDown 534 * nextFocusLeft 535 * nextFocusRight 536 * nextFocusUp 537 * </pre> 538 * </p> 539 * 540 * 541 * <p> 542 * To get a particular view to take focus, call {@link #requestFocus()}. 543 * </p> 544 * 545 * <a name="TouchMode"></a> 546 * <h3>Touch Mode</h3> 547 * <p> 548 * When a user is navigating a user interface via directional keys such as a D-pad, it is 549 * necessary to give focus to actionable items such as buttons so the user can see 550 * what will take input. If the device has touch capabilities, however, and the user 551 * begins interacting with the interface by touching it, it is no longer necessary to 552 * always highlight, or give focus to, a particular view. This motivates a mode 553 * for interaction named 'touch mode'. 554 * </p> 555 * <p> 556 * For a touch capable device, once the user touches the screen, the device 557 * will enter touch mode. From this point onward, only views for which 558 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 559 * Other views that are touchable, like buttons, will not take focus when touched; they will 560 * only fire the on click listeners. 561 * </p> 562 * <p> 563 * Any time a user hits a directional key, such as a D-pad direction, the view device will 564 * exit touch mode, and find a view to take focus, so that the user may resume interacting 565 * with the user interface without touching the screen again. 566 * </p> 567 * <p> 568 * The touch mode state is maintained across {@link android.app.Activity}s. Call 569 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 570 * </p> 571 * 572 * <a name="Scrolling"></a> 573 * <h3>Scrolling</h3> 574 * <p> 575 * The framework provides basic support for views that wish to internally 576 * scroll their content. This includes keeping track of the X and Y scroll 577 * offset as well as mechanisms for drawing scrollbars. See 578 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 579 * {@link #awakenScrollBars()} for more details. 580 * </p> 581 * 582 * <a name="Tags"></a> 583 * <h3>Tags</h3> 584 * <p> 585 * Unlike IDs, tags are not used to identify views. Tags are essentially an 586 * extra piece of information that can be associated with a view. They are most 587 * often used as a convenience to store data related to views in the views 588 * themselves rather than by putting them in a separate structure. 589 * </p> 590 * <p> 591 * Tags may be specified with character sequence values in layout XML as either 592 * a single tag using the {@link android.R.styleable#View_tag android:tag} 593 * attribute or multiple tags using the {@code <tag>} child element: 594 * <pre> 595 * <View ... 596 * android:tag="@string/mytag_value" /> 597 * <View ...> 598 * <tag android:id="@+id/mytag" 599 * android:value="@string/mytag_value" /> 600 * </View> 601 * </pre> 602 * </p> 603 * <p> 604 * Tags may also be specified with arbitrary objects from code using 605 * {@link #setTag(Object)} or {@link #setTag(int, Object)}. 606 * </p> 607 * 608 * <a name="Themes"></a> 609 * <h3>Themes</h3> 610 * <p> 611 * By default, Views are created using the theme of the Context object supplied 612 * to their constructor; however, a different theme may be specified by using 613 * the {@link android.R.styleable#View_theme android:theme} attribute in layout 614 * XML or by passing a {@link ContextThemeWrapper} to the constructor from 615 * code. 616 * </p> 617 * <p> 618 * When the {@link android.R.styleable#View_theme android:theme} attribute is 619 * used in XML, the specified theme is applied on top of the inflation 620 * context's theme (see {@link LayoutInflater}) and used for the view itself as 621 * well as any child elements. 622 * </p> 623 * <p> 624 * In the following example, both views will be created using the Material dark 625 * color scheme; however, because an overlay theme is used which only defines a 626 * subset of attributes, the value of 627 * {@link android.R.styleable#Theme_colorAccent android:colorAccent} defined on 628 * the inflation context's theme (e.g. the Activity theme) will be preserved. 629 * <pre> 630 * <LinearLayout 631 * ... 632 * android:theme="@android:theme/ThemeOverlay.Material.Dark"> 633 * <View ...> 634 * </LinearLayout> 635 * </pre> 636 * </p> 637 * 638 * <a name="Properties"></a> 639 * <h3>Properties</h3> 640 * <p> 641 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 642 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 643 * available both in the {@link Property} form as well as in similarly-named setter/getter 644 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 645 * be used to set persistent state associated with these rendering-related properties on the view. 646 * The properties and methods can also be used in conjunction with 647 * {@link android.animation.Animator Animator}-based animations, described more in the 648 * <a href="#Animation">Animation</a> section. 649 * </p> 650 * 651 * <a name="Animation"></a> 652 * <h3>Animation</h3> 653 * <p> 654 * Starting with Android 3.0, the preferred way of animating views is to use the 655 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 656 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 657 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 658 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 659 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 660 * makes animating these View properties particularly easy and efficient. 661 * </p> 662 * <p> 663 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 664 * You can attach an {@link Animation} object to a view using 665 * {@link #setAnimation(Animation)} or 666 * {@link #startAnimation(Animation)}. The animation can alter the scale, 667 * rotation, translation and alpha of a view over time. If the animation is 668 * attached to a view that has children, the animation will affect the entire 669 * subtree rooted by that node. When an animation is started, the framework will 670 * take care of redrawing the appropriate views until the animation completes. 671 * </p> 672 * 673 * <a name="Security"></a> 674 * <h3>Security</h3> 675 * <p> 676 * Sometimes it is essential that an application be able to verify that an action 677 * is being performed with the full knowledge and consent of the user, such as 678 * granting a permission request, making a purchase or clicking on an advertisement. 679 * Unfortunately, a malicious application could try to spoof the user into 680 * performing these actions, unaware, by concealing the intended purpose of the view. 681 * As a remedy, the framework offers a touch filtering mechanism that can be used to 682 * improve the security of views that provide access to sensitive functionality. 683 * </p><p> 684 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 685 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 686 * will discard touches that are received whenever the view's window is obscured by 687 * another visible window. As a result, the view will not receive touches whenever a 688 * toast, dialog or other window appears above the view's window. 689 * </p><p> 690 * For more fine-grained control over security, consider overriding the 691 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 692 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 693 * </p> 694 * 695 * @attr ref android.R.styleable#View_alpha 696 * @attr ref android.R.styleable#View_background 697 * @attr ref android.R.styleable#View_clickable 698 * @attr ref android.R.styleable#View_contentDescription 699 * @attr ref android.R.styleable#View_drawingCacheQuality 700 * @attr ref android.R.styleable#View_duplicateParentState 701 * @attr ref android.R.styleable#View_id 702 * @attr ref android.R.styleable#View_requiresFadingEdge 703 * @attr ref android.R.styleable#View_fadeScrollbars 704 * @attr ref android.R.styleable#View_fadingEdgeLength 705 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 706 * @attr ref android.R.styleable#View_fitsSystemWindows 707 * @attr ref android.R.styleable#View_isScrollContainer 708 * @attr ref android.R.styleable#View_focusable 709 * @attr ref android.R.styleable#View_focusableInTouchMode 710 * @attr ref android.R.styleable#View_focusedByDefault 711 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 712 * @attr ref android.R.styleable#View_keepScreenOn 713 * @attr ref android.R.styleable#View_keyboardNavigationCluster 714 * @attr ref android.R.styleable#View_layerType 715 * @attr ref android.R.styleable#View_layoutDirection 716 * @attr ref android.R.styleable#View_longClickable 717 * @attr ref android.R.styleable#View_minHeight 718 * @attr ref android.R.styleable#View_minWidth 719 * @attr ref android.R.styleable#View_nextClusterForward 720 * @attr ref android.R.styleable#View_nextFocusDown 721 * @attr ref android.R.styleable#View_nextFocusLeft 722 * @attr ref android.R.styleable#View_nextFocusRight 723 * @attr ref android.R.styleable#View_nextFocusUp 724 * @attr ref android.R.styleable#View_onClick 725 * @attr ref android.R.styleable#View_padding 726 * @attr ref android.R.styleable#View_paddingBottom 727 * @attr ref android.R.styleable#View_paddingLeft 728 * @attr ref android.R.styleable#View_paddingRight 729 * @attr ref android.R.styleable#View_paddingTop 730 * @attr ref android.R.styleable#View_paddingStart 731 * @attr ref android.R.styleable#View_paddingEnd 732 * @attr ref android.R.styleable#View_saveEnabled 733 * @attr ref android.R.styleable#View_rotation 734 * @attr ref android.R.styleable#View_rotationX 735 * @attr ref android.R.styleable#View_rotationY 736 * @attr ref android.R.styleable#View_scaleX 737 * @attr ref android.R.styleable#View_scaleY 738 * @attr ref android.R.styleable#View_scrollX 739 * @attr ref android.R.styleable#View_scrollY 740 * @attr ref android.R.styleable#View_scrollbarSize 741 * @attr ref android.R.styleable#View_scrollbarStyle 742 * @attr ref android.R.styleable#View_scrollbars 743 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 744 * @attr ref android.R.styleable#View_scrollbarFadeDuration 745 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 746 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 747 * @attr ref android.R.styleable#View_scrollbarThumbVertical 748 * @attr ref android.R.styleable#View_scrollbarTrackVertical 749 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 750 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 751 * @attr ref android.R.styleable#View_stateListAnimator 752 * @attr ref android.R.styleable#View_transitionName 753 * @attr ref android.R.styleable#View_soundEffectsEnabled 754 * @attr ref android.R.styleable#View_tag 755 * @attr ref android.R.styleable#View_textAlignment 756 * @attr ref android.R.styleable#View_textDirection 757 * @attr ref android.R.styleable#View_transformPivotX 758 * @attr ref android.R.styleable#View_transformPivotY 759 * @attr ref android.R.styleable#View_translationX 760 * @attr ref android.R.styleable#View_translationY 761 * @attr ref android.R.styleable#View_translationZ 762 * @attr ref android.R.styleable#View_visibility 763 * @attr ref android.R.styleable#View_theme 764 * 765 * @see android.view.ViewGroup 766 */ 767@UiThread 768public class View implements Drawable.Callback, KeyEvent.Callback, 769 AccessibilityEventSource { 770 private static final boolean DBG = false; 771 772 /** @hide */ 773 public static boolean DEBUG_DRAW = false; 774 775 /** 776 * The logging tag used by this class with android.util.Log. 777 */ 778 protected static final String VIEW_LOG_TAG = "View"; 779 780 /** 781 * When set to true, apps will draw debugging information about their layouts. 782 * 783 * @hide 784 */ 785 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 786 787 /** 788 * When set to true, this view will save its attribute data. 789 * 790 * @hide 791 */ 792 public static boolean mDebugViewAttributes = false; 793 794 /** 795 * Used to mark a View that has no ID. 796 */ 797 public static final int NO_ID = -1; 798 799 /** 800 * Signals that compatibility booleans have been initialized according to 801 * target SDK versions. 802 */ 803 private static boolean sCompatibilityDone = false; 804 805 /** 806 * Use the old (broken) way of building MeasureSpecs. 807 */ 808 private static boolean sUseBrokenMakeMeasureSpec = false; 809 810 /** 811 * Always return a size of 0 for MeasureSpec values with a mode of UNSPECIFIED 812 */ 813 static boolean sUseZeroUnspecifiedMeasureSpec = false; 814 815 /** 816 * Ignore any optimizations using the measure cache. 817 */ 818 private static boolean sIgnoreMeasureCache = false; 819 820 /** 821 * Ignore an optimization that skips unnecessary EXACTLY layout passes. 822 */ 823 private static boolean sAlwaysRemeasureExactly = false; 824 825 /** 826 * Relax constraints around whether setLayoutParams() must be called after 827 * modifying the layout params. 828 */ 829 private static boolean sLayoutParamsAlwaysChanged = false; 830 831 /** 832 * Allow setForeground/setBackground to be called (and ignored) on a textureview, 833 * without throwing 834 */ 835 static boolean sTextureViewIgnoresDrawableSetters = false; 836 837 /** 838 * Prior to N, some ViewGroups would not convert LayoutParams properly even though both extend 839 * MarginLayoutParams. For instance, converting LinearLayout.LayoutParams to 840 * RelativeLayout.LayoutParams would lose margin information. This is fixed on N but target API 841 * check is implemented for backwards compatibility. 842 * 843 * {@hide} 844 */ 845 protected static boolean sPreserveMarginParamsInLayoutParamConversion; 846 847 /** 848 * Prior to N, when drag enters into child of a view that has already received an 849 * ACTION_DRAG_ENTERED event, the parent doesn't get a ACTION_DRAG_EXITED event. 850 * ACTION_DRAG_LOCATION and ACTION_DROP were delivered to the parent of a view that returned 851 * false from its event handler for these events. 852 * Starting from N, the parent will get ACTION_DRAG_EXITED event before the child gets its 853 * ACTION_DRAG_ENTERED. ACTION_DRAG_LOCATION and ACTION_DROP are never propagated to the parent. 854 * sCascadedDragDrop is true for pre-N apps for backwards compatibility implementation. 855 */ 856 static boolean sCascadedDragDrop; 857 858 /** 859 * Prior to O, auto-focusable didn't exist and widgets such as ListView use hasFocusable 860 * to determine things like whether or not to permit item click events. We can't break 861 * apps that do this just because more things (clickable things) are now auto-focusable 862 * and they would get different results, so give old behavior to old apps. 863 */ 864 static boolean sHasFocusableExcludeAutoFocusable; 865 866 /** 867 * Prior to O, auto-focusable didn't exist and views marked as clickable weren't implicitly 868 * made focusable by default. As a result, apps could (incorrectly) change the clickable 869 * setting of views off the UI thread. Now that clickable can effect the focusable state, 870 * changing the clickable attribute off the UI thread will cause an exception (since changing 871 * the focusable state checks). In order to prevent apps from crashing, we will handle this 872 * specific case and just not notify parents on new focusables resulting from marking views 873 * clickable from outside the UI thread. 874 */ 875 private static boolean sAutoFocusableOffUIThreadWontNotifyParents; 876 877 /** @hide */ 878 @IntDef({NOT_FOCUSABLE, FOCUSABLE, FOCUSABLE_AUTO}) 879 @Retention(RetentionPolicy.SOURCE) 880 public @interface Focusable {} 881 882 /** 883 * This view does not want keystrokes. 884 * <p> 885 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 886 * android:focusable}. 887 */ 888 public static final int NOT_FOCUSABLE = 0x00000000; 889 890 /** 891 * This view wants keystrokes. 892 * <p> 893 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 894 * android:focusable}. 895 */ 896 public static final int FOCUSABLE = 0x00000001; 897 898 /** 899 * This view determines focusability automatically. This is the default. 900 * <p> 901 * Use with {@link #setFocusable(int)} and <a href="#attr_android:focusable">{@code 902 * android:focusable}. 903 */ 904 public static final int FOCUSABLE_AUTO = 0x00000010; 905 906 /** 907 * Mask for use with setFlags indicating bits used for focus. 908 */ 909 private static final int FOCUSABLE_MASK = 0x00000011; 910 911 /** 912 * This view will adjust its padding to fit sytem windows (e.g. status bar) 913 */ 914 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 915 916 /** @hide */ 917 @IntDef({VISIBLE, INVISIBLE, GONE}) 918 @Retention(RetentionPolicy.SOURCE) 919 public @interface Visibility {} 920 921 /** 922 * This view is visible. 923 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 924 * android:visibility}. 925 */ 926 public static final int VISIBLE = 0x00000000; 927 928 /** 929 * This view is invisible, but it still takes up space for layout purposes. 930 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 931 * android:visibility}. 932 */ 933 public static final int INVISIBLE = 0x00000004; 934 935 /** 936 * This view is invisible, and it doesn't take any space for layout 937 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 938 * android:visibility}. 939 */ 940 public static final int GONE = 0x00000008; 941 942 /** 943 * Mask for use with setFlags indicating bits used for visibility. 944 * {@hide} 945 */ 946 static final int VISIBILITY_MASK = 0x0000000C; 947 948 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 949 950 /** @hide */ 951 @IntDef({ 952 AUTOFILL_MODE_INHERIT, 953 AUTOFILL_MODE_AUTO, 954 AUTOFILL_MODE_MANUAL 955 }) 956 @Retention(RetentionPolicy.SOURCE) 957 public @interface AutofillMode {} 958 959 /** 960 * This view inherits the autofill state from it's parent. If there is no parent it is 961 * {@link #AUTOFILL_MODE_AUTO}. 962 * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode"> 963 * {@code android:autofillMode}. 964 */ 965 public static final int AUTOFILL_MODE_INHERIT = 0; 966 967 /** 968 * Allows this view to automatically trigger an autofill request when it get focus. 969 * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode"> 970 * {@code android:autofillMode}. 971 */ 972 public static final int AUTOFILL_MODE_AUTO = 1; 973 974 /** 975 * Do not trigger an autofill request if this view is focused. The user can still force 976 * an autofill request. 977 * <p>This does not prevent this field from being autofilled if an autofill operation is 978 * triggered from a different view.</p> 979 * 980 * Use with {@link #setAutofillMode(int)} and <a href="#attr_android:autofillMode">{@code 981 * android:autofillMode}. 982 */ 983 public static final int AUTOFILL_MODE_MANUAL = 2; 984 985 /** 986 * This view contains an email address. 987 * 988 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_EMAIL_ADDRESS}" 989 * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 990 */ 991 public static final String AUTOFILL_HINT_EMAIL_ADDRESS = "emailAddress"; 992 993 /** 994 * The view contains a real name. 995 * 996 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_NAME}" to 997 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 998 */ 999 public static final String AUTOFILL_HINT_NAME = "name"; 1000 1001 /** 1002 * The view contains a user name. 1003 * 1004 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_USERNAME}" to 1005 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1006 */ 1007 public static final String AUTOFILL_HINT_USERNAME = "username"; 1008 1009 /** 1010 * The view contains a password. 1011 * 1012 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PASSWORD}" to 1013 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1014 */ 1015 public static final String AUTOFILL_HINT_PASSWORD = "password"; 1016 1017 /** 1018 * The view contains a phone number. 1019 * 1020 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_PHONE}" to 1021 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1022 */ 1023 public static final String AUTOFILL_HINT_PHONE = "phone"; 1024 1025 /** 1026 * The view contains a postal address. 1027 * 1028 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_ADDRESS}" 1029 * to <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1030 */ 1031 public static final String AUTOFILL_HINT_POSTAL_ADDRESS = "postalAddress"; 1032 1033 /** 1034 * The view contains a postal code. 1035 * 1036 * Use with {@link #setAutofillHints(String[])}, or set "{@value #AUTOFILL_HINT_POSTAL_CODE}" to 1037 * <a href="#attr_android:autofillHint"> {@code android:autofillHint}. 1038 */ 1039 public static final String AUTOFILL_HINT_POSTAL_CODE = "postalCode"; 1040 1041 /** 1042 * The view contains a credit card number. 1043 * 1044 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1045 * #AUTOFILL_HINT_CREDIT_CARD_NUMBER}" to <a href="#attr_android:autofillHint"> {@code 1046 * android:autofillHint}. 1047 */ 1048 public static final String AUTOFILL_HINT_CREDIT_CARD_NUMBER = "creditCardNumber"; 1049 1050 /** 1051 * The view contains a credit card security code. 1052 * 1053 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1054 * #AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE}" to <a href="#attr_android:autofillHint"> {@code 1055 * android:autofillHint}. 1056 */ 1057 public static final String AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE = "creditCardSecurityCode"; 1058 1059 /** 1060 * The view contains a credit card expiration date. 1061 * 1062 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1063 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE}" to <a href="#attr_android:autofillHint"> {@code 1064 * android:autofillHint}. 1065 */ 1066 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE = 1067 "creditCardExpirationDate"; 1068 1069 /** 1070 * The view contains the month a credit card expires. 1071 * 1072 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1073 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH}" to <a href="#attr_android:autofillHint"> {@code 1074 * android:autofillHint}. 1075 */ 1076 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH = 1077 "creditCardExpirationMonth"; 1078 1079 /** 1080 * The view contains the year a credit card expires. 1081 * 1082 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1083 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR}" to <a href="#attr_android:autofillHint"> {@code 1084 * android:autofillHint}. 1085 */ 1086 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR = 1087 "creditCardExpirationYear"; 1088 1089 /** 1090 * The view contains the day a credit card expires. 1091 * 1092 * Use with {@link #setAutofillHints(String[])}, or set "{@value 1093 * #AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY}" to <a href="#attr_android:autofillHint"> {@code 1094 * android:autofillHint}. 1095 */ 1096 public static final String AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY = "creditCardExpirationDay"; 1097 1098 /** 1099 * Hintd for the autofill services that describes the content of the view. 1100 */ 1101 private @Nullable String[] mAutofillHints; 1102 1103 /** @hide */ 1104 @IntDef({ 1105 AUTOFILL_TYPE_NONE, 1106 AUTOFILL_TYPE_TEXT, 1107 AUTOFILL_TYPE_TOGGLE, 1108 AUTOFILL_TYPE_LIST, 1109 AUTOFILL_TYPE_DATE 1110 }) 1111 @Retention(RetentionPolicy.SOURCE) 1112 public @interface AutofillType {} 1113 1114 /** 1115 * Autofill type for views that cannot be autofilled. 1116 */ 1117 public static final int AUTOFILL_TYPE_NONE = 0; 1118 1119 /** 1120 * Autofill type for a text field, which is filled by a {@link CharSequence}. 1121 * 1122 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1123 * {@link AutofillValue#forText(CharSequence)}, and the value passed to autofill a 1124 * {@link View} can be fetched through {@link AutofillValue#getTextValue()}. 1125 */ 1126 public static final int AUTOFILL_TYPE_TEXT = 1; 1127 1128 /** 1129 * Autofill type for a togglable field, which is filled by a {@code boolean}. 1130 * 1131 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1132 * {@link AutofillValue#forToggle(boolean)}, and the value passed to autofill a 1133 * {@link View} can be fetched through {@link AutofillValue#getToggleValue()}. 1134 */ 1135 public static final int AUTOFILL_TYPE_TOGGLE = 2; 1136 1137 /** 1138 * Autofill type for a selection list field, which is filled by an {@code int} 1139 * representing the element index inside the list (starting at {@code 0}). 1140 * 1141 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1142 * {@link AutofillValue#forList(int)}, and the value passed to autofill a 1143 * {@link View} can be fetched through {@link AutofillValue#getListValue()}. 1144 * 1145 * <p>The available options in the selection list are typically provided by 1146 * {@link android.app.assist.AssistStructure.ViewNode#getAutofillOptions()}. 1147 */ 1148 public static final int AUTOFILL_TYPE_LIST = 3; 1149 1150 1151 /** 1152 * Autofill type for a field that contains a date, which is represented by a long representing 1153 * the number of milliseconds since the standard base time known as "the epoch", namely 1154 * January 1, 1970, 00:00:00 GMT (see {@link java.util.Date#getTime()}. 1155 * 1156 * <p>{@link AutofillValue} instances for autofilling a {@link View} can be obtained through 1157 * {@link AutofillValue#forDate(long)}, and the values passed to 1158 * autofill a {@link View} can be fetched through {@link AutofillValue#getDateValue()}. 1159 */ 1160 public static final int AUTOFILL_TYPE_DATE = 4; 1161 1162 /** @hide */ 1163 @IntDef({ 1164 IMPORTANT_FOR_AUTOFILL_AUTO, 1165 IMPORTANT_FOR_AUTOFILL_YES, 1166 IMPORTANT_FOR_AUTOFILL_NO 1167 }) 1168 @Retention(RetentionPolicy.SOURCE) 1169 public @interface AutofillImportance {} 1170 1171 /** 1172 * Automatically determine whether a view is important for auto-fill. 1173 */ 1174 public static final int IMPORTANT_FOR_AUTOFILL_AUTO = 0x0; 1175 1176 /** 1177 * The view is important for important for auto-fill. 1178 */ 1179 public static final int IMPORTANT_FOR_AUTOFILL_YES = 0x1; 1180 1181 /** 1182 * The view is not important for auto-fill. 1183 */ 1184 public static final int IMPORTANT_FOR_AUTOFILL_NO = 0x2; 1185 1186 /** 1187 * This view is enabled. Interpretation varies by subclass. 1188 * Use with ENABLED_MASK when calling setFlags. 1189 * {@hide} 1190 */ 1191 static final int ENABLED = 0x00000000; 1192 1193 /** 1194 * This view is disabled. Interpretation varies by subclass. 1195 * Use with ENABLED_MASK when calling setFlags. 1196 * {@hide} 1197 */ 1198 static final int DISABLED = 0x00000020; 1199 1200 /** 1201 * Mask for use with setFlags indicating bits used for indicating whether 1202 * this view is enabled 1203 * {@hide} 1204 */ 1205 static final int ENABLED_MASK = 0x00000020; 1206 1207 /** 1208 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 1209 * called and further optimizations will be performed. It is okay to have 1210 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 1211 * {@hide} 1212 */ 1213 static final int WILL_NOT_DRAW = 0x00000080; 1214 1215 /** 1216 * Mask for use with setFlags indicating bits used for indicating whether 1217 * this view is will draw 1218 * {@hide} 1219 */ 1220 static final int DRAW_MASK = 0x00000080; 1221 1222 /** 1223 * <p>This view doesn't show scrollbars.</p> 1224 * {@hide} 1225 */ 1226 static final int SCROLLBARS_NONE = 0x00000000; 1227 1228 /** 1229 * <p>This view shows horizontal scrollbars.</p> 1230 * {@hide} 1231 */ 1232 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 1233 1234 /** 1235 * <p>This view shows vertical scrollbars.</p> 1236 * {@hide} 1237 */ 1238 static final int SCROLLBARS_VERTICAL = 0x00000200; 1239 1240 /** 1241 * <p>Mask for use with setFlags indicating bits used for indicating which 1242 * scrollbars are enabled.</p> 1243 * {@hide} 1244 */ 1245 static final int SCROLLBARS_MASK = 0x00000300; 1246 1247 /** 1248 * Indicates that the view should filter touches when its window is obscured. 1249 * Refer to the class comments for more information about this security feature. 1250 * {@hide} 1251 */ 1252 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 1253 1254 /** 1255 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 1256 * that they are optional and should be skipped if the window has 1257 * requested system UI flags that ignore those insets for layout. 1258 */ 1259 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 1260 1261 /** 1262 * <p>This view doesn't show fading edges.</p> 1263 * {@hide} 1264 */ 1265 static final int FADING_EDGE_NONE = 0x00000000; 1266 1267 /** 1268 * <p>This view shows horizontal fading edges.</p> 1269 * {@hide} 1270 */ 1271 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 1272 1273 /** 1274 * <p>This view shows vertical fading edges.</p> 1275 * {@hide} 1276 */ 1277 static final int FADING_EDGE_VERTICAL = 0x00002000; 1278 1279 /** 1280 * <p>Mask for use with setFlags indicating bits used for indicating which 1281 * fading edges are enabled.</p> 1282 * {@hide} 1283 */ 1284 static final int FADING_EDGE_MASK = 0x00003000; 1285 1286 /** 1287 * <p>Indicates this view can be clicked. When clickable, a View reacts 1288 * to clicks by notifying the OnClickListener.<p> 1289 * {@hide} 1290 */ 1291 static final int CLICKABLE = 0x00004000; 1292 1293 /** 1294 * <p>Indicates this view is caching its drawing into a bitmap.</p> 1295 * {@hide} 1296 */ 1297 static final int DRAWING_CACHE_ENABLED = 0x00008000; 1298 1299 /** 1300 * <p>Indicates that no icicle should be saved for this view.<p> 1301 * {@hide} 1302 */ 1303 static final int SAVE_DISABLED = 0x000010000; 1304 1305 /** 1306 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 1307 * property.</p> 1308 * {@hide} 1309 */ 1310 static final int SAVE_DISABLED_MASK = 0x000010000; 1311 1312 /** 1313 * <p>Indicates that no drawing cache should ever be created for this view.<p> 1314 * {@hide} 1315 */ 1316 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 1317 1318 /** 1319 * <p>Indicates this view can take / keep focus when int touch mode.</p> 1320 * {@hide} 1321 */ 1322 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 1323 1324 /** @hide */ 1325 @Retention(RetentionPolicy.SOURCE) 1326 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 1327 public @interface DrawingCacheQuality {} 1328 1329 /** 1330 * <p>Enables low quality mode for the drawing cache.</p> 1331 */ 1332 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 1333 1334 /** 1335 * <p>Enables high quality mode for the drawing cache.</p> 1336 */ 1337 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 1338 1339 /** 1340 * <p>Enables automatic quality mode for the drawing cache.</p> 1341 */ 1342 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 1343 1344 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 1345 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 1346 }; 1347 1348 /** 1349 * <p>Mask for use with setFlags indicating bits used for the cache 1350 * quality property.</p> 1351 * {@hide} 1352 */ 1353 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 1354 1355 /** 1356 * <p> 1357 * Indicates this view can be long clicked. When long clickable, a View 1358 * reacts to long clicks by notifying the OnLongClickListener or showing a 1359 * context menu. 1360 * </p> 1361 * {@hide} 1362 */ 1363 static final int LONG_CLICKABLE = 0x00200000; 1364 1365 /** 1366 * <p>Indicates that this view gets its drawable states from its direct parent 1367 * and ignores its original internal states.</p> 1368 * 1369 * @hide 1370 */ 1371 static final int DUPLICATE_PARENT_STATE = 0x00400000; 1372 1373 /** 1374 * <p> 1375 * Indicates this view can be context clicked. When context clickable, a View reacts to a 1376 * context click (e.g. a primary stylus button press or right mouse click) by notifying the 1377 * OnContextClickListener. 1378 * </p> 1379 * {@hide} 1380 */ 1381 static final int CONTEXT_CLICKABLE = 0x00800000; 1382 1383 1384 /** @hide */ 1385 @IntDef({ 1386 SCROLLBARS_INSIDE_OVERLAY, 1387 SCROLLBARS_INSIDE_INSET, 1388 SCROLLBARS_OUTSIDE_OVERLAY, 1389 SCROLLBARS_OUTSIDE_INSET 1390 }) 1391 @Retention(RetentionPolicy.SOURCE) 1392 public @interface ScrollBarStyle {} 1393 1394 /** 1395 * The scrollbar style to display the scrollbars inside the content area, 1396 * without increasing the padding. The scrollbars will be overlaid with 1397 * translucency on the view's content. 1398 */ 1399 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 1400 1401 /** 1402 * The scrollbar style to display the scrollbars inside the padded area, 1403 * increasing the padding of the view. The scrollbars will not overlap the 1404 * content area of the view. 1405 */ 1406 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1407 1408 /** 1409 * The scrollbar style to display the scrollbars at the edge of the view, 1410 * without increasing the padding. The scrollbars will be overlaid with 1411 * translucency. 1412 */ 1413 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1414 1415 /** 1416 * The scrollbar style to display the scrollbars at the edge of the view, 1417 * increasing the padding of the view. The scrollbars will only overlap the 1418 * background, if any. 1419 */ 1420 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1421 1422 /** 1423 * Mask to check if the scrollbar style is overlay or inset. 1424 * {@hide} 1425 */ 1426 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1427 1428 /** 1429 * Mask to check if the scrollbar style is inside or outside. 1430 * {@hide} 1431 */ 1432 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1433 1434 /** 1435 * Mask for scrollbar style. 1436 * {@hide} 1437 */ 1438 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1439 1440 /** 1441 * View flag indicating that the screen should remain on while the 1442 * window containing this view is visible to the user. This effectively 1443 * takes care of automatically setting the WindowManager's 1444 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1445 */ 1446 public static final int KEEP_SCREEN_ON = 0x04000000; 1447 1448 /** 1449 * View flag indicating whether this view should have sound effects enabled 1450 * for events such as clicking and touching. 1451 */ 1452 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1453 1454 /** 1455 * View flag indicating whether this view should have haptic feedback 1456 * enabled for events such as long presses. 1457 */ 1458 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1459 1460 /** 1461 * <p>Indicates that the view hierarchy should stop saving state when 1462 * it reaches this view. If state saving is initiated immediately at 1463 * the view, it will be allowed. 1464 * {@hide} 1465 */ 1466 static final int PARENT_SAVE_DISABLED = 0x20000000; 1467 1468 /** 1469 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1470 * {@hide} 1471 */ 1472 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1473 1474 private static Paint sDebugPaint; 1475 1476 /** 1477 * <p>Indicates this view can display a tooltip on hover or long press.</p> 1478 * {@hide} 1479 */ 1480 static final int TOOLTIP = 0x40000000; 1481 1482 /** @hide */ 1483 @IntDef(flag = true, 1484 value = { 1485 FOCUSABLES_ALL, 1486 FOCUSABLES_TOUCH_MODE 1487 }) 1488 @Retention(RetentionPolicy.SOURCE) 1489 public @interface FocusableMode {} 1490 1491 /** 1492 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1493 * should add all focusable Views regardless if they are focusable in touch mode. 1494 */ 1495 public static final int FOCUSABLES_ALL = 0x00000000; 1496 1497 /** 1498 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1499 * should add only Views focusable in touch mode. 1500 */ 1501 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1502 1503 /** @hide */ 1504 @IntDef({ 1505 FOCUS_BACKWARD, 1506 FOCUS_FORWARD, 1507 FOCUS_LEFT, 1508 FOCUS_UP, 1509 FOCUS_RIGHT, 1510 FOCUS_DOWN 1511 }) 1512 @Retention(RetentionPolicy.SOURCE) 1513 public @interface FocusDirection {} 1514 1515 /** @hide */ 1516 @IntDef({ 1517 FOCUS_LEFT, 1518 FOCUS_UP, 1519 FOCUS_RIGHT, 1520 FOCUS_DOWN 1521 }) 1522 @Retention(RetentionPolicy.SOURCE) 1523 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1524 1525 /** 1526 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1527 * item. 1528 */ 1529 public static final int FOCUS_BACKWARD = 0x00000001; 1530 1531 /** 1532 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1533 * item. 1534 */ 1535 public static final int FOCUS_FORWARD = 0x00000002; 1536 1537 /** 1538 * Use with {@link #focusSearch(int)}. Move focus to the left. 1539 */ 1540 public static final int FOCUS_LEFT = 0x00000011; 1541 1542 /** 1543 * Use with {@link #focusSearch(int)}. Move focus up. 1544 */ 1545 public static final int FOCUS_UP = 0x00000021; 1546 1547 /** 1548 * Use with {@link #focusSearch(int)}. Move focus to the right. 1549 */ 1550 public static final int FOCUS_RIGHT = 0x00000042; 1551 1552 /** 1553 * Use with {@link #focusSearch(int)}. Move focus down. 1554 */ 1555 public static final int FOCUS_DOWN = 0x00000082; 1556 1557 /** 1558 * Bits of {@link #getMeasuredWidthAndState()} and 1559 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1560 */ 1561 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1562 1563 /** 1564 * Bits of {@link #getMeasuredWidthAndState()} and 1565 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1566 */ 1567 public static final int MEASURED_STATE_MASK = 0xff000000; 1568 1569 /** 1570 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1571 * for functions that combine both width and height into a single int, 1572 * such as {@link #getMeasuredState()} and the childState argument of 1573 * {@link #resolveSizeAndState(int, int, int)}. 1574 */ 1575 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1576 1577 /** 1578 * Bit of {@link #getMeasuredWidthAndState()} and 1579 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1580 * is smaller that the space the view would like to have. 1581 */ 1582 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1583 1584 /** 1585 * Base View state sets 1586 */ 1587 // Singles 1588 /** 1589 * Indicates the view has no states set. States are used with 1590 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1591 * view depending on its state. 1592 * 1593 * @see android.graphics.drawable.Drawable 1594 * @see #getDrawableState() 1595 */ 1596 protected static final int[] EMPTY_STATE_SET; 1597 /** 1598 * Indicates the view is enabled. States are used with 1599 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1600 * view depending on its state. 1601 * 1602 * @see android.graphics.drawable.Drawable 1603 * @see #getDrawableState() 1604 */ 1605 protected static final int[] ENABLED_STATE_SET; 1606 /** 1607 * Indicates the view is focused. States are used with 1608 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1609 * view depending on its state. 1610 * 1611 * @see android.graphics.drawable.Drawable 1612 * @see #getDrawableState() 1613 */ 1614 protected static final int[] FOCUSED_STATE_SET; 1615 /** 1616 * Indicates the view is selected. States are used with 1617 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1618 * view depending on its state. 1619 * 1620 * @see android.graphics.drawable.Drawable 1621 * @see #getDrawableState() 1622 */ 1623 protected static final int[] SELECTED_STATE_SET; 1624 /** 1625 * Indicates the view is pressed. States are used with 1626 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1627 * view depending on its state. 1628 * 1629 * @see android.graphics.drawable.Drawable 1630 * @see #getDrawableState() 1631 */ 1632 protected static final int[] PRESSED_STATE_SET; 1633 /** 1634 * Indicates the view's window has focus. States are used with 1635 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1636 * view depending on its state. 1637 * 1638 * @see android.graphics.drawable.Drawable 1639 * @see #getDrawableState() 1640 */ 1641 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1642 // Doubles 1643 /** 1644 * Indicates the view is enabled and has the focus. 1645 * 1646 * @see #ENABLED_STATE_SET 1647 * @see #FOCUSED_STATE_SET 1648 */ 1649 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1650 /** 1651 * Indicates the view is enabled and selected. 1652 * 1653 * @see #ENABLED_STATE_SET 1654 * @see #SELECTED_STATE_SET 1655 */ 1656 protected static final int[] ENABLED_SELECTED_STATE_SET; 1657 /** 1658 * Indicates the view is enabled and that its window has focus. 1659 * 1660 * @see #ENABLED_STATE_SET 1661 * @see #WINDOW_FOCUSED_STATE_SET 1662 */ 1663 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1664 /** 1665 * Indicates the view is focused and selected. 1666 * 1667 * @see #FOCUSED_STATE_SET 1668 * @see #SELECTED_STATE_SET 1669 */ 1670 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1671 /** 1672 * Indicates the view has the focus and that its window has the focus. 1673 * 1674 * @see #FOCUSED_STATE_SET 1675 * @see #WINDOW_FOCUSED_STATE_SET 1676 */ 1677 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1678 /** 1679 * Indicates the view is selected and that its window has the focus. 1680 * 1681 * @see #SELECTED_STATE_SET 1682 * @see #WINDOW_FOCUSED_STATE_SET 1683 */ 1684 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1685 // Triples 1686 /** 1687 * Indicates the view is enabled, focused and selected. 1688 * 1689 * @see #ENABLED_STATE_SET 1690 * @see #FOCUSED_STATE_SET 1691 * @see #SELECTED_STATE_SET 1692 */ 1693 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1694 /** 1695 * Indicates the view is enabled, focused and its window has the focus. 1696 * 1697 * @see #ENABLED_STATE_SET 1698 * @see #FOCUSED_STATE_SET 1699 * @see #WINDOW_FOCUSED_STATE_SET 1700 */ 1701 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1702 /** 1703 * Indicates the view is enabled, selected and its window has the focus. 1704 * 1705 * @see #ENABLED_STATE_SET 1706 * @see #SELECTED_STATE_SET 1707 * @see #WINDOW_FOCUSED_STATE_SET 1708 */ 1709 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1710 /** 1711 * Indicates the view is focused, selected and its window has the focus. 1712 * 1713 * @see #FOCUSED_STATE_SET 1714 * @see #SELECTED_STATE_SET 1715 * @see #WINDOW_FOCUSED_STATE_SET 1716 */ 1717 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1718 /** 1719 * Indicates the view is enabled, focused, selected and its window 1720 * has the focus. 1721 * 1722 * @see #ENABLED_STATE_SET 1723 * @see #FOCUSED_STATE_SET 1724 * @see #SELECTED_STATE_SET 1725 * @see #WINDOW_FOCUSED_STATE_SET 1726 */ 1727 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1728 /** 1729 * Indicates the view is pressed and its window has the focus. 1730 * 1731 * @see #PRESSED_STATE_SET 1732 * @see #WINDOW_FOCUSED_STATE_SET 1733 */ 1734 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1735 /** 1736 * Indicates the view is pressed and selected. 1737 * 1738 * @see #PRESSED_STATE_SET 1739 * @see #SELECTED_STATE_SET 1740 */ 1741 protected static final int[] PRESSED_SELECTED_STATE_SET; 1742 /** 1743 * Indicates the view is pressed, selected and its window has the focus. 1744 * 1745 * @see #PRESSED_STATE_SET 1746 * @see #SELECTED_STATE_SET 1747 * @see #WINDOW_FOCUSED_STATE_SET 1748 */ 1749 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1750 /** 1751 * Indicates the view is pressed and focused. 1752 * 1753 * @see #PRESSED_STATE_SET 1754 * @see #FOCUSED_STATE_SET 1755 */ 1756 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1757 /** 1758 * Indicates the view is pressed, focused and its window has the focus. 1759 * 1760 * @see #PRESSED_STATE_SET 1761 * @see #FOCUSED_STATE_SET 1762 * @see #WINDOW_FOCUSED_STATE_SET 1763 */ 1764 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1765 /** 1766 * Indicates the view is pressed, focused and selected. 1767 * 1768 * @see #PRESSED_STATE_SET 1769 * @see #SELECTED_STATE_SET 1770 * @see #FOCUSED_STATE_SET 1771 */ 1772 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1773 /** 1774 * Indicates the view is pressed, focused, selected and its window has the focus. 1775 * 1776 * @see #PRESSED_STATE_SET 1777 * @see #FOCUSED_STATE_SET 1778 * @see #SELECTED_STATE_SET 1779 * @see #WINDOW_FOCUSED_STATE_SET 1780 */ 1781 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1782 /** 1783 * Indicates the view is pressed and enabled. 1784 * 1785 * @see #PRESSED_STATE_SET 1786 * @see #ENABLED_STATE_SET 1787 */ 1788 protected static final int[] PRESSED_ENABLED_STATE_SET; 1789 /** 1790 * Indicates the view is pressed, enabled and its window has the focus. 1791 * 1792 * @see #PRESSED_STATE_SET 1793 * @see #ENABLED_STATE_SET 1794 * @see #WINDOW_FOCUSED_STATE_SET 1795 */ 1796 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1797 /** 1798 * Indicates the view is pressed, enabled and selected. 1799 * 1800 * @see #PRESSED_STATE_SET 1801 * @see #ENABLED_STATE_SET 1802 * @see #SELECTED_STATE_SET 1803 */ 1804 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1805 /** 1806 * Indicates the view is pressed, enabled, selected and its window has the 1807 * focus. 1808 * 1809 * @see #PRESSED_STATE_SET 1810 * @see #ENABLED_STATE_SET 1811 * @see #SELECTED_STATE_SET 1812 * @see #WINDOW_FOCUSED_STATE_SET 1813 */ 1814 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1815 /** 1816 * Indicates the view is pressed, enabled and focused. 1817 * 1818 * @see #PRESSED_STATE_SET 1819 * @see #ENABLED_STATE_SET 1820 * @see #FOCUSED_STATE_SET 1821 */ 1822 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1823 /** 1824 * Indicates the view is pressed, enabled, focused and its window has the 1825 * focus. 1826 * 1827 * @see #PRESSED_STATE_SET 1828 * @see #ENABLED_STATE_SET 1829 * @see #FOCUSED_STATE_SET 1830 * @see #WINDOW_FOCUSED_STATE_SET 1831 */ 1832 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1833 /** 1834 * Indicates the view is pressed, enabled, focused and selected. 1835 * 1836 * @see #PRESSED_STATE_SET 1837 * @see #ENABLED_STATE_SET 1838 * @see #SELECTED_STATE_SET 1839 * @see #FOCUSED_STATE_SET 1840 */ 1841 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1842 /** 1843 * Indicates the view is pressed, enabled, focused, selected and its window 1844 * has the focus. 1845 * 1846 * @see #PRESSED_STATE_SET 1847 * @see #ENABLED_STATE_SET 1848 * @see #SELECTED_STATE_SET 1849 * @see #FOCUSED_STATE_SET 1850 * @see #WINDOW_FOCUSED_STATE_SET 1851 */ 1852 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1853 1854 static { 1855 EMPTY_STATE_SET = StateSet.get(0); 1856 1857 WINDOW_FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_WINDOW_FOCUSED); 1858 1859 SELECTED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_SELECTED); 1860 SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1861 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED); 1862 1863 FOCUSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_FOCUSED); 1864 FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1865 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED); 1866 FOCUSED_SELECTED_STATE_SET = StateSet.get( 1867 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED); 1868 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1869 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1870 | StateSet.VIEW_STATE_FOCUSED); 1871 1872 ENABLED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_ENABLED); 1873 ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1874 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1875 ENABLED_SELECTED_STATE_SET = StateSet.get( 1876 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED); 1877 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1878 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1879 | StateSet.VIEW_STATE_ENABLED); 1880 ENABLED_FOCUSED_STATE_SET = StateSet.get( 1881 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED); 1882 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1883 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1884 | StateSet.VIEW_STATE_ENABLED); 1885 ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1886 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1887 | StateSet.VIEW_STATE_ENABLED); 1888 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1889 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1890 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED); 1891 1892 PRESSED_STATE_SET = StateSet.get(StateSet.VIEW_STATE_PRESSED); 1893 PRESSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1894 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1895 PRESSED_SELECTED_STATE_SET = StateSet.get( 1896 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_PRESSED); 1897 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1898 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1899 | StateSet.VIEW_STATE_PRESSED); 1900 PRESSED_FOCUSED_STATE_SET = StateSet.get( 1901 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1902 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1903 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1904 | StateSet.VIEW_STATE_PRESSED); 1905 PRESSED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1906 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1907 | StateSet.VIEW_STATE_PRESSED); 1908 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1909 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1910 | StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_PRESSED); 1911 PRESSED_ENABLED_STATE_SET = StateSet.get( 1912 StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1913 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1914 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_ENABLED 1915 | StateSet.VIEW_STATE_PRESSED); 1916 PRESSED_ENABLED_SELECTED_STATE_SET = StateSet.get( 1917 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_ENABLED 1918 | StateSet.VIEW_STATE_PRESSED); 1919 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1920 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1921 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1922 PRESSED_ENABLED_FOCUSED_STATE_SET = StateSet.get( 1923 StateSet.VIEW_STATE_FOCUSED | StateSet.VIEW_STATE_ENABLED 1924 | StateSet.VIEW_STATE_PRESSED); 1925 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1926 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_FOCUSED 1927 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1928 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = StateSet.get( 1929 StateSet.VIEW_STATE_SELECTED | StateSet.VIEW_STATE_FOCUSED 1930 | StateSet.VIEW_STATE_ENABLED | StateSet.VIEW_STATE_PRESSED); 1931 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = StateSet.get( 1932 StateSet.VIEW_STATE_WINDOW_FOCUSED | StateSet.VIEW_STATE_SELECTED 1933 | StateSet.VIEW_STATE_FOCUSED| StateSet.VIEW_STATE_ENABLED 1934 | StateSet.VIEW_STATE_PRESSED); 1935 } 1936 1937 /** 1938 * Accessibility event types that are dispatched for text population. 1939 */ 1940 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1941 AccessibilityEvent.TYPE_VIEW_CLICKED 1942 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1943 | AccessibilityEvent.TYPE_VIEW_SELECTED 1944 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1945 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1946 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1947 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1948 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1949 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1950 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1951 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1952 1953 static final int DEBUG_CORNERS_COLOR = Color.rgb(63, 127, 255); 1954 1955 static final int DEBUG_CORNERS_SIZE_DIP = 8; 1956 1957 /** 1958 * Temporary Rect currently for use in setBackground(). This will probably 1959 * be extended in the future to hold our own class with more than just 1960 * a Rect. :) 1961 */ 1962 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1963 1964 /** 1965 * Map used to store views' tags. 1966 */ 1967 private SparseArray<Object> mKeyedTags; 1968 1969 /** 1970 * The next available accessibility id. 1971 */ 1972 private static int sNextAccessibilityViewId; 1973 1974 /** 1975 * The animation currently associated with this view. 1976 * @hide 1977 */ 1978 protected Animation mCurrentAnimation = null; 1979 1980 /** 1981 * Width as measured during measure pass. 1982 * {@hide} 1983 */ 1984 @ViewDebug.ExportedProperty(category = "measurement") 1985 int mMeasuredWidth; 1986 1987 /** 1988 * Height as measured during measure pass. 1989 * {@hide} 1990 */ 1991 @ViewDebug.ExportedProperty(category = "measurement") 1992 int mMeasuredHeight; 1993 1994 /** 1995 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1996 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1997 * its display list. This flag, used only when hw accelerated, allows us to clear the 1998 * flag while retaining this information until it's needed (at getDisplayList() time and 1999 * in drawChild(), when we decide to draw a view's children's display lists into our own). 2000 * 2001 * {@hide} 2002 */ 2003 boolean mRecreateDisplayList = false; 2004 2005 /** 2006 * The view's identifier. 2007 * {@hide} 2008 * 2009 * @see #setId(int) 2010 * @see #getId() 2011 */ 2012 @IdRes 2013 @ViewDebug.ExportedProperty(resolveId = true) 2014 int mID = NO_ID; 2015 2016 /** 2017 * The stable ID of this view for accessibility purposes. 2018 */ 2019 int mAccessibilityViewId = NO_ID; 2020 2021 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 2022 2023 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 2024 2025 /** 2026 * The view's tag. 2027 * {@hide} 2028 * 2029 * @see #setTag(Object) 2030 * @see #getTag() 2031 */ 2032 protected Object mTag = null; 2033 2034 // for mPrivateFlags: 2035 /** {@hide} */ 2036 static final int PFLAG_WANTS_FOCUS = 0x00000001; 2037 /** {@hide} */ 2038 static final int PFLAG_FOCUSED = 0x00000002; 2039 /** {@hide} */ 2040 static final int PFLAG_SELECTED = 0x00000004; 2041 /** {@hide} */ 2042 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 2043 /** {@hide} */ 2044 static final int PFLAG_HAS_BOUNDS = 0x00000010; 2045 /** {@hide} */ 2046 static final int PFLAG_DRAWN = 0x00000020; 2047 /** 2048 * When this flag is set, this view is running an animation on behalf of its 2049 * children and should therefore not cancel invalidate requests, even if they 2050 * lie outside of this view's bounds. 2051 * 2052 * {@hide} 2053 */ 2054 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 2055 /** {@hide} */ 2056 static final int PFLAG_SKIP_DRAW = 0x00000080; 2057 /** {@hide} */ 2058 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 2059 /** {@hide} */ 2060 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 2061 /** {@hide} */ 2062 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 2063 /** {@hide} */ 2064 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 2065 /** {@hide} */ 2066 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 2067 2068 private static final int PFLAG_PRESSED = 0x00004000; 2069 2070 /** {@hide} */ 2071 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 2072 /** 2073 * Flag used to indicate that this view should be drawn once more (and only once 2074 * more) after its animation has completed. 2075 * {@hide} 2076 */ 2077 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 2078 2079 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 2080 2081 /** 2082 * Indicates that the View returned true when onSetAlpha() was called and that 2083 * the alpha must be restored. 2084 * {@hide} 2085 */ 2086 static final int PFLAG_ALPHA_SET = 0x00040000; 2087 2088 /** 2089 * Set by {@link #setScrollContainer(boolean)}. 2090 */ 2091 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 2092 2093 /** 2094 * Set by {@link #setScrollContainer(boolean)}. 2095 */ 2096 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 2097 2098 /** 2099 * View flag indicating whether this view was invalidated (fully or partially.) 2100 * 2101 * @hide 2102 */ 2103 static final int PFLAG_DIRTY = 0x00200000; 2104 2105 /** 2106 * View flag indicating whether this view was invalidated by an opaque 2107 * invalidate request. 2108 * 2109 * @hide 2110 */ 2111 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 2112 2113 /** 2114 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 2115 * 2116 * @hide 2117 */ 2118 static final int PFLAG_DIRTY_MASK = 0x00600000; 2119 2120 /** 2121 * Indicates whether the background is opaque. 2122 * 2123 * @hide 2124 */ 2125 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 2126 2127 /** 2128 * Indicates whether the scrollbars are opaque. 2129 * 2130 * @hide 2131 */ 2132 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 2133 2134 /** 2135 * Indicates whether the view is opaque. 2136 * 2137 * @hide 2138 */ 2139 static final int PFLAG_OPAQUE_MASK = 0x01800000; 2140 2141 /** 2142 * Indicates a prepressed state; 2143 * the short time between ACTION_DOWN and recognizing 2144 * a 'real' press. Prepressed is used to recognize quick taps 2145 * even when they are shorter than ViewConfiguration.getTapTimeout(). 2146 * 2147 * @hide 2148 */ 2149 private static final int PFLAG_PREPRESSED = 0x02000000; 2150 2151 /** 2152 * Indicates whether the view is temporarily detached. 2153 * 2154 * @hide 2155 */ 2156 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 2157 2158 /** 2159 * Indicates that we should awaken scroll bars once attached 2160 * 2161 * PLEASE NOTE: This flag is now unused as we now send onVisibilityChanged 2162 * during window attachment and it is no longer needed. Feel free to repurpose it. 2163 * 2164 * @hide 2165 */ 2166 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 2167 2168 /** 2169 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 2170 * @hide 2171 */ 2172 private static final int PFLAG_HOVERED = 0x10000000; 2173 2174 /** 2175 * no longer needed, should be reused 2176 */ 2177 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 2178 2179 /** {@hide} */ 2180 static final int PFLAG_ACTIVATED = 0x40000000; 2181 2182 /** 2183 * Indicates that this view was specifically invalidated, not just dirtied because some 2184 * child view was invalidated. The flag is used to determine when we need to recreate 2185 * a view's display list (as opposed to just returning a reference to its existing 2186 * display list). 2187 * 2188 * @hide 2189 */ 2190 static final int PFLAG_INVALIDATED = 0x80000000; 2191 2192 /** 2193 * Masks for mPrivateFlags2, as generated by dumpFlags(): 2194 * 2195 * |-------|-------|-------|-------| 2196 * 1 PFLAG2_DRAG_CAN_ACCEPT 2197 * 1 PFLAG2_DRAG_HOVERED 2198 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 2199 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 2200 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 2201 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 2202 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 2203 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 2204 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 2205 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 2206 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 2207 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[6] 2208 * 111 PFLAG2_TEXT_DIRECTION_FLAGS[7] 2209 * 111 PFLAG2_TEXT_DIRECTION_MASK 2210 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 2211 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 2212 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 2213 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 2214 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 2215 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 2216 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 2217 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 2218 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 2219 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 2220 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 2221 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 2222 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 2223 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 2224 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 2225 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 2226 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 2227 * 1 PFLAG2_VIEW_QUICK_REJECTED 2228 * 1 PFLAG2_PADDING_RESOLVED 2229 * 1 PFLAG2_DRAWABLE_RESOLVED 2230 * 1 PFLAG2_HAS_TRANSIENT_STATE 2231 * |-------|-------|-------|-------| 2232 */ 2233 2234 /** 2235 * Indicates that this view has reported that it can accept the current drag's content. 2236 * Cleared when the drag operation concludes. 2237 * @hide 2238 */ 2239 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 2240 2241 /** 2242 * Indicates that this view is currently directly under the drag location in a 2243 * drag-and-drop operation involving content that it can accept. Cleared when 2244 * the drag exits the view, or when the drag operation concludes. 2245 * @hide 2246 */ 2247 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 2248 2249 /** @hide */ 2250 @IntDef({ 2251 LAYOUT_DIRECTION_LTR, 2252 LAYOUT_DIRECTION_RTL, 2253 LAYOUT_DIRECTION_INHERIT, 2254 LAYOUT_DIRECTION_LOCALE 2255 }) 2256 @Retention(RetentionPolicy.SOURCE) 2257 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 2258 public @interface LayoutDir {} 2259 2260 /** @hide */ 2261 @IntDef({ 2262 LAYOUT_DIRECTION_LTR, 2263 LAYOUT_DIRECTION_RTL 2264 }) 2265 @Retention(RetentionPolicy.SOURCE) 2266 public @interface ResolvedLayoutDir {} 2267 2268 /** 2269 * A flag to indicate that the layout direction of this view has not been defined yet. 2270 * @hide 2271 */ 2272 public static final int LAYOUT_DIRECTION_UNDEFINED = LayoutDirection.UNDEFINED; 2273 2274 /** 2275 * Horizontal layout direction of this view is from Left to Right. 2276 * Use with {@link #setLayoutDirection}. 2277 */ 2278 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 2279 2280 /** 2281 * Horizontal layout direction of this view is from Right to Left. 2282 * Use with {@link #setLayoutDirection}. 2283 */ 2284 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 2285 2286 /** 2287 * Horizontal layout direction of this view is inherited from its parent. 2288 * Use with {@link #setLayoutDirection}. 2289 */ 2290 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 2291 2292 /** 2293 * Horizontal layout direction of this view is from deduced from the default language 2294 * script for the locale. Use with {@link #setLayoutDirection}. 2295 */ 2296 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 2297 2298 /** 2299 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2300 * @hide 2301 */ 2302 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 2303 2304 /** 2305 * Mask for use with private flags indicating bits used for horizontal layout direction. 2306 * @hide 2307 */ 2308 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2309 2310 /** 2311 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 2312 * right-to-left direction. 2313 * @hide 2314 */ 2315 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2316 2317 /** 2318 * Indicates whether the view horizontal layout direction has been resolved. 2319 * @hide 2320 */ 2321 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2322 2323 /** 2324 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 2325 * @hide 2326 */ 2327 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 2328 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 2329 2330 /* 2331 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 2332 * flag value. 2333 * @hide 2334 */ 2335 private static final int[] LAYOUT_DIRECTION_FLAGS = { 2336 LAYOUT_DIRECTION_LTR, 2337 LAYOUT_DIRECTION_RTL, 2338 LAYOUT_DIRECTION_INHERIT, 2339 LAYOUT_DIRECTION_LOCALE 2340 }; 2341 2342 /** 2343 * Default horizontal layout direction. 2344 */ 2345 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 2346 2347 /** 2348 * Default horizontal layout direction. 2349 * @hide 2350 */ 2351 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 2352 2353 /** 2354 * Text direction is inherited through {@link ViewGroup} 2355 */ 2356 public static final int TEXT_DIRECTION_INHERIT = 0; 2357 2358 /** 2359 * Text direction is using "first strong algorithm". The first strong directional character 2360 * determines the paragraph direction. If there is no strong directional character, the 2361 * paragraph direction is the view's resolved layout direction. 2362 */ 2363 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 2364 2365 /** 2366 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 2367 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 2368 * If there are neither, the paragraph direction is the view's resolved layout direction. 2369 */ 2370 public static final int TEXT_DIRECTION_ANY_RTL = 2; 2371 2372 /** 2373 * Text direction is forced to LTR. 2374 */ 2375 public static final int TEXT_DIRECTION_LTR = 3; 2376 2377 /** 2378 * Text direction is forced to RTL. 2379 */ 2380 public static final int TEXT_DIRECTION_RTL = 4; 2381 2382 /** 2383 * Text direction is coming from the system Locale. 2384 */ 2385 public static final int TEXT_DIRECTION_LOCALE = 5; 2386 2387 /** 2388 * Text direction is using "first strong algorithm". The first strong directional character 2389 * determines the paragraph direction. If there is no strong directional character, the 2390 * paragraph direction is LTR. 2391 */ 2392 public static final int TEXT_DIRECTION_FIRST_STRONG_LTR = 6; 2393 2394 /** 2395 * Text direction is using "first strong algorithm". The first strong directional character 2396 * determines the paragraph direction. If there is no strong directional character, the 2397 * paragraph direction is RTL. 2398 */ 2399 public static final int TEXT_DIRECTION_FIRST_STRONG_RTL = 7; 2400 2401 /** 2402 * Default text direction is inherited 2403 */ 2404 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2405 2406 /** 2407 * Default resolved text direction 2408 * @hide 2409 */ 2410 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2411 2412 /** 2413 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2414 * @hide 2415 */ 2416 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2417 2418 /** 2419 * Mask for use with private flags indicating bits used for text direction. 2420 * @hide 2421 */ 2422 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2423 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2424 2425 /** 2426 * Array of text direction flags for mapping attribute "textDirection" to correct 2427 * flag value. 2428 * @hide 2429 */ 2430 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2431 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2432 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2433 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2434 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2435 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2436 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2437 TEXT_DIRECTION_FIRST_STRONG_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2438 TEXT_DIRECTION_FIRST_STRONG_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2439 }; 2440 2441 /** 2442 * Indicates whether the view text direction has been resolved. 2443 * @hide 2444 */ 2445 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2446 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2447 2448 /** 2449 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2450 * @hide 2451 */ 2452 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2453 2454 /** 2455 * Mask for use with private flags indicating bits used for resolved text direction. 2456 * @hide 2457 */ 2458 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2459 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2460 2461 /** 2462 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2463 * @hide 2464 */ 2465 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2466 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2467 2468 /** @hide */ 2469 @IntDef({ 2470 TEXT_ALIGNMENT_INHERIT, 2471 TEXT_ALIGNMENT_GRAVITY, 2472 TEXT_ALIGNMENT_CENTER, 2473 TEXT_ALIGNMENT_TEXT_START, 2474 TEXT_ALIGNMENT_TEXT_END, 2475 TEXT_ALIGNMENT_VIEW_START, 2476 TEXT_ALIGNMENT_VIEW_END 2477 }) 2478 @Retention(RetentionPolicy.SOURCE) 2479 public @interface TextAlignment {} 2480 2481 /** 2482 * Default text alignment. The text alignment of this View is inherited from its parent. 2483 * Use with {@link #setTextAlignment(int)} 2484 */ 2485 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2486 2487 /** 2488 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2489 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2490 * 2491 * Use with {@link #setTextAlignment(int)} 2492 */ 2493 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2494 2495 /** 2496 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2497 * 2498 * Use with {@link #setTextAlignment(int)} 2499 */ 2500 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2501 2502 /** 2503 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2504 * 2505 * Use with {@link #setTextAlignment(int)} 2506 */ 2507 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2508 2509 /** 2510 * Center the paragraph, e.g. ALIGN_CENTER. 2511 * 2512 * Use with {@link #setTextAlignment(int)} 2513 */ 2514 public static final int TEXT_ALIGNMENT_CENTER = 4; 2515 2516 /** 2517 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2518 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2519 * 2520 * Use with {@link #setTextAlignment(int)} 2521 */ 2522 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2523 2524 /** 2525 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2526 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2527 * 2528 * Use with {@link #setTextAlignment(int)} 2529 */ 2530 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2531 2532 /** 2533 * Default text alignment is inherited 2534 */ 2535 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2536 2537 /** 2538 * Default resolved text alignment 2539 * @hide 2540 */ 2541 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2542 2543 /** 2544 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2545 * @hide 2546 */ 2547 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2548 2549 /** 2550 * Mask for use with private flags indicating bits used for text alignment. 2551 * @hide 2552 */ 2553 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2554 2555 /** 2556 * Array of text direction flags for mapping attribute "textAlignment" to correct 2557 * flag value. 2558 * @hide 2559 */ 2560 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2561 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2562 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2563 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2564 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2565 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2566 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2567 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2568 }; 2569 2570 /** 2571 * Indicates whether the view text alignment has been resolved. 2572 * @hide 2573 */ 2574 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2575 2576 /** 2577 * Bit shift to get the resolved text alignment. 2578 * @hide 2579 */ 2580 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2581 2582 /** 2583 * Mask for use with private flags indicating bits used for text alignment. 2584 * @hide 2585 */ 2586 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2587 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2588 2589 /** 2590 * Indicates whether if the view text alignment has been resolved to gravity 2591 */ 2592 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2593 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2594 2595 // Accessiblity constants for mPrivateFlags2 2596 2597 /** 2598 * Shift for the bits in {@link #mPrivateFlags2} related to the 2599 * "importantForAccessibility" attribute. 2600 */ 2601 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2602 2603 /** 2604 * Automatically determine whether a view is important for accessibility. 2605 */ 2606 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2607 2608 /** 2609 * The view is important for accessibility. 2610 */ 2611 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2612 2613 /** 2614 * The view is not important for accessibility. 2615 */ 2616 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2617 2618 /** 2619 * The view is not important for accessibility, nor are any of its 2620 * descendant views. 2621 */ 2622 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2623 2624 /** 2625 * The default whether the view is important for accessibility. 2626 */ 2627 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2628 2629 /** 2630 * Mask for obtaining the bits which specify how to determine 2631 * whether a view is important for accessibility. 2632 */ 2633 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2634 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2635 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2636 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2637 2638 /** 2639 * Shift for the bits in {@link #mPrivateFlags2} related to the 2640 * "accessibilityLiveRegion" attribute. 2641 */ 2642 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2643 2644 /** 2645 * Live region mode specifying that accessibility services should not 2646 * automatically announce changes to this view. This is the default live 2647 * region mode for most views. 2648 * <p> 2649 * Use with {@link #setAccessibilityLiveRegion(int)}. 2650 */ 2651 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2652 2653 /** 2654 * Live region mode specifying that accessibility services should announce 2655 * changes to this view. 2656 * <p> 2657 * Use with {@link #setAccessibilityLiveRegion(int)}. 2658 */ 2659 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2660 2661 /** 2662 * Live region mode specifying that accessibility services should interrupt 2663 * ongoing speech to immediately announce changes to this view. 2664 * <p> 2665 * Use with {@link #setAccessibilityLiveRegion(int)}. 2666 */ 2667 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2668 2669 /** 2670 * The default whether the view is important for accessibility. 2671 */ 2672 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2673 2674 /** 2675 * Mask for obtaining the bits which specify a view's accessibility live 2676 * region mode. 2677 */ 2678 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2679 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2680 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2681 2682 /** 2683 * Flag indicating whether a view has accessibility focus. 2684 */ 2685 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2686 2687 /** 2688 * Flag whether the accessibility state of the subtree rooted at this view changed. 2689 */ 2690 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2691 2692 /** 2693 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2694 * is used to check whether later changes to the view's transform should invalidate the 2695 * view to force the quickReject test to run again. 2696 */ 2697 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2698 2699 /** 2700 * Flag indicating that start/end padding has been resolved into left/right padding 2701 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2702 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2703 * during measurement. In some special cases this is required such as when an adapter-based 2704 * view measures prospective children without attaching them to a window. 2705 */ 2706 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2707 2708 /** 2709 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2710 */ 2711 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2712 2713 /** 2714 * Indicates that the view is tracking some sort of transient state 2715 * that the app should not need to be aware of, but that the framework 2716 * should take special care to preserve. 2717 */ 2718 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2719 2720 /** 2721 * Group of bits indicating that RTL properties resolution is done. 2722 */ 2723 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2724 PFLAG2_TEXT_DIRECTION_RESOLVED | 2725 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2726 PFLAG2_PADDING_RESOLVED | 2727 PFLAG2_DRAWABLE_RESOLVED; 2728 2729 // There are a couple of flags left in mPrivateFlags2 2730 2731 /* End of masks for mPrivateFlags2 */ 2732 2733 /** 2734 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2735 * 2736 * |-------|-------|-------|-------| 2737 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2738 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2739 * 1 PFLAG3_IS_LAID_OUT 2740 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2741 * 1 PFLAG3_CALLED_SUPER 2742 * 1 PFLAG3_APPLYING_INSETS 2743 * 1 PFLAG3_FITTING_SYSTEM_WINDOWS 2744 * 1 PFLAG3_NESTED_SCROLLING_ENABLED 2745 * 1 PFLAG3_SCROLL_INDICATOR_TOP 2746 * 1 PFLAG3_SCROLL_INDICATOR_BOTTOM 2747 * 1 PFLAG3_SCROLL_INDICATOR_LEFT 2748 * 1 PFLAG3_SCROLL_INDICATOR_RIGHT 2749 * 1 PFLAG3_SCROLL_INDICATOR_START 2750 * 1 PFLAG3_SCROLL_INDICATOR_END 2751 * 1 PFLAG3_ASSIST_BLOCKED 2752 * 1 PFLAG3_CLUSTER 2753 * x * NO LONGER NEEDED, SHOULD BE REUSED * 2754 * 1 PFLAG3_FINGER_DOWN 2755 * 1 PFLAG3_FOCUSED_BY_DEFAULT 2756 * 11 PFLAG3_AUTO_FILL_MODE_MASK 2757 * 11 PFLAG3_IMPORTANT_FOR_AUTOFILL 2758 * 1 PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE 2759 * 1 PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED 2760 * 1 PFLAG3_TEMPORARY_DETACH 2761 * 1 PFLAG3_NO_REVEAL_ON_FOCUS 2762 * |-------|-------|-------|-------| 2763 */ 2764 2765 /** 2766 * Flag indicating that view has a transform animation set on it. This is used to track whether 2767 * an animation is cleared between successive frames, in order to tell the associated 2768 * DisplayList to clear its animation matrix. 2769 */ 2770 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2771 2772 /** 2773 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2774 * animation is cleared between successive frames, in order to tell the associated 2775 * DisplayList to restore its alpha value. 2776 */ 2777 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2778 2779 /** 2780 * Flag indicating that the view has been through at least one layout since it 2781 * was last attached to a window. 2782 */ 2783 static final int PFLAG3_IS_LAID_OUT = 0x4; 2784 2785 /** 2786 * Flag indicating that a call to measure() was skipped and should be done 2787 * instead when layout() is invoked. 2788 */ 2789 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2790 2791 /** 2792 * Flag indicating that an overridden method correctly called down to 2793 * the superclass implementation as required by the API spec. 2794 */ 2795 static final int PFLAG3_CALLED_SUPER = 0x10; 2796 2797 /** 2798 * Flag indicating that we're in the process of applying window insets. 2799 */ 2800 static final int PFLAG3_APPLYING_INSETS = 0x20; 2801 2802 /** 2803 * Flag indicating that we're in the process of fitting system windows using the old method. 2804 */ 2805 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2806 2807 /** 2808 * Flag indicating that nested scrolling is enabled for this view. 2809 * The view will optionally cooperate with views up its parent chain to allow for 2810 * integrated nested scrolling along the same axis. 2811 */ 2812 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2813 2814 /** 2815 * Flag indicating that the bottom scroll indicator should be displayed 2816 * when this view can scroll up. 2817 */ 2818 static final int PFLAG3_SCROLL_INDICATOR_TOP = 0x0100; 2819 2820 /** 2821 * Flag indicating that the bottom scroll indicator should be displayed 2822 * when this view can scroll down. 2823 */ 2824 static final int PFLAG3_SCROLL_INDICATOR_BOTTOM = 0x0200; 2825 2826 /** 2827 * Flag indicating that the left scroll indicator should be displayed 2828 * when this view can scroll left. 2829 */ 2830 static final int PFLAG3_SCROLL_INDICATOR_LEFT = 0x0400; 2831 2832 /** 2833 * Flag indicating that the right scroll indicator should be displayed 2834 * when this view can scroll right. 2835 */ 2836 static final int PFLAG3_SCROLL_INDICATOR_RIGHT = 0x0800; 2837 2838 /** 2839 * Flag indicating that the start scroll indicator should be displayed 2840 * when this view can scroll in the start direction. 2841 */ 2842 static final int PFLAG3_SCROLL_INDICATOR_START = 0x1000; 2843 2844 /** 2845 * Flag indicating that the end scroll indicator should be displayed 2846 * when this view can scroll in the end direction. 2847 */ 2848 static final int PFLAG3_SCROLL_INDICATOR_END = 0x2000; 2849 2850 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2851 2852 static final int SCROLL_INDICATORS_NONE = 0x0000; 2853 2854 /** 2855 * Mask for use with setFlags indicating bits used for indicating which 2856 * scroll indicators are enabled. 2857 */ 2858 static final int SCROLL_INDICATORS_PFLAG3_MASK = PFLAG3_SCROLL_INDICATOR_TOP 2859 | PFLAG3_SCROLL_INDICATOR_BOTTOM | PFLAG3_SCROLL_INDICATOR_LEFT 2860 | PFLAG3_SCROLL_INDICATOR_RIGHT | PFLAG3_SCROLL_INDICATOR_START 2861 | PFLAG3_SCROLL_INDICATOR_END; 2862 2863 /** 2864 * Left-shift required to translate between public scroll indicator flags 2865 * and internal PFLAGS3 flags. When used as a right-shift, translates 2866 * PFLAGS3 flags to public flags. 2867 */ 2868 static final int SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT = 8; 2869 2870 /** @hide */ 2871 @Retention(RetentionPolicy.SOURCE) 2872 @IntDef(flag = true, 2873 value = { 2874 SCROLL_INDICATOR_TOP, 2875 SCROLL_INDICATOR_BOTTOM, 2876 SCROLL_INDICATOR_LEFT, 2877 SCROLL_INDICATOR_RIGHT, 2878 SCROLL_INDICATOR_START, 2879 SCROLL_INDICATOR_END, 2880 }) 2881 public @interface ScrollIndicators {} 2882 2883 /** 2884 * Scroll indicator direction for the top edge of the view. 2885 * 2886 * @see #setScrollIndicators(int) 2887 * @see #setScrollIndicators(int, int) 2888 * @see #getScrollIndicators() 2889 */ 2890 public static final int SCROLL_INDICATOR_TOP = 2891 PFLAG3_SCROLL_INDICATOR_TOP >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2892 2893 /** 2894 * Scroll indicator direction for the bottom edge of the view. 2895 * 2896 * @see #setScrollIndicators(int) 2897 * @see #setScrollIndicators(int, int) 2898 * @see #getScrollIndicators() 2899 */ 2900 public static final int SCROLL_INDICATOR_BOTTOM = 2901 PFLAG3_SCROLL_INDICATOR_BOTTOM >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2902 2903 /** 2904 * Scroll indicator direction for the left edge of the view. 2905 * 2906 * @see #setScrollIndicators(int) 2907 * @see #setScrollIndicators(int, int) 2908 * @see #getScrollIndicators() 2909 */ 2910 public static final int SCROLL_INDICATOR_LEFT = 2911 PFLAG3_SCROLL_INDICATOR_LEFT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2912 2913 /** 2914 * Scroll indicator direction for the right edge of the view. 2915 * 2916 * @see #setScrollIndicators(int) 2917 * @see #setScrollIndicators(int, int) 2918 * @see #getScrollIndicators() 2919 */ 2920 public static final int SCROLL_INDICATOR_RIGHT = 2921 PFLAG3_SCROLL_INDICATOR_RIGHT >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2922 2923 /** 2924 * Scroll indicator direction for the starting edge of the view. 2925 * <p> 2926 * Resolved according to the view's layout direction, see 2927 * {@link #getLayoutDirection()} for more information. 2928 * 2929 * @see #setScrollIndicators(int) 2930 * @see #setScrollIndicators(int, int) 2931 * @see #getScrollIndicators() 2932 */ 2933 public static final int SCROLL_INDICATOR_START = 2934 PFLAG3_SCROLL_INDICATOR_START >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2935 2936 /** 2937 * Scroll indicator direction for the ending edge of the view. 2938 * <p> 2939 * Resolved according to the view's layout direction, see 2940 * {@link #getLayoutDirection()} for more information. 2941 * 2942 * @see #setScrollIndicators(int) 2943 * @see #setScrollIndicators(int, int) 2944 * @see #getScrollIndicators() 2945 */ 2946 public static final int SCROLL_INDICATOR_END = 2947 PFLAG3_SCROLL_INDICATOR_END >> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 2948 2949 /** 2950 * <p>Indicates that we are allowing {@link ViewStructure} to traverse 2951 * into this view.<p> 2952 */ 2953 static final int PFLAG3_ASSIST_BLOCKED = 0x4000; 2954 2955 /** 2956 * Flag indicating that the view is a root of a keyboard navigation cluster. 2957 * 2958 * @see #isKeyboardNavigationCluster() 2959 * @see #setKeyboardNavigationCluster(boolean) 2960 */ 2961 private static final int PFLAG3_CLUSTER = 0x8000; 2962 2963 /** 2964 * Indicates that the user is currently touching the screen. 2965 * Currently used for the tooltip positioning only. 2966 */ 2967 private static final int PFLAG3_FINGER_DOWN = 0x20000; 2968 2969 /** 2970 * Flag indicating that this view is the default-focus view. 2971 * 2972 * @see #isFocusedByDefault() 2973 * @see #setFocusedByDefault(boolean) 2974 */ 2975 private static final int PFLAG3_FOCUSED_BY_DEFAULT = 0x40000; 2976 2977 /** 2978 * Shift for the place where the autofill mode is stored in the pflags 2979 * 2980 * @see #getAutofillMode() 2981 * @see #setAutofillMode(int) 2982 */ 2983 private static final int PFLAG3_AUTOFILL_MODE_SHIFT = 19; 2984 2985 /** 2986 * Mask for autofill modes 2987 * 2988 * @see #getAutofillMode() 2989 * @see #setAutofillMode(int) 2990 */ 2991 private static final int PFLAG3_AUTOFILL_MODE_MASK = (AUTOFILL_MODE_INHERIT 2992 | AUTOFILL_MODE_AUTO | AUTOFILL_MODE_MANUAL) << PFLAG3_AUTOFILL_MODE_SHIFT; 2993 2994 /** 2995 * Shift for the bits in {@link #mPrivateFlags3} related to the 2996 * "importantForAutofill" attribute. 2997 */ 2998 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT = 21; 2999 3000 /** 3001 * Mask for obtaining the bits which specify how to determine 3002 * whether a view is important for autofill. 3003 */ 3004 static final int PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK = (IMPORTANT_FOR_AUTOFILL_AUTO 3005 | IMPORTANT_FOR_AUTOFILL_YES | IMPORTANT_FOR_AUTOFILL_NO) 3006 << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT; 3007 3008 /** 3009 * Whether this view has rendered elements that overlap (see {@link 3010 * #hasOverlappingRendering()}, {@link #forceHasOverlappingRendering(boolean)}, and 3011 * {@link #getHasOverlappingRendering()} ). The value in this bit is only valid when 3012 * PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED has been set. Otherwise, the value is 3013 * determined by whatever {@link #hasOverlappingRendering()} returns. 3014 */ 3015 private static final int PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE = 0x800000; 3016 3017 /** 3018 * Whether {@link #forceHasOverlappingRendering(boolean)} has been called. When true, value 3019 * in PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE is valid. 3020 */ 3021 private static final int PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED = 0x1000000; 3022 3023 /** 3024 * Flag indicating that the view is temporarily detached from the parent view. 3025 * 3026 * @see #onStartTemporaryDetach() 3027 * @see #onFinishTemporaryDetach() 3028 */ 3029 static final int PFLAG3_TEMPORARY_DETACH = 0x2000000; 3030 3031 /** 3032 * Flag indicating that the view does not wish to be revealed within its parent 3033 * hierarchy when it gains focus. Expressed in the negative since the historical 3034 * default behavior is to reveal on focus; this flag suppresses that behavior. 3035 * 3036 * @see #setRevealOnFocusHint(boolean) 3037 * @see #getRevealOnFocusHint() 3038 */ 3039 private static final int PFLAG3_NO_REVEAL_ON_FOCUS = 0x4000000; 3040 3041 /* End of masks for mPrivateFlags3 */ 3042 3043 /** 3044 * Always allow a user to over-scroll this view, provided it is a 3045 * view that can scroll. 3046 * 3047 * @see #getOverScrollMode() 3048 * @see #setOverScrollMode(int) 3049 */ 3050 public static final int OVER_SCROLL_ALWAYS = 0; 3051 3052 /** 3053 * Allow a user to over-scroll this view only if the content is large 3054 * enough to meaningfully scroll, provided it is a view that can scroll. 3055 * 3056 * @see #getOverScrollMode() 3057 * @see #setOverScrollMode(int) 3058 */ 3059 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 3060 3061 /** 3062 * Never allow a user to over-scroll this view. 3063 * 3064 * @see #getOverScrollMode() 3065 * @see #setOverScrollMode(int) 3066 */ 3067 public static final int OVER_SCROLL_NEVER = 2; 3068 3069 /** 3070 * Special constant for {@link #setSystemUiVisibility(int)}: View has 3071 * requested the system UI (status bar) to be visible (the default). 3072 * 3073 * @see #setSystemUiVisibility(int) 3074 */ 3075 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 3076 3077 /** 3078 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 3079 * system UI to enter an unobtrusive "low profile" mode. 3080 * 3081 * <p>This is for use in games, book readers, video players, or any other 3082 * "immersive" application where the usual system chrome is deemed too distracting. 3083 * 3084 * <p>In low profile mode, the status bar and/or navigation icons may dim. 3085 * 3086 * @see #setSystemUiVisibility(int) 3087 */ 3088 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 3089 3090 /** 3091 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 3092 * system navigation be temporarily hidden. 3093 * 3094 * <p>This is an even less obtrusive state than that called for by 3095 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 3096 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 3097 * those to disappear. This is useful (in conjunction with the 3098 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 3099 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 3100 * window flags) for displaying content using every last pixel on the display. 3101 * 3102 * <p>There is a limitation: because navigation controls are so important, the least user 3103 * interaction will cause them to reappear immediately. When this happens, both 3104 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 3105 * so that both elements reappear at the same time. 3106 * 3107 * @see #setSystemUiVisibility(int) 3108 */ 3109 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 3110 3111 /** 3112 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 3113 * into the normal fullscreen mode so that its content can take over the screen 3114 * while still allowing the user to interact with the application. 3115 * 3116 * <p>This has the same visual effect as 3117 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 3118 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 3119 * meaning that non-critical screen decorations (such as the status bar) will be 3120 * hidden while the user is in the View's window, focusing the experience on 3121 * that content. Unlike the window flag, if you are using ActionBar in 3122 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 3123 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 3124 * hide the action bar. 3125 * 3126 * <p>This approach to going fullscreen is best used over the window flag when 3127 * it is a transient state -- that is, the application does this at certain 3128 * points in its user interaction where it wants to allow the user to focus 3129 * on content, but not as a continuous state. For situations where the application 3130 * would like to simply stay full screen the entire time (such as a game that 3131 * wants to take over the screen), the 3132 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 3133 * is usually a better approach. The state set here will be removed by the system 3134 * in various situations (such as the user moving to another application) like 3135 * the other system UI states. 3136 * 3137 * <p>When using this flag, the application should provide some easy facility 3138 * for the user to go out of it. A common example would be in an e-book 3139 * reader, where tapping on the screen brings back whatever screen and UI 3140 * decorations that had been hidden while the user was immersed in reading 3141 * the book. 3142 * 3143 * @see #setSystemUiVisibility(int) 3144 */ 3145 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 3146 3147 /** 3148 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 3149 * flags, we would like a stable view of the content insets given to 3150 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 3151 * will always represent the worst case that the application can expect 3152 * as a continuous state. In the stock Android UI this is the space for 3153 * the system bar, nav bar, and status bar, but not more transient elements 3154 * such as an input method. 3155 * 3156 * The stable layout your UI sees is based on the system UI modes you can 3157 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 3158 * then you will get a stable layout for changes of the 3159 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 3160 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 3161 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 3162 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 3163 * with a stable layout. (Note that you should avoid using 3164 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 3165 * 3166 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 3167 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 3168 * then a hidden status bar will be considered a "stable" state for purposes 3169 * here. This allows your UI to continually hide the status bar, while still 3170 * using the system UI flags to hide the action bar while still retaining 3171 * a stable layout. Note that changing the window fullscreen flag will never 3172 * provide a stable layout for a clean transition. 3173 * 3174 * <p>If you are using ActionBar in 3175 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 3176 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 3177 * insets it adds to those given to the application. 3178 */ 3179 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 3180 3181 /** 3182 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 3183 * to be laid out as if it has requested 3184 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 3185 * allows it to avoid artifacts when switching in and out of that mode, at 3186 * the expense that some of its user interface may be covered by screen 3187 * decorations when they are shown. You can perform layout of your inner 3188 * UI elements to account for the navigation system UI through the 3189 * {@link #fitSystemWindows(Rect)} method. 3190 */ 3191 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 3192 3193 /** 3194 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 3195 * to be laid out as if it has requested 3196 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 3197 * allows it to avoid artifacts when switching in and out of that mode, at 3198 * the expense that some of its user interface may be covered by screen 3199 * decorations when they are shown. You can perform layout of your inner 3200 * UI elements to account for non-fullscreen system UI through the 3201 * {@link #fitSystemWindows(Rect)} method. 3202 */ 3203 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 3204 3205 /** 3206 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 3207 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 3208 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 3209 * user interaction. 3210 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 3211 * has an effect when used in combination with that flag.</p> 3212 */ 3213 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 3214 3215 /** 3216 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 3217 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 3218 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 3219 * experience while also hiding the system bars. If this flag is not set, 3220 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 3221 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 3222 * if the user swipes from the top of the screen. 3223 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 3224 * system gestures, such as swiping from the top of the screen. These transient system bars 3225 * will overlay app’s content, may have some degree of transparency, and will automatically 3226 * hide after a short timeout. 3227 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 3228 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 3229 * with one or both of those flags.</p> 3230 */ 3231 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 3232 3233 /** 3234 * Flag for {@link #setSystemUiVisibility(int)}: Requests the status bar to draw in a mode that 3235 * is compatible with light status bar backgrounds. 3236 * 3237 * <p>For this to take effect, the window must request 3238 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 3239 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 3240 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS 3241 * FLAG_TRANSLUCENT_STATUS}. 3242 * 3243 * @see android.R.attr#windowLightStatusBar 3244 */ 3245 public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000; 3246 3247 /** 3248 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 3249 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 3250 */ 3251 private static final int SYSTEM_UI_RESERVED_LEGACY1 = 0x00004000; 3252 3253 /** 3254 * This flag was previously used for a private API. DO NOT reuse it for a public API as it might 3255 * trigger undefined behavior on older platforms with apps compiled against a new SDK. 3256 */ 3257 private static final int SYSTEM_UI_RESERVED_LEGACY2 = 0x00010000; 3258 3259 /** 3260 * Flag for {@link #setSystemUiVisibility(int)}: Requests the navigation bar to draw in a mode 3261 * that is compatible with light navigation bar backgrounds. 3262 * 3263 * <p>For this to take effect, the window must request 3264 * {@link android.view.WindowManager.LayoutParams#FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 3265 * FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS} but not 3266 * {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_NAVIGATION 3267 * FLAG_TRANSLUCENT_NAVIGATION}. 3268 */ 3269 public static final int SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR = 0x00000010; 3270 3271 /** 3272 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 3273 */ 3274 @Deprecated 3275 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 3276 3277 /** 3278 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 3279 */ 3280 @Deprecated 3281 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 3282 3283 /** 3284 * @hide 3285 * 3286 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3287 * out of the public fields to keep the undefined bits out of the developer's way. 3288 * 3289 * Flag to make the status bar not expandable. Unless you also 3290 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 3291 */ 3292 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 3293 3294 /** 3295 * @hide 3296 * 3297 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3298 * out of the public fields to keep the undefined bits out of the developer's way. 3299 * 3300 * Flag to hide notification icons and scrolling ticker text. 3301 */ 3302 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 3303 3304 /** 3305 * @hide 3306 * 3307 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3308 * out of the public fields to keep the undefined bits out of the developer's way. 3309 * 3310 * Flag to disable incoming notification alerts. This will not block 3311 * icons, but it will block sound, vibrating and other visual or aural notifications. 3312 */ 3313 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 3314 3315 /** 3316 * @hide 3317 * 3318 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3319 * out of the public fields to keep the undefined bits out of the developer's way. 3320 * 3321 * Flag to hide only the scrolling ticker. Note that 3322 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 3323 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 3324 */ 3325 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 3326 3327 /** 3328 * @hide 3329 * 3330 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3331 * out of the public fields to keep the undefined bits out of the developer's way. 3332 * 3333 * Flag to hide the center system info area. 3334 */ 3335 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 3336 3337 /** 3338 * @hide 3339 * 3340 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3341 * out of the public fields to keep the undefined bits out of the developer's way. 3342 * 3343 * Flag to hide only the home button. Don't use this 3344 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3345 */ 3346 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 3347 3348 /** 3349 * @hide 3350 * 3351 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3352 * out of the public fields to keep the undefined bits out of the developer's way. 3353 * 3354 * Flag to hide only the back button. Don't use this 3355 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3356 */ 3357 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 3358 3359 /** 3360 * @hide 3361 * 3362 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3363 * out of the public fields to keep the undefined bits out of the developer's way. 3364 * 3365 * Flag to hide only the clock. You might use this if your activity has 3366 * its own clock making the status bar's clock redundant. 3367 */ 3368 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 3369 3370 /** 3371 * @hide 3372 * 3373 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3374 * out of the public fields to keep the undefined bits out of the developer's way. 3375 * 3376 * Flag to hide only the recent apps button. Don't use this 3377 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3378 */ 3379 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 3380 3381 /** 3382 * @hide 3383 * 3384 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3385 * out of the public fields to keep the undefined bits out of the developer's way. 3386 * 3387 * Flag to disable the global search gesture. Don't use this 3388 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 3389 */ 3390 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 3391 3392 /** 3393 * @hide 3394 * 3395 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3396 * out of the public fields to keep the undefined bits out of the developer's way. 3397 * 3398 * Flag to specify that the status bar is displayed in transient mode. 3399 */ 3400 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 3401 3402 /** 3403 * @hide 3404 * 3405 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3406 * out of the public fields to keep the undefined bits out of the developer's way. 3407 * 3408 * Flag to specify that the navigation bar is displayed in transient mode. 3409 */ 3410 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 3411 3412 /** 3413 * @hide 3414 * 3415 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3416 * out of the public fields to keep the undefined bits out of the developer's way. 3417 * 3418 * Flag to specify that the hidden status bar would like to be shown. 3419 */ 3420 public static final int STATUS_BAR_UNHIDE = 0x10000000; 3421 3422 /** 3423 * @hide 3424 * 3425 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3426 * out of the public fields to keep the undefined bits out of the developer's way. 3427 * 3428 * Flag to specify that the hidden navigation bar would like to be shown. 3429 */ 3430 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 3431 3432 /** 3433 * @hide 3434 * 3435 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3436 * out of the public fields to keep the undefined bits out of the developer's way. 3437 * 3438 * Flag to specify that the status bar is displayed in translucent mode. 3439 */ 3440 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 3441 3442 /** 3443 * @hide 3444 * 3445 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 3446 * out of the public fields to keep the undefined bits out of the developer's way. 3447 * 3448 * Flag to specify that the navigation bar is displayed in translucent mode. 3449 */ 3450 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 3451 3452 /** 3453 * @hide 3454 * 3455 * Makes navigation bar transparent (but not the status bar). 3456 */ 3457 public static final int NAVIGATION_BAR_TRANSPARENT = 0x00008000; 3458 3459 /** 3460 * @hide 3461 * 3462 * Makes status bar transparent (but not the navigation bar). 3463 */ 3464 public static final int STATUS_BAR_TRANSPARENT = 0x00000008; 3465 3466 /** 3467 * @hide 3468 * 3469 * Makes both status bar and navigation bar transparent. 3470 */ 3471 public static final int SYSTEM_UI_TRANSPARENT = NAVIGATION_BAR_TRANSPARENT 3472 | STATUS_BAR_TRANSPARENT; 3473 3474 /** 3475 * @hide 3476 */ 3477 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FF7; 3478 3479 /** 3480 * These are the system UI flags that can be cleared by events outside 3481 * of an application. Currently this is just the ability to tap on the 3482 * screen while hiding the navigation bar to have it return. 3483 * @hide 3484 */ 3485 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 3486 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 3487 | SYSTEM_UI_FLAG_FULLSCREEN; 3488 3489 /** 3490 * Flags that can impact the layout in relation to system UI. 3491 */ 3492 public static final int SYSTEM_UI_LAYOUT_FLAGS = 3493 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 3494 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 3495 3496 /** @hide */ 3497 @IntDef(flag = true, 3498 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 3499 @Retention(RetentionPolicy.SOURCE) 3500 public @interface FindViewFlags {} 3501 3502 /** 3503 * Find views that render the specified text. 3504 * 3505 * @see #findViewsWithText(ArrayList, CharSequence, int) 3506 */ 3507 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 3508 3509 /** 3510 * Find find views that contain the specified content description. 3511 * 3512 * @see #findViewsWithText(ArrayList, CharSequence, int) 3513 */ 3514 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 3515 3516 /** 3517 * Find views that contain {@link AccessibilityNodeProvider}. Such 3518 * a View is a root of virtual view hierarchy and may contain the searched 3519 * text. If this flag is set Views with providers are automatically 3520 * added and it is a responsibility of the client to call the APIs of 3521 * the provider to determine whether the virtual tree rooted at this View 3522 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 3523 * representing the virtual views with this text. 3524 * 3525 * @see #findViewsWithText(ArrayList, CharSequence, int) 3526 * 3527 * @hide 3528 */ 3529 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 3530 3531 /** 3532 * The undefined cursor position. 3533 * 3534 * @hide 3535 */ 3536 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 3537 3538 /** 3539 * Indicates that the screen has changed state and is now off. 3540 * 3541 * @see #onScreenStateChanged(int) 3542 */ 3543 public static final int SCREEN_STATE_OFF = 0x0; 3544 3545 /** 3546 * Indicates that the screen has changed state and is now on. 3547 * 3548 * @see #onScreenStateChanged(int) 3549 */ 3550 public static final int SCREEN_STATE_ON = 0x1; 3551 3552 /** 3553 * Indicates no axis of view scrolling. 3554 */ 3555 public static final int SCROLL_AXIS_NONE = 0; 3556 3557 /** 3558 * Indicates scrolling along the horizontal axis. 3559 */ 3560 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 3561 3562 /** 3563 * Indicates scrolling along the vertical axis. 3564 */ 3565 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 3566 3567 /** 3568 * Controls the over-scroll mode for this view. 3569 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 3570 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 3571 * and {@link #OVER_SCROLL_NEVER}. 3572 */ 3573 private int mOverScrollMode; 3574 3575 /** 3576 * The parent this view is attached to. 3577 * {@hide} 3578 * 3579 * @see #getParent() 3580 */ 3581 protected ViewParent mParent; 3582 3583 /** 3584 * {@hide} 3585 */ 3586 AttachInfo mAttachInfo; 3587 3588 /** 3589 * {@hide} 3590 */ 3591 @ViewDebug.ExportedProperty(flagMapping = { 3592 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 3593 name = "FORCE_LAYOUT"), 3594 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 3595 name = "LAYOUT_REQUIRED"), 3596 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 3597 name = "DRAWING_CACHE_INVALID", outputIf = false), 3598 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 3599 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 3600 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 3601 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 3602 }, formatToHexString = true) 3603 3604 /* @hide */ 3605 public int mPrivateFlags; 3606 int mPrivateFlags2; 3607 int mPrivateFlags3; 3608 3609 /** 3610 * This view's request for the visibility of the status bar. 3611 * @hide 3612 */ 3613 @ViewDebug.ExportedProperty(flagMapping = { 3614 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 3615 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 3616 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 3617 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3618 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 3619 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 3620 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 3621 equals = SYSTEM_UI_FLAG_VISIBLE, 3622 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 3623 }, formatToHexString = true) 3624 int mSystemUiVisibility; 3625 3626 /** 3627 * Reference count for transient state. 3628 * @see #setHasTransientState(boolean) 3629 */ 3630 int mTransientStateCount = 0; 3631 3632 /** 3633 * Count of how many windows this view has been attached to. 3634 */ 3635 int mWindowAttachCount; 3636 3637 /** 3638 * The layout parameters associated with this view and used by the parent 3639 * {@link android.view.ViewGroup} to determine how this view should be 3640 * laid out. 3641 * {@hide} 3642 */ 3643 protected ViewGroup.LayoutParams mLayoutParams; 3644 3645 /** 3646 * The view flags hold various views states. 3647 * {@hide} 3648 */ 3649 @ViewDebug.ExportedProperty(formatToHexString = true) 3650 int mViewFlags; 3651 3652 static class TransformationInfo { 3653 /** 3654 * The transform matrix for the View. This transform is calculated internally 3655 * based on the translation, rotation, and scale properties. 3656 * 3657 * Do *not* use this variable directly; instead call getMatrix(), which will 3658 * load the value from the View's RenderNode. 3659 */ 3660 private final Matrix mMatrix = new Matrix(); 3661 3662 /** 3663 * The inverse transform matrix for the View. This transform is calculated 3664 * internally based on the translation, rotation, and scale properties. 3665 * 3666 * Do *not* use this variable directly; instead call getInverseMatrix(), 3667 * which will load the value from the View's RenderNode. 3668 */ 3669 private Matrix mInverseMatrix; 3670 3671 /** 3672 * The opacity of the View. This is a value from 0 to 1, where 0 means 3673 * completely transparent and 1 means completely opaque. 3674 */ 3675 @ViewDebug.ExportedProperty 3676 float mAlpha = 1f; 3677 3678 /** 3679 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3680 * property only used by transitions, which is composited with the other alpha 3681 * values to calculate the final visual alpha value. 3682 */ 3683 float mTransitionAlpha = 1f; 3684 } 3685 3686 /** @hide */ 3687 public TransformationInfo mTransformationInfo; 3688 3689 /** 3690 * Current clip bounds. to which all drawing of this view are constrained. 3691 */ 3692 Rect mClipBounds = null; 3693 3694 private boolean mLastIsOpaque; 3695 3696 /** 3697 * The distance in pixels from the left edge of this view's parent 3698 * to the left edge of this view. 3699 * {@hide} 3700 */ 3701 @ViewDebug.ExportedProperty(category = "layout") 3702 protected int mLeft; 3703 /** 3704 * The distance in pixels from the left edge of this view's parent 3705 * to the right edge of this view. 3706 * {@hide} 3707 */ 3708 @ViewDebug.ExportedProperty(category = "layout") 3709 protected int mRight; 3710 /** 3711 * The distance in pixels from the top edge of this view's parent 3712 * to the top edge of this view. 3713 * {@hide} 3714 */ 3715 @ViewDebug.ExportedProperty(category = "layout") 3716 protected int mTop; 3717 /** 3718 * The distance in pixels from the top edge of this view's parent 3719 * to the bottom edge of this view. 3720 * {@hide} 3721 */ 3722 @ViewDebug.ExportedProperty(category = "layout") 3723 protected int mBottom; 3724 3725 /** 3726 * The offset, in pixels, by which the content of this view is scrolled 3727 * horizontally. 3728 * {@hide} 3729 */ 3730 @ViewDebug.ExportedProperty(category = "scrolling") 3731 protected int mScrollX; 3732 /** 3733 * The offset, in pixels, by which the content of this view is scrolled 3734 * vertically. 3735 * {@hide} 3736 */ 3737 @ViewDebug.ExportedProperty(category = "scrolling") 3738 protected int mScrollY; 3739 3740 /** 3741 * The left padding in pixels, that is the distance in pixels between the 3742 * left edge of this view and the left edge of its content. 3743 * {@hide} 3744 */ 3745 @ViewDebug.ExportedProperty(category = "padding") 3746 protected int mPaddingLeft = 0; 3747 /** 3748 * The right padding in pixels, that is the distance in pixels between the 3749 * right edge of this view and the right edge of its content. 3750 * {@hide} 3751 */ 3752 @ViewDebug.ExportedProperty(category = "padding") 3753 protected int mPaddingRight = 0; 3754 /** 3755 * The top padding in pixels, that is the distance in pixels between the 3756 * top edge of this view and the top edge of its content. 3757 * {@hide} 3758 */ 3759 @ViewDebug.ExportedProperty(category = "padding") 3760 protected int mPaddingTop; 3761 /** 3762 * The bottom padding in pixels, that is the distance in pixels between the 3763 * bottom edge of this view and the bottom edge of its content. 3764 * {@hide} 3765 */ 3766 @ViewDebug.ExportedProperty(category = "padding") 3767 protected int mPaddingBottom; 3768 3769 /** 3770 * The layout insets in pixels, that is the distance in pixels between the 3771 * visible edges of this view its bounds. 3772 */ 3773 private Insets mLayoutInsets; 3774 3775 /** 3776 * Briefly describes the view and is primarily used for accessibility support. 3777 */ 3778 private CharSequence mContentDescription; 3779 3780 /** 3781 * Specifies the id of a view for which this view serves as a label for 3782 * accessibility purposes. 3783 */ 3784 private int mLabelForId = View.NO_ID; 3785 3786 /** 3787 * Predicate for matching labeled view id with its label for 3788 * accessibility purposes. 3789 */ 3790 private MatchLabelForPredicate mMatchLabelForPredicate; 3791 3792 /** 3793 * Specifies a view before which this one is visited in accessibility traversal. 3794 */ 3795 private int mAccessibilityTraversalBeforeId = NO_ID; 3796 3797 /** 3798 * Specifies a view after which this one is visited in accessibility traversal. 3799 */ 3800 private int mAccessibilityTraversalAfterId = NO_ID; 3801 3802 /** 3803 * Predicate for matching a view by its id. 3804 */ 3805 private MatchIdPredicate mMatchIdPredicate; 3806 3807 /** 3808 * Cache the paddingRight set by the user to append to the scrollbar's size. 3809 * 3810 * @hide 3811 */ 3812 @ViewDebug.ExportedProperty(category = "padding") 3813 protected int mUserPaddingRight; 3814 3815 /** 3816 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3817 * 3818 * @hide 3819 */ 3820 @ViewDebug.ExportedProperty(category = "padding") 3821 protected int mUserPaddingBottom; 3822 3823 /** 3824 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3825 * 3826 * @hide 3827 */ 3828 @ViewDebug.ExportedProperty(category = "padding") 3829 protected int mUserPaddingLeft; 3830 3831 /** 3832 * Cache the paddingStart set by the user to append to the scrollbar's size. 3833 * 3834 */ 3835 @ViewDebug.ExportedProperty(category = "padding") 3836 int mUserPaddingStart; 3837 3838 /** 3839 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3840 * 3841 */ 3842 @ViewDebug.ExportedProperty(category = "padding") 3843 int mUserPaddingEnd; 3844 3845 /** 3846 * Cache initial left padding. 3847 * 3848 * @hide 3849 */ 3850 int mUserPaddingLeftInitial; 3851 3852 /** 3853 * Cache initial right padding. 3854 * 3855 * @hide 3856 */ 3857 int mUserPaddingRightInitial; 3858 3859 /** 3860 * Default undefined padding 3861 */ 3862 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3863 3864 /** 3865 * Cache if a left padding has been defined 3866 */ 3867 private boolean mLeftPaddingDefined = false; 3868 3869 /** 3870 * Cache if a right padding has been defined 3871 */ 3872 private boolean mRightPaddingDefined = false; 3873 3874 /** 3875 * @hide 3876 */ 3877 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3878 /** 3879 * @hide 3880 */ 3881 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3882 3883 private LongSparseLongArray mMeasureCache; 3884 3885 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3886 private Drawable mBackground; 3887 private TintInfo mBackgroundTint; 3888 3889 @ViewDebug.ExportedProperty(deepExport = true, prefix = "fg_") 3890 private ForegroundInfo mForegroundInfo; 3891 3892 private Drawable mScrollIndicatorDrawable; 3893 3894 /** 3895 * RenderNode used for backgrounds. 3896 * <p> 3897 * When non-null and valid, this is expected to contain an up-to-date copy 3898 * of the background drawable. It is cleared on temporary detach, and reset 3899 * on cleanup. 3900 */ 3901 private RenderNode mBackgroundRenderNode; 3902 3903 private int mBackgroundResource; 3904 private boolean mBackgroundSizeChanged; 3905 3906 /** The default focus highlight. 3907 * @see #mDefaultFocusHighlightEnabled 3908 * @see Drawable#hasFocusStateSpecified() 3909 */ 3910 private Drawable mDefaultFocusHighlight; 3911 private Drawable mDefaultFocusHighlightCache; 3912 private boolean mDefaultFocusHighlightSizeChanged; 3913 3914 private String mTransitionName; 3915 3916 static class TintInfo { 3917 ColorStateList mTintList; 3918 PorterDuff.Mode mTintMode; 3919 boolean mHasTintMode; 3920 boolean mHasTintList; 3921 } 3922 3923 private static class ForegroundInfo { 3924 private Drawable mDrawable; 3925 private TintInfo mTintInfo; 3926 private int mGravity = Gravity.FILL; 3927 private boolean mInsidePadding = true; 3928 private boolean mBoundsChanged = true; 3929 private final Rect mSelfBounds = new Rect(); 3930 private final Rect mOverlayBounds = new Rect(); 3931 } 3932 3933 static class ListenerInfo { 3934 /** 3935 * Listener used to dispatch focus change events. 3936 * This field should be made private, so it is hidden from the SDK. 3937 * {@hide} 3938 */ 3939 protected OnFocusChangeListener mOnFocusChangeListener; 3940 3941 /** 3942 * Listeners for layout change events. 3943 */ 3944 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3945 3946 protected OnScrollChangeListener mOnScrollChangeListener; 3947 3948 /** 3949 * Listeners for attach events. 3950 */ 3951 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3952 3953 /** 3954 * Listener used to dispatch click events. 3955 * This field should be made private, so it is hidden from the SDK. 3956 * {@hide} 3957 */ 3958 public OnClickListener mOnClickListener; 3959 3960 /** 3961 * Listener used to dispatch long click events. 3962 * This field should be made private, so it is hidden from the SDK. 3963 * {@hide} 3964 */ 3965 protected OnLongClickListener mOnLongClickListener; 3966 3967 /** 3968 * Listener used to dispatch context click events. This field should be made private, so it 3969 * is hidden from the SDK. 3970 * {@hide} 3971 */ 3972 protected OnContextClickListener mOnContextClickListener; 3973 3974 /** 3975 * Listener used to build the context menu. 3976 * This field should be made private, so it is hidden from the SDK. 3977 * {@hide} 3978 */ 3979 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3980 3981 private OnKeyListener mOnKeyListener; 3982 3983 private OnTouchListener mOnTouchListener; 3984 3985 private OnHoverListener mOnHoverListener; 3986 3987 private OnGenericMotionListener mOnGenericMotionListener; 3988 3989 private OnDragListener mOnDragListener; 3990 3991 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3992 3993 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3994 3995 OnCapturedPointerListener mOnCapturedPointerListener; 3996 } 3997 3998 ListenerInfo mListenerInfo; 3999 4000 private static class TooltipInfo { 4001 /** 4002 * Text to be displayed in a tooltip popup. 4003 */ 4004 @Nullable 4005 CharSequence mTooltipText; 4006 4007 /** 4008 * View-relative position of the tooltip anchor point. 4009 */ 4010 int mAnchorX; 4011 int mAnchorY; 4012 4013 /** 4014 * The tooltip popup. 4015 */ 4016 @Nullable 4017 TooltipPopup mTooltipPopup; 4018 4019 /** 4020 * Set to true if the tooltip was shown as a result of a long click. 4021 */ 4022 boolean mTooltipFromLongClick; 4023 4024 /** 4025 * Keep these Runnables so that they can be used to reschedule. 4026 */ 4027 Runnable mShowTooltipRunnable; 4028 Runnable mHideTooltipRunnable; 4029 } 4030 4031 TooltipInfo mTooltipInfo; 4032 4033 // Temporary values used to hold (x,y) coordinates when delegating from the 4034 // two-arg performLongClick() method to the legacy no-arg version. 4035 private float mLongClickX = Float.NaN; 4036 private float mLongClickY = Float.NaN; 4037 4038 /** 4039 * The application environment this view lives in. 4040 * This field should be made private, so it is hidden from the SDK. 4041 * {@hide} 4042 */ 4043 @ViewDebug.ExportedProperty(deepExport = true) 4044 protected Context mContext; 4045 4046 private final Resources mResources; 4047 4048 private ScrollabilityCache mScrollCache; 4049 4050 private int[] mDrawableState = null; 4051 4052 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 4053 4054 /** 4055 * Animator that automatically runs based on state changes. 4056 */ 4057 private StateListAnimator mStateListAnimator; 4058 4059 /** 4060 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 4061 * the user may specify which view to go to next. 4062 */ 4063 private int mNextFocusLeftId = View.NO_ID; 4064 4065 /** 4066 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 4067 * the user may specify which view to go to next. 4068 */ 4069 private int mNextFocusRightId = View.NO_ID; 4070 4071 /** 4072 * When this view has focus and the next focus is {@link #FOCUS_UP}, 4073 * the user may specify which view to go to next. 4074 */ 4075 private int mNextFocusUpId = View.NO_ID; 4076 4077 /** 4078 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 4079 * the user may specify which view to go to next. 4080 */ 4081 private int mNextFocusDownId = View.NO_ID; 4082 4083 /** 4084 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 4085 * the user may specify which view to go to next. 4086 */ 4087 int mNextFocusForwardId = View.NO_ID; 4088 4089 /** 4090 * User-specified next keyboard navigation cluster in the {@link #FOCUS_FORWARD} direction. 4091 * 4092 * @see #findUserSetNextKeyboardNavigationCluster(View, int) 4093 */ 4094 int mNextClusterForwardId = View.NO_ID; 4095 4096 /** 4097 * Whether this View should use a default focus highlight when it gets focused but doesn't 4098 * have {@link android.R.attr#state_focused} defined in its background. 4099 */ 4100 boolean mDefaultFocusHighlightEnabled = true; 4101 4102 private CheckForLongPress mPendingCheckForLongPress; 4103 private CheckForTap mPendingCheckForTap = null; 4104 private PerformClick mPerformClick; 4105 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 4106 4107 private UnsetPressedState mUnsetPressedState; 4108 4109 /** 4110 * Whether the long press's action has been invoked. The tap's action is invoked on the 4111 * up event while a long press is invoked as soon as the long press duration is reached, so 4112 * a long press could be performed before the tap is checked, in which case the tap's action 4113 * should not be invoked. 4114 */ 4115 private boolean mHasPerformedLongPress; 4116 4117 /** 4118 * Whether a context click button is currently pressed down. This is true when the stylus is 4119 * touching the screen and the primary button has been pressed, or if a mouse's right button is 4120 * pressed. This is false once the button is released or if the stylus has been lifted. 4121 */ 4122 private boolean mInContextButtonPress; 4123 4124 /** 4125 * Whether the next up event should be ignored for the purposes of gesture recognition. This is 4126 * true after a stylus button press has occured, when the next up event should not be recognized 4127 * as a tap. 4128 */ 4129 private boolean mIgnoreNextUpEvent; 4130 4131 /** 4132 * The minimum height of the view. We'll try our best to have the height 4133 * of this view to at least this amount. 4134 */ 4135 @ViewDebug.ExportedProperty(category = "measurement") 4136 private int mMinHeight; 4137 4138 /** 4139 * The minimum width of the view. We'll try our best to have the width 4140 * of this view to at least this amount. 4141 */ 4142 @ViewDebug.ExportedProperty(category = "measurement") 4143 private int mMinWidth; 4144 4145 /** 4146 * The delegate to handle touch events that are physically in this view 4147 * but should be handled by another view. 4148 */ 4149 private TouchDelegate mTouchDelegate = null; 4150 4151 /** 4152 * Solid color to use as a background when creating the drawing cache. Enables 4153 * the cache to use 16 bit bitmaps instead of 32 bit. 4154 */ 4155 private int mDrawingCacheBackgroundColor = 0; 4156 4157 /** 4158 * Special tree observer used when mAttachInfo is null. 4159 */ 4160 private ViewTreeObserver mFloatingTreeObserver; 4161 4162 /** 4163 * Cache the touch slop from the context that created the view. 4164 */ 4165 private int mTouchSlop; 4166 4167 /** 4168 * Object that handles automatic animation of view properties. 4169 */ 4170 private ViewPropertyAnimator mAnimator = null; 4171 4172 /** 4173 * List of registered FrameMetricsObservers. 4174 */ 4175 private ArrayList<FrameMetricsObserver> mFrameMetricsObservers; 4176 4177 /** 4178 * Flag indicating that a drag can cross window boundaries. When 4179 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 4180 * with this flag set, all visible applications with targetSdkVersion >= 4181 * {@link android.os.Build.VERSION_CODES#N API 24} will be able to participate 4182 * in the drag operation and receive the dragged content. 4183 * 4184 * <p>If this is the only flag set, then the drag recipient will only have access to text data 4185 * and intents contained in the {@link ClipData} object. Access to URIs contained in the 4186 * {@link ClipData} is determined by other DRAG_FLAG_GLOBAL_* flags</p> 4187 */ 4188 public static final int DRAG_FLAG_GLOBAL = 1 << 8; // 256 4189 4190 /** 4191 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 4192 * request read access to the content URI(s) contained in the {@link ClipData} object. 4193 * @see android.content.Intent#FLAG_GRANT_READ_URI_PERMISSION 4194 */ 4195 public static final int DRAG_FLAG_GLOBAL_URI_READ = Intent.FLAG_GRANT_READ_URI_PERMISSION; 4196 4197 /** 4198 * When this flag is used with {@link #DRAG_FLAG_GLOBAL}, the drag recipient will be able to 4199 * request write access to the content URI(s) contained in the {@link ClipData} object. 4200 * @see android.content.Intent#FLAG_GRANT_WRITE_URI_PERMISSION 4201 */ 4202 public static final int DRAG_FLAG_GLOBAL_URI_WRITE = Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 4203 4204 /** 4205 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 4206 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant can be persisted across device 4207 * reboots until explicitly revoked with 4208 * {@link android.content.Context#revokeUriPermission(Uri, int)} Context.revokeUriPermission}. 4209 * @see android.content.Intent#FLAG_GRANT_PERSISTABLE_URI_PERMISSION 4210 */ 4211 public static final int DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION = 4212 Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION; 4213 4214 /** 4215 * When this flag is used with {@link #DRAG_FLAG_GLOBAL_URI_READ} and/or {@link 4216 * #DRAG_FLAG_GLOBAL_URI_WRITE}, the URI permission grant applies to any URI that is a prefix 4217 * match against the original granted URI. 4218 * @see android.content.Intent#FLAG_GRANT_PREFIX_URI_PERMISSION 4219 */ 4220 public static final int DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION = 4221 Intent.FLAG_GRANT_PREFIX_URI_PERMISSION; 4222 4223 /** 4224 * Flag indicating that the drag shadow will be opaque. When 4225 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int)} is called 4226 * with this flag set, the drag shadow will be opaque, otherwise, it will be semitransparent. 4227 */ 4228 public static final int DRAG_FLAG_OPAQUE = 1 << 9; 4229 4230 /** 4231 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 4232 */ 4233 private float mVerticalScrollFactor; 4234 4235 /** 4236 * Position of the vertical scroll bar. 4237 */ 4238 private int mVerticalScrollbarPosition; 4239 4240 /** 4241 * Position the scroll bar at the default position as determined by the system. 4242 */ 4243 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 4244 4245 /** 4246 * Position the scroll bar along the left edge. 4247 */ 4248 public static final int SCROLLBAR_POSITION_LEFT = 1; 4249 4250 /** 4251 * Position the scroll bar along the right edge. 4252 */ 4253 public static final int SCROLLBAR_POSITION_RIGHT = 2; 4254 4255 /** 4256 * Indicates that the view does not have a layer. 4257 * 4258 * @see #getLayerType() 4259 * @see #setLayerType(int, android.graphics.Paint) 4260 * @see #LAYER_TYPE_SOFTWARE 4261 * @see #LAYER_TYPE_HARDWARE 4262 */ 4263 public static final int LAYER_TYPE_NONE = 0; 4264 4265 /** 4266 * <p>Indicates that the view has a software layer. A software layer is backed 4267 * by a bitmap and causes the view to be rendered using Android's software 4268 * rendering pipeline, even if hardware acceleration is enabled.</p> 4269 * 4270 * <p>Software layers have various usages:</p> 4271 * <p>When the application is not using hardware acceleration, a software layer 4272 * is useful to apply a specific color filter and/or blending mode and/or 4273 * translucency to a view and all its children.</p> 4274 * <p>When the application is using hardware acceleration, a software layer 4275 * is useful to render drawing primitives not supported by the hardware 4276 * accelerated pipeline. It can also be used to cache a complex view tree 4277 * into a texture and reduce the complexity of drawing operations. For instance, 4278 * when animating a complex view tree with a translation, a software layer can 4279 * be used to render the view tree only once.</p> 4280 * <p>Software layers should be avoided when the affected view tree updates 4281 * often. Every update will require to re-render the software layer, which can 4282 * potentially be slow (particularly when hardware acceleration is turned on 4283 * since the layer will have to be uploaded into a hardware texture after every 4284 * update.)</p> 4285 * 4286 * @see #getLayerType() 4287 * @see #setLayerType(int, android.graphics.Paint) 4288 * @see #LAYER_TYPE_NONE 4289 * @see #LAYER_TYPE_HARDWARE 4290 */ 4291 public static final int LAYER_TYPE_SOFTWARE = 1; 4292 4293 /** 4294 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 4295 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 4296 * OpenGL hardware) and causes the view to be rendered using Android's hardware 4297 * rendering pipeline, but only if hardware acceleration is turned on for the 4298 * view hierarchy. When hardware acceleration is turned off, hardware layers 4299 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 4300 * 4301 * <p>A hardware layer is useful to apply a specific color filter and/or 4302 * blending mode and/or translucency to a view and all its children.</p> 4303 * <p>A hardware layer can be used to cache a complex view tree into a 4304 * texture and reduce the complexity of drawing operations. For instance, 4305 * when animating a complex view tree with a translation, a hardware layer can 4306 * be used to render the view tree only once.</p> 4307 * <p>A hardware layer can also be used to increase the rendering quality when 4308 * rotation transformations are applied on a view. It can also be used to 4309 * prevent potential clipping issues when applying 3D transforms on a view.</p> 4310 * 4311 * @see #getLayerType() 4312 * @see #setLayerType(int, android.graphics.Paint) 4313 * @see #LAYER_TYPE_NONE 4314 * @see #LAYER_TYPE_SOFTWARE 4315 */ 4316 public static final int LAYER_TYPE_HARDWARE = 2; 4317 4318 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 4319 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 4320 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 4321 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 4322 }) 4323 int mLayerType = LAYER_TYPE_NONE; 4324 Paint mLayerPaint; 4325 4326 /** 4327 * Set to true when drawing cache is enabled and cannot be created. 4328 * 4329 * @hide 4330 */ 4331 public boolean mCachingFailed; 4332 private Bitmap mDrawingCache; 4333 private Bitmap mUnscaledDrawingCache; 4334 4335 /** 4336 * RenderNode holding View properties, potentially holding a DisplayList of View content. 4337 * <p> 4338 * When non-null and valid, this is expected to contain an up-to-date copy 4339 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 4340 * cleanup. 4341 */ 4342 final RenderNode mRenderNode; 4343 4344 /** 4345 * Set to true when the view is sending hover accessibility events because it 4346 * is the innermost hovered view. 4347 */ 4348 private boolean mSendingHoverAccessibilityEvents; 4349 4350 /** 4351 * Delegate for injecting accessibility functionality. 4352 */ 4353 AccessibilityDelegate mAccessibilityDelegate; 4354 4355 /** 4356 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 4357 * and add/remove objects to/from the overlay directly through the Overlay methods. 4358 */ 4359 ViewOverlay mOverlay; 4360 4361 /** 4362 * The currently active parent view for receiving delegated nested scrolling events. 4363 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 4364 * by {@link #stopNestedScroll()} at the same point where we clear 4365 * requestDisallowInterceptTouchEvent. 4366 */ 4367 private ViewParent mNestedScrollingParent; 4368 4369 /** 4370 * Consistency verifier for debugging purposes. 4371 * @hide 4372 */ 4373 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 4374 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 4375 new InputEventConsistencyVerifier(this, 0) : null; 4376 4377 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 4378 4379 private int[] mTempNestedScrollConsumed; 4380 4381 /** 4382 * An overlay is going to draw this View instead of being drawn as part of this 4383 * View's parent. mGhostView is the View in the Overlay that must be invalidated 4384 * when this view is invalidated. 4385 */ 4386 GhostView mGhostView; 4387 4388 /** 4389 * Holds pairs of adjacent attribute data: attribute name followed by its value. 4390 * @hide 4391 */ 4392 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 4393 public String[] mAttributes; 4394 4395 /** 4396 * Maps a Resource id to its name. 4397 */ 4398 private static SparseArray<String> mAttributeMap; 4399 4400 /** 4401 * Queue of pending runnables. Used to postpone calls to post() until this 4402 * view is attached and has a handler. 4403 */ 4404 private HandlerActionQueue mRunQueue; 4405 4406 /** 4407 * The pointer icon when the mouse hovers on this view. The default is null. 4408 */ 4409 private PointerIcon mPointerIcon; 4410 4411 /** 4412 * @hide 4413 */ 4414 String mStartActivityRequestWho; 4415 4416 @Nullable 4417 private RoundScrollbarRenderer mRoundScrollbarRenderer; 4418 4419 /** 4420 * Simple constructor to use when creating a view from code. 4421 * 4422 * @param context The Context the view is running in, through which it can 4423 * access the current theme, resources, etc. 4424 */ 4425 public View(Context context) { 4426 mContext = context; 4427 mResources = context != null ? context.getResources() : null; 4428 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED | FOCUSABLE_AUTO; 4429 // Set some flags defaults 4430 mPrivateFlags2 = 4431 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 4432 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 4433 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 4434 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 4435 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 4436 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 4437 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 4438 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 4439 mUserPaddingStart = UNDEFINED_PADDING; 4440 mUserPaddingEnd = UNDEFINED_PADDING; 4441 mRenderNode = RenderNode.create(getClass().getName(), this); 4442 4443 if (!sCompatibilityDone && context != null) { 4444 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4445 4446 // Older apps may need this compatibility hack for measurement. 4447 sUseBrokenMakeMeasureSpec = targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN_MR1; 4448 4449 // Older apps expect onMeasure() to always be called on a layout pass, regardless 4450 // of whether a layout was requested on that View. 4451 sIgnoreMeasureCache = targetSdkVersion < Build.VERSION_CODES.KITKAT; 4452 4453 Canvas.sCompatibilityRestore = targetSdkVersion < Build.VERSION_CODES.M; 4454 4455 // In M and newer, our widgets can pass a "hint" value in the size 4456 // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers 4457 // know what the expected parent size is going to be, so e.g. list items can size 4458 // themselves at 1/3 the size of their container. It breaks older apps though, 4459 // specifically apps that use some popular open source libraries. 4460 sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < Build.VERSION_CODES.M; 4461 4462 // Old versions of the platform would give different results from 4463 // LinearLayout measurement passes using EXACTLY and non-EXACTLY 4464 // modes, so we always need to run an additional EXACTLY pass. 4465 sAlwaysRemeasureExactly = targetSdkVersion <= Build.VERSION_CODES.M; 4466 4467 // Prior to N, layout params could change without requiring a 4468 // subsequent call to setLayoutParams() and they would usually 4469 // work. Partial layout breaks this assumption. 4470 sLayoutParamsAlwaysChanged = targetSdkVersion <= Build.VERSION_CODES.M; 4471 4472 // Prior to N, TextureView would silently ignore calls to setBackground/setForeground. 4473 // On N+, we throw, but that breaks compatibility with apps that use these methods. 4474 sTextureViewIgnoresDrawableSetters = targetSdkVersion <= Build.VERSION_CODES.M; 4475 4476 // Prior to N, we would drop margins in LayoutParam conversions. The fix triggers bugs 4477 // in apps so we target check it to avoid breaking existing apps. 4478 sPreserveMarginParamsInLayoutParamConversion = 4479 targetSdkVersion >= Build.VERSION_CODES.N; 4480 4481 sCascadedDragDrop = targetSdkVersion < Build.VERSION_CODES.N; 4482 4483 sHasFocusableExcludeAutoFocusable = targetSdkVersion < Build.VERSION_CODES.O; 4484 4485 sAutoFocusableOffUIThreadWontNotifyParents = targetSdkVersion < Build.VERSION_CODES.O; 4486 4487 sCompatibilityDone = true; 4488 } 4489 } 4490 4491 /** 4492 * Constructor that is called when inflating a view from XML. This is called 4493 * when a view is being constructed from an XML file, supplying attributes 4494 * that were specified in the XML file. This version uses a default style of 4495 * 0, so the only attribute values applied are those in the Context's Theme 4496 * and the given AttributeSet. 4497 * 4498 * <p> 4499 * The method onFinishInflate() will be called after all children have been 4500 * added. 4501 * 4502 * @param context The Context the view is running in, through which it can 4503 * access the current theme, resources, etc. 4504 * @param attrs The attributes of the XML tag that is inflating the view. 4505 * @see #View(Context, AttributeSet, int) 4506 */ 4507 public View(Context context, @Nullable AttributeSet attrs) { 4508 this(context, attrs, 0); 4509 } 4510 4511 /** 4512 * Perform inflation from XML and apply a class-specific base style from a 4513 * theme attribute. This constructor of View allows subclasses to use their 4514 * own base style when they are inflating. For example, a Button class's 4515 * constructor would call this version of the super class constructor and 4516 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 4517 * allows the theme's button style to modify all of the base view attributes 4518 * (in particular its background) as well as the Button class's attributes. 4519 * 4520 * @param context The Context the view is running in, through which it can 4521 * access the current theme, resources, etc. 4522 * @param attrs The attributes of the XML tag that is inflating the view. 4523 * @param defStyleAttr An attribute in the current theme that contains a 4524 * reference to a style resource that supplies default values for 4525 * the view. Can be 0 to not look for defaults. 4526 * @see #View(Context, AttributeSet) 4527 */ 4528 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 4529 this(context, attrs, defStyleAttr, 0); 4530 } 4531 4532 /** 4533 * Perform inflation from XML and apply a class-specific base style from a 4534 * theme attribute or style resource. This constructor of View allows 4535 * subclasses to use their own base style when they are inflating. 4536 * <p> 4537 * When determining the final value of a particular attribute, there are 4538 * four inputs that come into play: 4539 * <ol> 4540 * <li>Any attribute values in the given AttributeSet. 4541 * <li>The style resource specified in the AttributeSet (named "style"). 4542 * <li>The default style specified by <var>defStyleAttr</var>. 4543 * <li>The default style specified by <var>defStyleRes</var>. 4544 * <li>The base values in this theme. 4545 * </ol> 4546 * <p> 4547 * Each of these inputs is considered in-order, with the first listed taking 4548 * precedence over the following ones. In other words, if in the 4549 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 4550 * , then the button's text will <em>always</em> be black, regardless of 4551 * what is specified in any of the styles. 4552 * 4553 * @param context The Context the view is running in, through which it can 4554 * access the current theme, resources, etc. 4555 * @param attrs The attributes of the XML tag that is inflating the view. 4556 * @param defStyleAttr An attribute in the current theme that contains a 4557 * reference to a style resource that supplies default values for 4558 * the view. Can be 0 to not look for defaults. 4559 * @param defStyleRes A resource identifier of a style resource that 4560 * supplies default values for the view, used only if 4561 * defStyleAttr is 0 or can not be found in the theme. Can be 0 4562 * to not look for defaults. 4563 * @see #View(Context, AttributeSet, int) 4564 */ 4565 public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 4566 this(context); 4567 4568 final TypedArray a = context.obtainStyledAttributes( 4569 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 4570 4571 if (mDebugViewAttributes) { 4572 saveAttributeData(attrs, a); 4573 } 4574 4575 Drawable background = null; 4576 4577 int leftPadding = -1; 4578 int topPadding = -1; 4579 int rightPadding = -1; 4580 int bottomPadding = -1; 4581 int startPadding = UNDEFINED_PADDING; 4582 int endPadding = UNDEFINED_PADDING; 4583 4584 int padding = -1; 4585 int paddingHorizontal = -1; 4586 int paddingVertical = -1; 4587 4588 int viewFlagValues = 0; 4589 int viewFlagMasks = 0; 4590 4591 boolean setScrollContainer = false; 4592 4593 int x = 0; 4594 int y = 0; 4595 4596 float tx = 0; 4597 float ty = 0; 4598 float tz = 0; 4599 float elevation = 0; 4600 float rotation = 0; 4601 float rotationX = 0; 4602 float rotationY = 0; 4603 float sx = 1f; 4604 float sy = 1f; 4605 boolean transformSet = false; 4606 4607 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 4608 int overScrollMode = mOverScrollMode; 4609 boolean initializeScrollbars = false; 4610 boolean initializeScrollIndicators = false; 4611 4612 boolean startPaddingDefined = false; 4613 boolean endPaddingDefined = false; 4614 boolean leftPaddingDefined = false; 4615 boolean rightPaddingDefined = false; 4616 4617 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 4618 4619 // Set default values. 4620 viewFlagValues |= FOCUSABLE_AUTO; 4621 viewFlagMasks |= FOCUSABLE_AUTO; 4622 4623 final int N = a.getIndexCount(); 4624 for (int i = 0; i < N; i++) { 4625 int attr = a.getIndex(i); 4626 switch (attr) { 4627 case com.android.internal.R.styleable.View_background: 4628 background = a.getDrawable(attr); 4629 break; 4630 case com.android.internal.R.styleable.View_padding: 4631 padding = a.getDimensionPixelSize(attr, -1); 4632 mUserPaddingLeftInitial = padding; 4633 mUserPaddingRightInitial = padding; 4634 leftPaddingDefined = true; 4635 rightPaddingDefined = true; 4636 break; 4637 case com.android.internal.R.styleable.View_paddingHorizontal: 4638 paddingHorizontal = a.getDimensionPixelSize(attr, -1); 4639 mUserPaddingLeftInitial = paddingHorizontal; 4640 mUserPaddingRightInitial = paddingHorizontal; 4641 leftPaddingDefined = true; 4642 rightPaddingDefined = true; 4643 break; 4644 case com.android.internal.R.styleable.View_paddingVertical: 4645 paddingVertical = a.getDimensionPixelSize(attr, -1); 4646 break; 4647 case com.android.internal.R.styleable.View_paddingLeft: 4648 leftPadding = a.getDimensionPixelSize(attr, -1); 4649 mUserPaddingLeftInitial = leftPadding; 4650 leftPaddingDefined = true; 4651 break; 4652 case com.android.internal.R.styleable.View_paddingTop: 4653 topPadding = a.getDimensionPixelSize(attr, -1); 4654 break; 4655 case com.android.internal.R.styleable.View_paddingRight: 4656 rightPadding = a.getDimensionPixelSize(attr, -1); 4657 mUserPaddingRightInitial = rightPadding; 4658 rightPaddingDefined = true; 4659 break; 4660 case com.android.internal.R.styleable.View_paddingBottom: 4661 bottomPadding = a.getDimensionPixelSize(attr, -1); 4662 break; 4663 case com.android.internal.R.styleable.View_paddingStart: 4664 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4665 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 4666 break; 4667 case com.android.internal.R.styleable.View_paddingEnd: 4668 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 4669 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 4670 break; 4671 case com.android.internal.R.styleable.View_scrollX: 4672 x = a.getDimensionPixelOffset(attr, 0); 4673 break; 4674 case com.android.internal.R.styleable.View_scrollY: 4675 y = a.getDimensionPixelOffset(attr, 0); 4676 break; 4677 case com.android.internal.R.styleable.View_alpha: 4678 setAlpha(a.getFloat(attr, 1f)); 4679 break; 4680 case com.android.internal.R.styleable.View_transformPivotX: 4681 setPivotX(a.getDimension(attr, 0)); 4682 break; 4683 case com.android.internal.R.styleable.View_transformPivotY: 4684 setPivotY(a.getDimension(attr, 0)); 4685 break; 4686 case com.android.internal.R.styleable.View_translationX: 4687 tx = a.getDimension(attr, 0); 4688 transformSet = true; 4689 break; 4690 case com.android.internal.R.styleable.View_translationY: 4691 ty = a.getDimension(attr, 0); 4692 transformSet = true; 4693 break; 4694 case com.android.internal.R.styleable.View_translationZ: 4695 tz = a.getDimension(attr, 0); 4696 transformSet = true; 4697 break; 4698 case com.android.internal.R.styleable.View_elevation: 4699 elevation = a.getDimension(attr, 0); 4700 transformSet = true; 4701 break; 4702 case com.android.internal.R.styleable.View_rotation: 4703 rotation = a.getFloat(attr, 0); 4704 transformSet = true; 4705 break; 4706 case com.android.internal.R.styleable.View_rotationX: 4707 rotationX = a.getFloat(attr, 0); 4708 transformSet = true; 4709 break; 4710 case com.android.internal.R.styleable.View_rotationY: 4711 rotationY = a.getFloat(attr, 0); 4712 transformSet = true; 4713 break; 4714 case com.android.internal.R.styleable.View_scaleX: 4715 sx = a.getFloat(attr, 1f); 4716 transformSet = true; 4717 break; 4718 case com.android.internal.R.styleable.View_scaleY: 4719 sy = a.getFloat(attr, 1f); 4720 transformSet = true; 4721 break; 4722 case com.android.internal.R.styleable.View_id: 4723 mID = a.getResourceId(attr, NO_ID); 4724 break; 4725 case com.android.internal.R.styleable.View_tag: 4726 mTag = a.getText(attr); 4727 break; 4728 case com.android.internal.R.styleable.View_fitsSystemWindows: 4729 if (a.getBoolean(attr, false)) { 4730 viewFlagValues |= FITS_SYSTEM_WINDOWS; 4731 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 4732 } 4733 break; 4734 case com.android.internal.R.styleable.View_focusable: 4735 viewFlagValues = (viewFlagValues & ~FOCUSABLE_MASK) | getFocusableAttribute(a); 4736 if ((viewFlagValues & FOCUSABLE_AUTO) == 0) { 4737 viewFlagMasks |= FOCUSABLE_MASK; 4738 } 4739 break; 4740 case com.android.internal.R.styleable.View_focusableInTouchMode: 4741 if (a.getBoolean(attr, false)) { 4742 // unset auto focus since focusableInTouchMode implies explicit focusable 4743 viewFlagValues &= ~FOCUSABLE_AUTO; 4744 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 4745 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 4746 } 4747 break; 4748 case com.android.internal.R.styleable.View_clickable: 4749 if (a.getBoolean(attr, false)) { 4750 viewFlagValues |= CLICKABLE; 4751 viewFlagMasks |= CLICKABLE; 4752 } 4753 break; 4754 case com.android.internal.R.styleable.View_longClickable: 4755 if (a.getBoolean(attr, false)) { 4756 viewFlagValues |= LONG_CLICKABLE; 4757 viewFlagMasks |= LONG_CLICKABLE; 4758 } 4759 break; 4760 case com.android.internal.R.styleable.View_contextClickable: 4761 if (a.getBoolean(attr, false)) { 4762 viewFlagValues |= CONTEXT_CLICKABLE; 4763 viewFlagMasks |= CONTEXT_CLICKABLE; 4764 } 4765 break; 4766 case com.android.internal.R.styleable.View_saveEnabled: 4767 if (!a.getBoolean(attr, true)) { 4768 viewFlagValues |= SAVE_DISABLED; 4769 viewFlagMasks |= SAVE_DISABLED_MASK; 4770 } 4771 break; 4772 case com.android.internal.R.styleable.View_duplicateParentState: 4773 if (a.getBoolean(attr, false)) { 4774 viewFlagValues |= DUPLICATE_PARENT_STATE; 4775 viewFlagMasks |= DUPLICATE_PARENT_STATE; 4776 } 4777 break; 4778 case com.android.internal.R.styleable.View_visibility: 4779 final int visibility = a.getInt(attr, 0); 4780 if (visibility != 0) { 4781 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 4782 viewFlagMasks |= VISIBILITY_MASK; 4783 } 4784 break; 4785 case com.android.internal.R.styleable.View_layoutDirection: 4786 // Clear any layout direction flags (included resolved bits) already set 4787 mPrivateFlags2 &= 4788 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 4789 // Set the layout direction flags depending on the value of the attribute 4790 final int layoutDirection = a.getInt(attr, -1); 4791 final int value = (layoutDirection != -1) ? 4792 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 4793 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 4794 break; 4795 case com.android.internal.R.styleable.View_drawingCacheQuality: 4796 final int cacheQuality = a.getInt(attr, 0); 4797 if (cacheQuality != 0) { 4798 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 4799 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 4800 } 4801 break; 4802 case com.android.internal.R.styleable.View_contentDescription: 4803 setContentDescription(a.getString(attr)); 4804 break; 4805 case com.android.internal.R.styleable.View_accessibilityTraversalBefore: 4806 setAccessibilityTraversalBefore(a.getResourceId(attr, NO_ID)); 4807 break; 4808 case com.android.internal.R.styleable.View_accessibilityTraversalAfter: 4809 setAccessibilityTraversalAfter(a.getResourceId(attr, NO_ID)); 4810 break; 4811 case com.android.internal.R.styleable.View_labelFor: 4812 setLabelFor(a.getResourceId(attr, NO_ID)); 4813 break; 4814 case com.android.internal.R.styleable.View_soundEffectsEnabled: 4815 if (!a.getBoolean(attr, true)) { 4816 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 4817 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 4818 } 4819 break; 4820 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 4821 if (!a.getBoolean(attr, true)) { 4822 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 4823 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 4824 } 4825 break; 4826 case R.styleable.View_scrollbars: 4827 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 4828 if (scrollbars != SCROLLBARS_NONE) { 4829 viewFlagValues |= scrollbars; 4830 viewFlagMasks |= SCROLLBARS_MASK; 4831 initializeScrollbars = true; 4832 } 4833 break; 4834 //noinspection deprecation 4835 case R.styleable.View_fadingEdge: 4836 if (targetSdkVersion >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 4837 // Ignore the attribute starting with ICS 4838 break; 4839 } 4840 // With builds < ICS, fall through and apply fading edges 4841 case R.styleable.View_requiresFadingEdge: 4842 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 4843 if (fadingEdge != FADING_EDGE_NONE) { 4844 viewFlagValues |= fadingEdge; 4845 viewFlagMasks |= FADING_EDGE_MASK; 4846 initializeFadingEdgeInternal(a); 4847 } 4848 break; 4849 case R.styleable.View_scrollbarStyle: 4850 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 4851 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4852 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 4853 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 4854 } 4855 break; 4856 case R.styleable.View_isScrollContainer: 4857 setScrollContainer = true; 4858 if (a.getBoolean(attr, false)) { 4859 setScrollContainer(true); 4860 } 4861 break; 4862 case com.android.internal.R.styleable.View_keepScreenOn: 4863 if (a.getBoolean(attr, false)) { 4864 viewFlagValues |= KEEP_SCREEN_ON; 4865 viewFlagMasks |= KEEP_SCREEN_ON; 4866 } 4867 break; 4868 case R.styleable.View_filterTouchesWhenObscured: 4869 if (a.getBoolean(attr, false)) { 4870 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 4871 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 4872 } 4873 break; 4874 case R.styleable.View_nextFocusLeft: 4875 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 4876 break; 4877 case R.styleable.View_nextFocusRight: 4878 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 4879 break; 4880 case R.styleable.View_nextFocusUp: 4881 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 4882 break; 4883 case R.styleable.View_nextFocusDown: 4884 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 4885 break; 4886 case R.styleable.View_nextFocusForward: 4887 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 4888 break; 4889 case R.styleable.View_nextClusterForward: 4890 mNextClusterForwardId = a.getResourceId(attr, View.NO_ID); 4891 break; 4892 case R.styleable.View_minWidth: 4893 mMinWidth = a.getDimensionPixelSize(attr, 0); 4894 break; 4895 case R.styleable.View_minHeight: 4896 mMinHeight = a.getDimensionPixelSize(attr, 0); 4897 break; 4898 case R.styleable.View_onClick: 4899 if (context.isRestricted()) { 4900 throw new IllegalStateException("The android:onClick attribute cannot " 4901 + "be used within a restricted context"); 4902 } 4903 4904 final String handlerName = a.getString(attr); 4905 if (handlerName != null) { 4906 setOnClickListener(new DeclaredOnClickListener(this, handlerName)); 4907 } 4908 break; 4909 case R.styleable.View_overScrollMode: 4910 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4911 break; 4912 case R.styleable.View_verticalScrollbarPosition: 4913 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4914 break; 4915 case R.styleable.View_layerType: 4916 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4917 break; 4918 case R.styleable.View_textDirection: 4919 // Clear any text direction flag already set 4920 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4921 // Set the text direction flags depending on the value of the attribute 4922 final int textDirection = a.getInt(attr, -1); 4923 if (textDirection != -1) { 4924 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4925 } 4926 break; 4927 case R.styleable.View_textAlignment: 4928 // Clear any text alignment flag already set 4929 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4930 // Set the text alignment flag depending on the value of the attribute 4931 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4932 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4933 break; 4934 case R.styleable.View_importantForAccessibility: 4935 setImportantForAccessibility(a.getInt(attr, 4936 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4937 break; 4938 case R.styleable.View_accessibilityLiveRegion: 4939 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4940 break; 4941 case R.styleable.View_transitionName: 4942 setTransitionName(a.getString(attr)); 4943 break; 4944 case R.styleable.View_nestedScrollingEnabled: 4945 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4946 break; 4947 case R.styleable.View_stateListAnimator: 4948 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4949 a.getResourceId(attr, 0))); 4950 break; 4951 case R.styleable.View_backgroundTint: 4952 // This will get applied later during setBackground(). 4953 if (mBackgroundTint == null) { 4954 mBackgroundTint = new TintInfo(); 4955 } 4956 mBackgroundTint.mTintList = a.getColorStateList( 4957 R.styleable.View_backgroundTint); 4958 mBackgroundTint.mHasTintList = true; 4959 break; 4960 case R.styleable.View_backgroundTintMode: 4961 // This will get applied later during setBackground(). 4962 if (mBackgroundTint == null) { 4963 mBackgroundTint = new TintInfo(); 4964 } 4965 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4966 R.styleable.View_backgroundTintMode, -1), null); 4967 mBackgroundTint.mHasTintMode = true; 4968 break; 4969 case R.styleable.View_outlineProvider: 4970 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4971 PROVIDER_BACKGROUND)); 4972 break; 4973 case R.styleable.View_foreground: 4974 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 4975 setForeground(a.getDrawable(attr)); 4976 } 4977 break; 4978 case R.styleable.View_foregroundGravity: 4979 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 4980 setForegroundGravity(a.getInt(attr, Gravity.NO_GRAVITY)); 4981 } 4982 break; 4983 case R.styleable.View_foregroundTintMode: 4984 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 4985 setForegroundTintMode(Drawable.parseTintMode(a.getInt(attr, -1), null)); 4986 } 4987 break; 4988 case R.styleable.View_foregroundTint: 4989 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 4990 setForegroundTintList(a.getColorStateList(attr)); 4991 } 4992 break; 4993 case R.styleable.View_foregroundInsidePadding: 4994 if (targetSdkVersion >= Build.VERSION_CODES.M || this instanceof FrameLayout) { 4995 if (mForegroundInfo == null) { 4996 mForegroundInfo = new ForegroundInfo(); 4997 } 4998 mForegroundInfo.mInsidePadding = a.getBoolean(attr, 4999 mForegroundInfo.mInsidePadding); 5000 } 5001 break; 5002 case R.styleable.View_scrollIndicators: 5003 final int scrollIndicators = 5004 (a.getInt(attr, 0) << SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT) 5005 & SCROLL_INDICATORS_PFLAG3_MASK; 5006 if (scrollIndicators != 0) { 5007 mPrivateFlags3 |= scrollIndicators; 5008 initializeScrollIndicators = true; 5009 } 5010 break; 5011 case R.styleable.View_pointerIcon: 5012 final int resourceId = a.getResourceId(attr, 0); 5013 if (resourceId != 0) { 5014 setPointerIcon(PointerIcon.load( 5015 context.getResources(), resourceId)); 5016 } else { 5017 final int pointerType = a.getInt(attr, PointerIcon.TYPE_NOT_SPECIFIED); 5018 if (pointerType != PointerIcon.TYPE_NOT_SPECIFIED) { 5019 setPointerIcon(PointerIcon.getSystemIcon(context, pointerType)); 5020 } 5021 } 5022 break; 5023 case R.styleable.View_forceHasOverlappingRendering: 5024 if (a.peekValue(attr) != null) { 5025 forceHasOverlappingRendering(a.getBoolean(attr, true)); 5026 } 5027 break; 5028 case R.styleable.View_tooltipText: 5029 setTooltipText(a.getText(attr)); 5030 break; 5031 case R.styleable.View_keyboardNavigationCluster: 5032 if (a.peekValue(attr) != null) { 5033 setKeyboardNavigationCluster(a.getBoolean(attr, true)); 5034 } 5035 break; 5036 case R.styleable.View_focusedByDefault: 5037 if (a.peekValue(attr) != null) { 5038 setFocusedByDefault(a.getBoolean(attr, true)); 5039 } 5040 break; 5041 case R.styleable.View_autofillMode: 5042 if (a.peekValue(attr) != null) { 5043 setAutofillMode(a.getInt(attr, AUTOFILL_MODE_INHERIT)); 5044 } 5045 break; 5046 case R.styleable.View_autofillHints: 5047 if (a.peekValue(attr) != null) { 5048 CharSequence[] rawHints = null; 5049 String rawString = null; 5050 5051 if (a.getType(attr) == TypedValue.TYPE_REFERENCE) { 5052 int resId = a.getResourceId(attr, 0); 5053 5054 try { 5055 rawHints = a.getTextArray(attr); 5056 } catch (Resources.NotFoundException e) { 5057 rawString = getResources().getString(resId); 5058 } 5059 } else { 5060 rawString = a.getString(attr); 5061 } 5062 5063 if (rawHints == null) { 5064 if (rawString == null) { 5065 throw new IllegalArgumentException( 5066 "Could not resolve autofillHints"); 5067 } else { 5068 rawHints = rawString.split(","); 5069 } 5070 } 5071 5072 String[] hints = new String[rawHints.length]; 5073 5074 int numHints = rawHints.length; 5075 for (int rawHintNum = 0; rawHintNum < numHints; rawHintNum++) { 5076 hints[rawHintNum] = rawHints[rawHintNum].toString().trim(); 5077 } 5078 setAutofillHints(hints); 5079 } 5080 break; 5081 case R.styleable.View_importantForAutofill: 5082 if (a.peekValue(attr) != null) { 5083 setImportantForAutofill(a.getInt(attr, IMPORTANT_FOR_AUTOFILL_AUTO)); 5084 } 5085 break; 5086 case R.styleable.View_defaultFocusHighlightEnabled: 5087 if (a.peekValue(attr) != null) { 5088 setDefaultFocusHighlightEnabled(a.getBoolean(attr, true)); 5089 } 5090 break; 5091 } 5092 } 5093 5094 setOverScrollMode(overScrollMode); 5095 5096 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 5097 // the resolved layout direction). Those cached values will be used later during padding 5098 // resolution. 5099 mUserPaddingStart = startPadding; 5100 mUserPaddingEnd = endPadding; 5101 5102 if (background != null) { 5103 setBackground(background); 5104 } 5105 5106 // setBackground above will record that padding is currently provided by the background. 5107 // If we have padding specified via xml, record that here instead and use it. 5108 mLeftPaddingDefined = leftPaddingDefined; 5109 mRightPaddingDefined = rightPaddingDefined; 5110 5111 if (padding >= 0) { 5112 leftPadding = padding; 5113 topPadding = padding; 5114 rightPadding = padding; 5115 bottomPadding = padding; 5116 mUserPaddingLeftInitial = padding; 5117 mUserPaddingRightInitial = padding; 5118 } else { 5119 if (paddingHorizontal >= 0) { 5120 leftPadding = paddingHorizontal; 5121 rightPadding = paddingHorizontal; 5122 mUserPaddingLeftInitial = paddingHorizontal; 5123 mUserPaddingRightInitial = paddingHorizontal; 5124 } 5125 if (paddingVertical >= 0) { 5126 topPadding = paddingVertical; 5127 bottomPadding = paddingVertical; 5128 } 5129 } 5130 5131 if (isRtlCompatibilityMode()) { 5132 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 5133 // left / right padding are used if defined (meaning here nothing to do). If they are not 5134 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 5135 // start / end and resolve them as left / right (layout direction is not taken into account). 5136 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 5137 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 5138 // defined. 5139 if (!mLeftPaddingDefined && startPaddingDefined) { 5140 leftPadding = startPadding; 5141 } 5142 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 5143 if (!mRightPaddingDefined && endPaddingDefined) { 5144 rightPadding = endPadding; 5145 } 5146 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 5147 } else { 5148 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 5149 // values defined. Otherwise, left /right values are used. 5150 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 5151 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 5152 // defined. 5153 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 5154 5155 if (mLeftPaddingDefined && !hasRelativePadding) { 5156 mUserPaddingLeftInitial = leftPadding; 5157 } 5158 if (mRightPaddingDefined && !hasRelativePadding) { 5159 mUserPaddingRightInitial = rightPadding; 5160 } 5161 } 5162 5163 internalSetPadding( 5164 mUserPaddingLeftInitial, 5165 topPadding >= 0 ? topPadding : mPaddingTop, 5166 mUserPaddingRightInitial, 5167 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 5168 5169 if (viewFlagMasks != 0) { 5170 setFlags(viewFlagValues, viewFlagMasks); 5171 } 5172 5173 if (initializeScrollbars) { 5174 initializeScrollbarsInternal(a); 5175 } 5176 5177 if (initializeScrollIndicators) { 5178 initializeScrollIndicatorsInternal(); 5179 } 5180 5181 a.recycle(); 5182 5183 // Needs to be called after mViewFlags is set 5184 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 5185 recomputePadding(); 5186 } 5187 5188 if (x != 0 || y != 0) { 5189 scrollTo(x, y); 5190 } 5191 5192 if (transformSet) { 5193 setTranslationX(tx); 5194 setTranslationY(ty); 5195 setTranslationZ(tz); 5196 setElevation(elevation); 5197 setRotation(rotation); 5198 setRotationX(rotationX); 5199 setRotationY(rotationY); 5200 setScaleX(sx); 5201 setScaleY(sy); 5202 } 5203 5204 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 5205 setScrollContainer(true); 5206 } 5207 5208 computeOpaqueFlags(); 5209 } 5210 5211 /** 5212 * An implementation of OnClickListener that attempts to lazily load a 5213 * named click handling method from a parent or ancestor context. 5214 */ 5215 private static class DeclaredOnClickListener implements OnClickListener { 5216 private final View mHostView; 5217 private final String mMethodName; 5218 5219 private Method mResolvedMethod; 5220 private Context mResolvedContext; 5221 5222 public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) { 5223 mHostView = hostView; 5224 mMethodName = methodName; 5225 } 5226 5227 @Override 5228 public void onClick(@NonNull View v) { 5229 if (mResolvedMethod == null) { 5230 resolveMethod(mHostView.getContext(), mMethodName); 5231 } 5232 5233 try { 5234 mResolvedMethod.invoke(mResolvedContext, v); 5235 } catch (IllegalAccessException e) { 5236 throw new IllegalStateException( 5237 "Could not execute non-public method for android:onClick", e); 5238 } catch (InvocationTargetException e) { 5239 throw new IllegalStateException( 5240 "Could not execute method for android:onClick", e); 5241 } 5242 } 5243 5244 @NonNull 5245 private void resolveMethod(@Nullable Context context, @NonNull String name) { 5246 while (context != null) { 5247 try { 5248 if (!context.isRestricted()) { 5249 final Method method = context.getClass().getMethod(mMethodName, View.class); 5250 if (method != null) { 5251 mResolvedMethod = method; 5252 mResolvedContext = context; 5253 return; 5254 } 5255 } 5256 } catch (NoSuchMethodException e) { 5257 // Failed to find method, keep searching up the hierarchy. 5258 } 5259 5260 if (context instanceof ContextWrapper) { 5261 context = ((ContextWrapper) context).getBaseContext(); 5262 } else { 5263 // Can't search up the hierarchy, null out and fail. 5264 context = null; 5265 } 5266 } 5267 5268 final int id = mHostView.getId(); 5269 final String idText = id == NO_ID ? "" : " with id '" 5270 + mHostView.getContext().getResources().getResourceEntryName(id) + "'"; 5271 throw new IllegalStateException("Could not find method " + mMethodName 5272 + "(View) in a parent or ancestor Context for android:onClick " 5273 + "attribute defined on view " + mHostView.getClass() + idText); 5274 } 5275 } 5276 5277 /** 5278 * Non-public constructor for use in testing 5279 */ 5280 View() { 5281 mResources = null; 5282 mRenderNode = RenderNode.create(getClass().getName(), this); 5283 } 5284 5285 final boolean debugDraw() { 5286 return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout; 5287 } 5288 5289 private static SparseArray<String> getAttributeMap() { 5290 if (mAttributeMap == null) { 5291 mAttributeMap = new SparseArray<>(); 5292 } 5293 return mAttributeMap; 5294 } 5295 5296 private void saveAttributeData(@Nullable AttributeSet attrs, @NonNull TypedArray t) { 5297 final int attrsCount = attrs == null ? 0 : attrs.getAttributeCount(); 5298 final int indexCount = t.getIndexCount(); 5299 final String[] attributes = new String[(attrsCount + indexCount) * 2]; 5300 5301 int i = 0; 5302 5303 // Store raw XML attributes. 5304 for (int j = 0; j < attrsCount; ++j) { 5305 attributes[i] = attrs.getAttributeName(j); 5306 attributes[i + 1] = attrs.getAttributeValue(j); 5307 i += 2; 5308 } 5309 5310 // Store resolved styleable attributes. 5311 final Resources res = t.getResources(); 5312 final SparseArray<String> attributeMap = getAttributeMap(); 5313 for (int j = 0; j < indexCount; ++j) { 5314 final int index = t.getIndex(j); 5315 if (!t.hasValueOrEmpty(index)) { 5316 // Value is undefined. Skip it. 5317 continue; 5318 } 5319 5320 final int resourceId = t.getResourceId(index, 0); 5321 if (resourceId == 0) { 5322 // Value is not a reference. Skip it. 5323 continue; 5324 } 5325 5326 String resourceName = attributeMap.get(resourceId); 5327 if (resourceName == null) { 5328 try { 5329 resourceName = res.getResourceName(resourceId); 5330 } catch (Resources.NotFoundException e) { 5331 resourceName = "0x" + Integer.toHexString(resourceId); 5332 } 5333 attributeMap.put(resourceId, resourceName); 5334 } 5335 5336 attributes[i] = resourceName; 5337 attributes[i + 1] = t.getString(index); 5338 i += 2; 5339 } 5340 5341 // Trim to fit contents. 5342 final String[] trimmed = new String[i]; 5343 System.arraycopy(attributes, 0, trimmed, 0, i); 5344 mAttributes = trimmed; 5345 } 5346 5347 public String toString() { 5348 StringBuilder out = new StringBuilder(128); 5349 out.append(getClass().getName()); 5350 out.append('{'); 5351 out.append(Integer.toHexString(System.identityHashCode(this))); 5352 out.append(' '); 5353 switch (mViewFlags&VISIBILITY_MASK) { 5354 case VISIBLE: out.append('V'); break; 5355 case INVISIBLE: out.append('I'); break; 5356 case GONE: out.append('G'); break; 5357 default: out.append('.'); break; 5358 } 5359 out.append((mViewFlags & FOCUSABLE) == FOCUSABLE ? 'F' : '.'); 5360 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 5361 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 5362 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 5363 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 5364 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 5365 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 5366 out.append((mViewFlags&CONTEXT_CLICKABLE) != 0 ? 'X' : '.'); 5367 out.append(' '); 5368 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 5369 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 5370 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 5371 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 5372 out.append('p'); 5373 } else { 5374 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 5375 } 5376 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 5377 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 5378 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 5379 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 5380 out.append(' '); 5381 out.append(mLeft); 5382 out.append(','); 5383 out.append(mTop); 5384 out.append('-'); 5385 out.append(mRight); 5386 out.append(','); 5387 out.append(mBottom); 5388 final int id = getId(); 5389 if (id != NO_ID) { 5390 out.append(" #"); 5391 out.append(Integer.toHexString(id)); 5392 final Resources r = mResources; 5393 if (id > 0 && Resources.resourceHasPackage(id) && r != null) { 5394 try { 5395 String pkgname; 5396 switch (id&0xff000000) { 5397 case 0x7f000000: 5398 pkgname="app"; 5399 break; 5400 case 0x01000000: 5401 pkgname="android"; 5402 break; 5403 default: 5404 pkgname = r.getResourcePackageName(id); 5405 break; 5406 } 5407 String typename = r.getResourceTypeName(id); 5408 String entryname = r.getResourceEntryName(id); 5409 out.append(" "); 5410 out.append(pkgname); 5411 out.append(":"); 5412 out.append(typename); 5413 out.append("/"); 5414 out.append(entryname); 5415 } catch (Resources.NotFoundException e) { 5416 } 5417 } 5418 } 5419 out.append("}"); 5420 return out.toString(); 5421 } 5422 5423 /** 5424 * <p> 5425 * Initializes the fading edges from a given set of styled attributes. This 5426 * method should be called by subclasses that need fading edges and when an 5427 * instance of these subclasses is created programmatically rather than 5428 * being inflated from XML. This method is automatically called when the XML 5429 * is inflated. 5430 * </p> 5431 * 5432 * @param a the styled attributes set to initialize the fading edges from 5433 * 5434 * @removed 5435 */ 5436 protected void initializeFadingEdge(TypedArray a) { 5437 // This method probably shouldn't have been included in the SDK to begin with. 5438 // It relies on 'a' having been initialized using an attribute filter array that is 5439 // not publicly available to the SDK. The old method has been renamed 5440 // to initializeFadingEdgeInternal and hidden for framework use only; 5441 // this one initializes using defaults to make it safe to call for apps. 5442 5443 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5444 5445 initializeFadingEdgeInternal(arr); 5446 5447 arr.recycle(); 5448 } 5449 5450 /** 5451 * <p> 5452 * Initializes the fading edges from a given set of styled attributes. This 5453 * method should be called by subclasses that need fading edges and when an 5454 * instance of these subclasses is created programmatically rather than 5455 * being inflated from XML. This method is automatically called when the XML 5456 * is inflated. 5457 * </p> 5458 * 5459 * @param a the styled attributes set to initialize the fading edges from 5460 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 5461 */ 5462 protected void initializeFadingEdgeInternal(TypedArray a) { 5463 initScrollCache(); 5464 5465 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 5466 R.styleable.View_fadingEdgeLength, 5467 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 5468 } 5469 5470 /** 5471 * Returns the size of the vertical faded edges used to indicate that more 5472 * content in this view is visible. 5473 * 5474 * @return The size in pixels of the vertical faded edge or 0 if vertical 5475 * faded edges are not enabled for this view. 5476 * @attr ref android.R.styleable#View_fadingEdgeLength 5477 */ 5478 public int getVerticalFadingEdgeLength() { 5479 if (isVerticalFadingEdgeEnabled()) { 5480 ScrollabilityCache cache = mScrollCache; 5481 if (cache != null) { 5482 return cache.fadingEdgeLength; 5483 } 5484 } 5485 return 0; 5486 } 5487 5488 /** 5489 * Set the size of the faded edge used to indicate that more content in this 5490 * view is available. Will not change whether the fading edge is enabled; use 5491 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 5492 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 5493 * for the vertical or horizontal fading edges. 5494 * 5495 * @param length The size in pixels of the faded edge used to indicate that more 5496 * content in this view is visible. 5497 */ 5498 public void setFadingEdgeLength(int length) { 5499 initScrollCache(); 5500 mScrollCache.fadingEdgeLength = length; 5501 } 5502 5503 /** 5504 * Returns the size of the horizontal faded edges used to indicate that more 5505 * content in this view is visible. 5506 * 5507 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 5508 * faded edges are not enabled for this view. 5509 * @attr ref android.R.styleable#View_fadingEdgeLength 5510 */ 5511 public int getHorizontalFadingEdgeLength() { 5512 if (isHorizontalFadingEdgeEnabled()) { 5513 ScrollabilityCache cache = mScrollCache; 5514 if (cache != null) { 5515 return cache.fadingEdgeLength; 5516 } 5517 } 5518 return 0; 5519 } 5520 5521 /** 5522 * Returns the width of the vertical scrollbar. 5523 * 5524 * @return The width in pixels of the vertical scrollbar or 0 if there 5525 * is no vertical scrollbar. 5526 */ 5527 public int getVerticalScrollbarWidth() { 5528 ScrollabilityCache cache = mScrollCache; 5529 if (cache != null) { 5530 ScrollBarDrawable scrollBar = cache.scrollBar; 5531 if (scrollBar != null) { 5532 int size = scrollBar.getSize(true); 5533 if (size <= 0) { 5534 size = cache.scrollBarSize; 5535 } 5536 return size; 5537 } 5538 return 0; 5539 } 5540 return 0; 5541 } 5542 5543 /** 5544 * Returns the height of the horizontal scrollbar. 5545 * 5546 * @return The height in pixels of the horizontal scrollbar or 0 if 5547 * there is no horizontal scrollbar. 5548 */ 5549 protected int getHorizontalScrollbarHeight() { 5550 ScrollabilityCache cache = mScrollCache; 5551 if (cache != null) { 5552 ScrollBarDrawable scrollBar = cache.scrollBar; 5553 if (scrollBar != null) { 5554 int size = scrollBar.getSize(false); 5555 if (size <= 0) { 5556 size = cache.scrollBarSize; 5557 } 5558 return size; 5559 } 5560 return 0; 5561 } 5562 return 0; 5563 } 5564 5565 /** 5566 * <p> 5567 * Initializes the scrollbars from a given set of styled attributes. This 5568 * method should be called by subclasses that need scrollbars and when an 5569 * instance of these subclasses is created programmatically rather than 5570 * being inflated from XML. This method is automatically called when the XML 5571 * is inflated. 5572 * </p> 5573 * 5574 * @param a the styled attributes set to initialize the scrollbars from 5575 * 5576 * @removed 5577 */ 5578 protected void initializeScrollbars(TypedArray a) { 5579 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 5580 // using the View filter array which is not available to the SDK. As such, internal 5581 // framework usage now uses initializeScrollbarsInternal and we grab a default 5582 // TypedArray with the right filter instead here. 5583 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 5584 5585 initializeScrollbarsInternal(arr); 5586 5587 // We ignored the method parameter. Recycle the one we actually did use. 5588 arr.recycle(); 5589 } 5590 5591 /** 5592 * <p> 5593 * Initializes the scrollbars from a given set of styled attributes. This 5594 * method should be called by subclasses that need scrollbars and when an 5595 * instance of these subclasses is created programmatically rather than 5596 * being inflated from XML. This method is automatically called when the XML 5597 * is inflated. 5598 * </p> 5599 * 5600 * @param a the styled attributes set to initialize the scrollbars from 5601 * @hide 5602 */ 5603 protected void initializeScrollbarsInternal(TypedArray a) { 5604 initScrollCache(); 5605 5606 final ScrollabilityCache scrollabilityCache = mScrollCache; 5607 5608 if (scrollabilityCache.scrollBar == null) { 5609 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 5610 scrollabilityCache.scrollBar.setState(getDrawableState()); 5611 scrollabilityCache.scrollBar.setCallback(this); 5612 } 5613 5614 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 5615 5616 if (!fadeScrollbars) { 5617 scrollabilityCache.state = ScrollabilityCache.ON; 5618 } 5619 scrollabilityCache.fadeScrollBars = fadeScrollbars; 5620 5621 5622 scrollabilityCache.scrollBarFadeDuration = a.getInt( 5623 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 5624 .getScrollBarFadeDuration()); 5625 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 5626 R.styleable.View_scrollbarDefaultDelayBeforeFade, 5627 ViewConfiguration.getScrollDefaultDelay()); 5628 5629 5630 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 5631 com.android.internal.R.styleable.View_scrollbarSize, 5632 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 5633 5634 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 5635 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 5636 5637 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 5638 if (thumb != null) { 5639 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 5640 } 5641 5642 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 5643 false); 5644 if (alwaysDraw) { 5645 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 5646 } 5647 5648 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 5649 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 5650 5651 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 5652 if (thumb != null) { 5653 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 5654 } 5655 5656 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 5657 false); 5658 if (alwaysDraw) { 5659 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 5660 } 5661 5662 // Apply layout direction to the new Drawables if needed 5663 final int layoutDirection = getLayoutDirection(); 5664 if (track != null) { 5665 track.setLayoutDirection(layoutDirection); 5666 } 5667 if (thumb != null) { 5668 thumb.setLayoutDirection(layoutDirection); 5669 } 5670 5671 // Re-apply user/background padding so that scrollbar(s) get added 5672 resolvePadding(); 5673 } 5674 5675 private void initializeScrollIndicatorsInternal() { 5676 // Some day maybe we'll break this into top/left/start/etc. and let the 5677 // client control it. Until then, you can have any scroll indicator you 5678 // want as long as it's a 1dp foreground-colored rectangle. 5679 if (mScrollIndicatorDrawable == null) { 5680 mScrollIndicatorDrawable = mContext.getDrawable(R.drawable.scroll_indicator_material); 5681 } 5682 } 5683 5684 /** 5685 * <p> 5686 * Initalizes the scrollability cache if necessary. 5687 * </p> 5688 */ 5689 private void initScrollCache() { 5690 if (mScrollCache == null) { 5691 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 5692 } 5693 } 5694 5695 private ScrollabilityCache getScrollCache() { 5696 initScrollCache(); 5697 return mScrollCache; 5698 } 5699 5700 /** 5701 * Set the position of the vertical scroll bar. Should be one of 5702 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 5703 * {@link #SCROLLBAR_POSITION_RIGHT}. 5704 * 5705 * @param position Where the vertical scroll bar should be positioned. 5706 */ 5707 public void setVerticalScrollbarPosition(int position) { 5708 if (mVerticalScrollbarPosition != position) { 5709 mVerticalScrollbarPosition = position; 5710 computeOpaqueFlags(); 5711 resolvePadding(); 5712 } 5713 } 5714 5715 /** 5716 * @return The position where the vertical scroll bar will show, if applicable. 5717 * @see #setVerticalScrollbarPosition(int) 5718 */ 5719 public int getVerticalScrollbarPosition() { 5720 return mVerticalScrollbarPosition; 5721 } 5722 5723 boolean isOnScrollbar(float x, float y) { 5724 if (mScrollCache == null) { 5725 return false; 5726 } 5727 x += getScrollX(); 5728 y += getScrollY(); 5729 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5730 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5731 getVerticalScrollBarBounds(null, touchBounds); 5732 if (touchBounds.contains((int) x, (int) y)) { 5733 return true; 5734 } 5735 } 5736 if (isHorizontalScrollBarEnabled()) { 5737 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5738 getHorizontalScrollBarBounds(null, touchBounds); 5739 if (touchBounds.contains((int) x, (int) y)) { 5740 return true; 5741 } 5742 } 5743 return false; 5744 } 5745 5746 boolean isOnScrollbarThumb(float x, float y) { 5747 return isOnVerticalScrollbarThumb(x, y) || isOnHorizontalScrollbarThumb(x, y); 5748 } 5749 5750 private boolean isOnVerticalScrollbarThumb(float x, float y) { 5751 if (mScrollCache == null) { 5752 return false; 5753 } 5754 if (isVerticalScrollBarEnabled() && !isVerticalScrollBarHidden()) { 5755 x += getScrollX(); 5756 y += getScrollY(); 5757 final Rect bounds = mScrollCache.mScrollBarBounds; 5758 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5759 getVerticalScrollBarBounds(bounds, touchBounds); 5760 final int range = computeVerticalScrollRange(); 5761 final int offset = computeVerticalScrollOffset(); 5762 final int extent = computeVerticalScrollExtent(); 5763 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.height(), bounds.width(), 5764 extent, range); 5765 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.height(), thumbLength, 5766 extent, range, offset); 5767 final int thumbTop = bounds.top + thumbOffset; 5768 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2; 5769 if (x >= touchBounds.left && x <= touchBounds.right 5770 && y >= thumbTop - adjust && y <= thumbTop + thumbLength + adjust) { 5771 return true; 5772 } 5773 } 5774 return false; 5775 } 5776 5777 private boolean isOnHorizontalScrollbarThumb(float x, float y) { 5778 if (mScrollCache == null) { 5779 return false; 5780 } 5781 if (isHorizontalScrollBarEnabled()) { 5782 x += getScrollX(); 5783 y += getScrollY(); 5784 final Rect bounds = mScrollCache.mScrollBarBounds; 5785 final Rect touchBounds = mScrollCache.mScrollBarTouchBounds; 5786 getHorizontalScrollBarBounds(bounds, touchBounds); 5787 final int range = computeHorizontalScrollRange(); 5788 final int offset = computeHorizontalScrollOffset(); 5789 final int extent = computeHorizontalScrollExtent(); 5790 final int thumbLength = ScrollBarUtils.getThumbLength(bounds.width(), bounds.height(), 5791 extent, range); 5792 final int thumbOffset = ScrollBarUtils.getThumbOffset(bounds.width(), thumbLength, 5793 extent, range, offset); 5794 final int thumbLeft = bounds.left + thumbOffset; 5795 final int adjust = Math.max(mScrollCache.scrollBarMinTouchTarget - thumbLength, 0) / 2; 5796 if (x >= thumbLeft - adjust && x <= thumbLeft + thumbLength + adjust 5797 && y >= touchBounds.top && y <= touchBounds.bottom) { 5798 return true; 5799 } 5800 } 5801 return false; 5802 } 5803 5804 boolean isDraggingScrollBar() { 5805 return mScrollCache != null 5806 && mScrollCache.mScrollBarDraggingState != ScrollabilityCache.NOT_DRAGGING; 5807 } 5808 5809 /** 5810 * Sets the state of all scroll indicators. 5811 * <p> 5812 * See {@link #setScrollIndicators(int, int)} for usage information. 5813 * 5814 * @param indicators a bitmask of indicators that should be enabled, or 5815 * {@code 0} to disable all indicators 5816 * @see #setScrollIndicators(int, int) 5817 * @see #getScrollIndicators() 5818 * @attr ref android.R.styleable#View_scrollIndicators 5819 */ 5820 public void setScrollIndicators(@ScrollIndicators int indicators) { 5821 setScrollIndicators(indicators, 5822 SCROLL_INDICATORS_PFLAG3_MASK >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT); 5823 } 5824 5825 /** 5826 * Sets the state of the scroll indicators specified by the mask. To change 5827 * all scroll indicators at once, see {@link #setScrollIndicators(int)}. 5828 * <p> 5829 * When a scroll indicator is enabled, it will be displayed if the view 5830 * can scroll in the direction of the indicator. 5831 * <p> 5832 * Multiple indicator types may be enabled or disabled by passing the 5833 * logical OR of the desired types. If multiple types are specified, they 5834 * will all be set to the same enabled state. 5835 * <p> 5836 * For example, to enable the top scroll indicatorExample: {@code setScrollIndicators 5837 * 5838 * @param indicators the indicator direction, or the logical OR of multiple 5839 * indicator directions. One or more of: 5840 * <ul> 5841 * <li>{@link #SCROLL_INDICATOR_TOP}</li> 5842 * <li>{@link #SCROLL_INDICATOR_BOTTOM}</li> 5843 * <li>{@link #SCROLL_INDICATOR_LEFT}</li> 5844 * <li>{@link #SCROLL_INDICATOR_RIGHT}</li> 5845 * <li>{@link #SCROLL_INDICATOR_START}</li> 5846 * <li>{@link #SCROLL_INDICATOR_END}</li> 5847 * </ul> 5848 * @see #setScrollIndicators(int) 5849 * @see #getScrollIndicators() 5850 * @attr ref android.R.styleable#View_scrollIndicators 5851 */ 5852 public void setScrollIndicators(@ScrollIndicators int indicators, @ScrollIndicators int mask) { 5853 // Shift and sanitize mask. 5854 mask <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5855 mask &= SCROLL_INDICATORS_PFLAG3_MASK; 5856 5857 // Shift and mask indicators. 5858 indicators <<= SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5859 indicators &= mask; 5860 5861 // Merge with non-masked flags. 5862 final int updatedFlags = indicators | (mPrivateFlags3 & ~mask); 5863 5864 if (mPrivateFlags3 != updatedFlags) { 5865 mPrivateFlags3 = updatedFlags; 5866 5867 if (indicators != 0) { 5868 initializeScrollIndicatorsInternal(); 5869 } 5870 invalidate(); 5871 } 5872 } 5873 5874 /** 5875 * Returns a bitmask representing the enabled scroll indicators. 5876 * <p> 5877 * For example, if the top and left scroll indicators are enabled and all 5878 * other indicators are disabled, the return value will be 5879 * {@code View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_LEFT}. 5880 * <p> 5881 * To check whether the bottom scroll indicator is enabled, use the value 5882 * of {@code (getScrollIndicators() & View.SCROLL_INDICATOR_BOTTOM) != 0}. 5883 * 5884 * @return a bitmask representing the enabled scroll indicators 5885 */ 5886 @ScrollIndicators 5887 public int getScrollIndicators() { 5888 return (mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) 5889 >>> SCROLL_INDICATORS_TO_PFLAGS3_LSHIFT; 5890 } 5891 5892 ListenerInfo getListenerInfo() { 5893 if (mListenerInfo != null) { 5894 return mListenerInfo; 5895 } 5896 mListenerInfo = new ListenerInfo(); 5897 return mListenerInfo; 5898 } 5899 5900 /** 5901 * Register a callback to be invoked when the scroll X or Y positions of 5902 * this view change. 5903 * <p> 5904 * <b>Note:</b> Some views handle scrolling independently from View and may 5905 * have their own separate listeners for scroll-type events. For example, 5906 * {@link android.widget.ListView ListView} allows clients to register an 5907 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 5908 * to listen for changes in list scroll position. 5909 * 5910 * @param l The listener to notify when the scroll X or Y position changes. 5911 * @see android.view.View#getScrollX() 5912 * @see android.view.View#getScrollY() 5913 */ 5914 public void setOnScrollChangeListener(OnScrollChangeListener l) { 5915 getListenerInfo().mOnScrollChangeListener = l; 5916 } 5917 5918 /** 5919 * Register a callback to be invoked when focus of this view changed. 5920 * 5921 * @param l The callback that will run. 5922 */ 5923 public void setOnFocusChangeListener(OnFocusChangeListener l) { 5924 getListenerInfo().mOnFocusChangeListener = l; 5925 } 5926 5927 /** 5928 * Add a listener that will be called when the bounds of the view change due to 5929 * layout processing. 5930 * 5931 * @param listener The listener that will be called when layout bounds change. 5932 */ 5933 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 5934 ListenerInfo li = getListenerInfo(); 5935 if (li.mOnLayoutChangeListeners == null) { 5936 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 5937 } 5938 if (!li.mOnLayoutChangeListeners.contains(listener)) { 5939 li.mOnLayoutChangeListeners.add(listener); 5940 } 5941 } 5942 5943 /** 5944 * Remove a listener for layout changes. 5945 * 5946 * @param listener The listener for layout bounds change. 5947 */ 5948 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 5949 ListenerInfo li = mListenerInfo; 5950 if (li == null || li.mOnLayoutChangeListeners == null) { 5951 return; 5952 } 5953 li.mOnLayoutChangeListeners.remove(listener); 5954 } 5955 5956 /** 5957 * Add a listener for attach state changes. 5958 * 5959 * This listener will be called whenever this view is attached or detached 5960 * from a window. Remove the listener using 5961 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 5962 * 5963 * @param listener Listener to attach 5964 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 5965 */ 5966 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5967 ListenerInfo li = getListenerInfo(); 5968 if (li.mOnAttachStateChangeListeners == null) { 5969 li.mOnAttachStateChangeListeners 5970 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 5971 } 5972 li.mOnAttachStateChangeListeners.add(listener); 5973 } 5974 5975 /** 5976 * Remove a listener for attach state changes. The listener will receive no further 5977 * notification of window attach/detach events. 5978 * 5979 * @param listener Listener to remove 5980 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 5981 */ 5982 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 5983 ListenerInfo li = mListenerInfo; 5984 if (li == null || li.mOnAttachStateChangeListeners == null) { 5985 return; 5986 } 5987 li.mOnAttachStateChangeListeners.remove(listener); 5988 } 5989 5990 /** 5991 * Returns the focus-change callback registered for this view. 5992 * 5993 * @return The callback, or null if one is not registered. 5994 */ 5995 public OnFocusChangeListener getOnFocusChangeListener() { 5996 ListenerInfo li = mListenerInfo; 5997 return li != null ? li.mOnFocusChangeListener : null; 5998 } 5999 6000 /** 6001 * Register a callback to be invoked when this view is clicked. If this view is not 6002 * clickable, it becomes clickable. 6003 * 6004 * @param l The callback that will run 6005 * 6006 * @see #setClickable(boolean) 6007 */ 6008 public void setOnClickListener(@Nullable OnClickListener l) { 6009 if (!isClickable()) { 6010 setClickable(true); 6011 } 6012 getListenerInfo().mOnClickListener = l; 6013 } 6014 6015 /** 6016 * Return whether this view has an attached OnClickListener. Returns 6017 * true if there is a listener, false if there is none. 6018 */ 6019 public boolean hasOnClickListeners() { 6020 ListenerInfo li = mListenerInfo; 6021 return (li != null && li.mOnClickListener != null); 6022 } 6023 6024 /** 6025 * Register a callback to be invoked when this view is clicked and held. If this view is not 6026 * long clickable, it becomes long clickable. 6027 * 6028 * @param l The callback that will run 6029 * 6030 * @see #setLongClickable(boolean) 6031 */ 6032 public void setOnLongClickListener(@Nullable OnLongClickListener l) { 6033 if (!isLongClickable()) { 6034 setLongClickable(true); 6035 } 6036 getListenerInfo().mOnLongClickListener = l; 6037 } 6038 6039 /** 6040 * Register a callback to be invoked when this view is context clicked. If the view is not 6041 * context clickable, it becomes context clickable. 6042 * 6043 * @param l The callback that will run 6044 * @see #setContextClickable(boolean) 6045 */ 6046 public void setOnContextClickListener(@Nullable OnContextClickListener l) { 6047 if (!isContextClickable()) { 6048 setContextClickable(true); 6049 } 6050 getListenerInfo().mOnContextClickListener = l; 6051 } 6052 6053 /** 6054 * Register a callback to be invoked when the context menu for this view is 6055 * being built. If this view is not long clickable, it becomes long clickable. 6056 * 6057 * @param l The callback that will run 6058 * 6059 */ 6060 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 6061 if (!isLongClickable()) { 6062 setLongClickable(true); 6063 } 6064 getListenerInfo().mOnCreateContextMenuListener = l; 6065 } 6066 6067 /** 6068 * Set an observer to collect stats for each frame rendered for this view. 6069 * 6070 * @hide 6071 */ 6072 public void addFrameMetricsListener(Window window, 6073 Window.OnFrameMetricsAvailableListener listener, 6074 Handler handler) { 6075 if (mAttachInfo != null) { 6076 if (mAttachInfo.mThreadedRenderer != null) { 6077 if (mFrameMetricsObservers == null) { 6078 mFrameMetricsObservers = new ArrayList<>(); 6079 } 6080 6081 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 6082 handler.getLooper(), listener); 6083 mFrameMetricsObservers.add(fmo); 6084 mAttachInfo.mThreadedRenderer.addFrameMetricsObserver(fmo); 6085 } else { 6086 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 6087 } 6088 } else { 6089 if (mFrameMetricsObservers == null) { 6090 mFrameMetricsObservers = new ArrayList<>(); 6091 } 6092 6093 FrameMetricsObserver fmo = new FrameMetricsObserver(window, 6094 handler.getLooper(), listener); 6095 mFrameMetricsObservers.add(fmo); 6096 } 6097 } 6098 6099 /** 6100 * Remove observer configured to collect frame stats for this view. 6101 * 6102 * @hide 6103 */ 6104 public void removeFrameMetricsListener( 6105 Window.OnFrameMetricsAvailableListener listener) { 6106 ThreadedRenderer renderer = getThreadedRenderer(); 6107 FrameMetricsObserver fmo = findFrameMetricsObserver(listener); 6108 if (fmo == null) { 6109 throw new IllegalArgumentException( 6110 "attempt to remove OnFrameMetricsAvailableListener that was never added"); 6111 } 6112 6113 if (mFrameMetricsObservers != null) { 6114 mFrameMetricsObservers.remove(fmo); 6115 if (renderer != null) { 6116 renderer.removeFrameMetricsObserver(fmo); 6117 } 6118 } 6119 } 6120 6121 private void registerPendingFrameMetricsObservers() { 6122 if (mFrameMetricsObservers != null) { 6123 ThreadedRenderer renderer = getThreadedRenderer(); 6124 if (renderer != null) { 6125 for (FrameMetricsObserver fmo : mFrameMetricsObservers) { 6126 renderer.addFrameMetricsObserver(fmo); 6127 } 6128 } else { 6129 Log.w(VIEW_LOG_TAG, "View not hardware-accelerated. Unable to observe frame stats"); 6130 } 6131 } 6132 } 6133 6134 private FrameMetricsObserver findFrameMetricsObserver( 6135 Window.OnFrameMetricsAvailableListener listener) { 6136 for (int i = 0; i < mFrameMetricsObservers.size(); i++) { 6137 FrameMetricsObserver observer = mFrameMetricsObservers.get(i); 6138 if (observer.mListener == listener) { 6139 return observer; 6140 } 6141 } 6142 6143 return null; 6144 } 6145 6146 /** 6147 * Call this view's OnClickListener, if it is defined. Performs all normal 6148 * actions associated with clicking: reporting accessibility event, playing 6149 * a sound, etc. 6150 * 6151 * @return True there was an assigned OnClickListener that was called, false 6152 * otherwise is returned. 6153 */ 6154 public boolean performClick() { 6155 final boolean result; 6156 final ListenerInfo li = mListenerInfo; 6157 if (li != null && li.mOnClickListener != null) { 6158 playSoundEffect(SoundEffectConstants.CLICK); 6159 li.mOnClickListener.onClick(this); 6160 result = true; 6161 } else { 6162 result = false; 6163 } 6164 6165 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 6166 6167 notifyEnterOrExitForAutoFillIfNeeded(true); 6168 6169 return result; 6170 } 6171 6172 /** 6173 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 6174 * this only calls the listener, and does not do any associated clicking 6175 * actions like reporting an accessibility event. 6176 * 6177 * @return True there was an assigned OnClickListener that was called, false 6178 * otherwise is returned. 6179 */ 6180 public boolean callOnClick() { 6181 ListenerInfo li = mListenerInfo; 6182 if (li != null && li.mOnClickListener != null) { 6183 li.mOnClickListener.onClick(this); 6184 return true; 6185 } 6186 return false; 6187 } 6188 6189 /** 6190 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6191 * context menu if the OnLongClickListener did not consume the event. 6192 * 6193 * @return {@code true} if one of the above receivers consumed the event, 6194 * {@code false} otherwise 6195 */ 6196 public boolean performLongClick() { 6197 return performLongClickInternal(mLongClickX, mLongClickY); 6198 } 6199 6200 /** 6201 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6202 * context menu if the OnLongClickListener did not consume the event, 6203 * anchoring it to an (x,y) coordinate. 6204 * 6205 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 6206 * to disable anchoring 6207 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 6208 * to disable anchoring 6209 * @return {@code true} if one of the above receivers consumed the event, 6210 * {@code false} otherwise 6211 */ 6212 public boolean performLongClick(float x, float y) { 6213 mLongClickX = x; 6214 mLongClickY = y; 6215 final boolean handled = performLongClick(); 6216 mLongClickX = Float.NaN; 6217 mLongClickY = Float.NaN; 6218 return handled; 6219 } 6220 6221 /** 6222 * Calls this view's OnLongClickListener, if it is defined. Invokes the 6223 * context menu if the OnLongClickListener did not consume the event, 6224 * optionally anchoring it to an (x,y) coordinate. 6225 * 6226 * @param x x coordinate of the anchoring touch event, or {@link Float#NaN} 6227 * to disable anchoring 6228 * @param y y coordinate of the anchoring touch event, or {@link Float#NaN} 6229 * to disable anchoring 6230 * @return {@code true} if one of the above receivers consumed the event, 6231 * {@code false} otherwise 6232 */ 6233 private boolean performLongClickInternal(float x, float y) { 6234 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 6235 6236 boolean handled = false; 6237 final ListenerInfo li = mListenerInfo; 6238 if (li != null && li.mOnLongClickListener != null) { 6239 handled = li.mOnLongClickListener.onLongClick(View.this); 6240 } 6241 if (!handled) { 6242 final boolean isAnchored = !Float.isNaN(x) && !Float.isNaN(y); 6243 handled = isAnchored ? showContextMenu(x, y) : showContextMenu(); 6244 } 6245 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 6246 if (!handled) { 6247 handled = showLongClickTooltip((int) x, (int) y); 6248 } 6249 } 6250 if (handled) { 6251 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 6252 } 6253 return handled; 6254 } 6255 6256 /** 6257 * Call this view's OnContextClickListener, if it is defined. 6258 * 6259 * @param x the x coordinate of the context click 6260 * @param y the y coordinate of the context click 6261 * @return True if there was an assigned OnContextClickListener that consumed the event, false 6262 * otherwise. 6263 */ 6264 public boolean performContextClick(float x, float y) { 6265 return performContextClick(); 6266 } 6267 6268 /** 6269 * Call this view's OnContextClickListener, if it is defined. 6270 * 6271 * @return True if there was an assigned OnContextClickListener that consumed the event, false 6272 * otherwise. 6273 */ 6274 public boolean performContextClick() { 6275 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CONTEXT_CLICKED); 6276 6277 boolean handled = false; 6278 ListenerInfo li = mListenerInfo; 6279 if (li != null && li.mOnContextClickListener != null) { 6280 handled = li.mOnContextClickListener.onContextClick(View.this); 6281 } 6282 if (handled) { 6283 performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK); 6284 } 6285 return handled; 6286 } 6287 6288 /** 6289 * Performs button-related actions during a touch down event. 6290 * 6291 * @param event The event. 6292 * @return True if the down was consumed. 6293 * 6294 * @hide 6295 */ 6296 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 6297 if (event.isFromSource(InputDevice.SOURCE_MOUSE) && 6298 (event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 6299 showContextMenu(event.getX(), event.getY()); 6300 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 6301 return true; 6302 } 6303 return false; 6304 } 6305 6306 /** 6307 * Shows the context menu for this view. 6308 * 6309 * @return {@code true} if the context menu was shown, {@code false} 6310 * otherwise 6311 * @see #showContextMenu(float, float) 6312 */ 6313 public boolean showContextMenu() { 6314 return getParent().showContextMenuForChild(this); 6315 } 6316 6317 /** 6318 * Shows the context menu for this view anchored to the specified 6319 * view-relative coordinate. 6320 * 6321 * @param x the X coordinate in pixels relative to the view to which the 6322 * menu should be anchored, or {@link Float#NaN} to disable anchoring 6323 * @param y the Y coordinate in pixels relative to the view to which the 6324 * menu should be anchored, or {@link Float#NaN} to disable anchoring 6325 * @return {@code true} if the context menu was shown, {@code false} 6326 * otherwise 6327 */ 6328 public boolean showContextMenu(float x, float y) { 6329 return getParent().showContextMenuForChild(this, x, y); 6330 } 6331 6332 /** 6333 * Start an action mode with the default type {@link ActionMode#TYPE_PRIMARY}. 6334 * 6335 * @param callback Callback that will control the lifecycle of the action mode 6336 * @return The new action mode if it is started, null otherwise 6337 * 6338 * @see ActionMode 6339 * @see #startActionMode(android.view.ActionMode.Callback, int) 6340 */ 6341 public ActionMode startActionMode(ActionMode.Callback callback) { 6342 return startActionMode(callback, ActionMode.TYPE_PRIMARY); 6343 } 6344 6345 /** 6346 * Start an action mode with the given type. 6347 * 6348 * @param callback Callback that will control the lifecycle of the action mode 6349 * @param type One of {@link ActionMode#TYPE_PRIMARY} or {@link ActionMode#TYPE_FLOATING}. 6350 * @return The new action mode if it is started, null otherwise 6351 * 6352 * @see ActionMode 6353 */ 6354 public ActionMode startActionMode(ActionMode.Callback callback, int type) { 6355 ViewParent parent = getParent(); 6356 if (parent == null) return null; 6357 try { 6358 return parent.startActionModeForChild(this, callback, type); 6359 } catch (AbstractMethodError ame) { 6360 // Older implementations of custom views might not implement this. 6361 return parent.startActionModeForChild(this, callback); 6362 } 6363 } 6364 6365 /** 6366 * Call {@link Context#startActivityForResult(String, Intent, int, Bundle)} for the View's 6367 * Context, creating a unique View identifier to retrieve the result. 6368 * 6369 * @param intent The Intent to be started. 6370 * @param requestCode The request code to use. 6371 * @hide 6372 */ 6373 public void startActivityForResult(Intent intent, int requestCode) { 6374 mStartActivityRequestWho = "@android:view:" + System.identityHashCode(this); 6375 getContext().startActivityForResult(mStartActivityRequestWho, intent, requestCode, null); 6376 } 6377 6378 /** 6379 * If this View corresponds to the calling who, dispatches the activity result. 6380 * @param who The identifier for the targeted View to receive the result. 6381 * @param requestCode The integer request code originally supplied to 6382 * startActivityForResult(), allowing you to identify who this 6383 * result came from. 6384 * @param resultCode The integer result code returned by the child activity 6385 * through its setResult(). 6386 * @param data An Intent, which can return result data to the caller 6387 * (various data can be attached to Intent "extras"). 6388 * @return {@code true} if the activity result was dispatched. 6389 * @hide 6390 */ 6391 public boolean dispatchActivityResult( 6392 String who, int requestCode, int resultCode, Intent data) { 6393 if (mStartActivityRequestWho != null && mStartActivityRequestWho.equals(who)) { 6394 onActivityResult(requestCode, resultCode, data); 6395 mStartActivityRequestWho = null; 6396 return true; 6397 } 6398 return false; 6399 } 6400 6401 /** 6402 * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. 6403 * 6404 * @param requestCode The integer request code originally supplied to 6405 * startActivityForResult(), allowing you to identify who this 6406 * result came from. 6407 * @param resultCode The integer result code returned by the child activity 6408 * through its setResult(). 6409 * @param data An Intent, which can return result data to the caller 6410 * (various data can be attached to Intent "extras"). 6411 * @hide 6412 */ 6413 public void onActivityResult(int requestCode, int resultCode, Intent data) { 6414 // Do nothing. 6415 } 6416 6417 /** 6418 * Register a callback to be invoked when a hardware key is pressed in this view. 6419 * Key presses in software input methods will generally not trigger the methods of 6420 * this listener. 6421 * @param l the key listener to attach to this view 6422 */ 6423 public void setOnKeyListener(OnKeyListener l) { 6424 getListenerInfo().mOnKeyListener = l; 6425 } 6426 6427 /** 6428 * Register a callback to be invoked when a touch event is sent to this view. 6429 * @param l the touch listener to attach to this view 6430 */ 6431 public void setOnTouchListener(OnTouchListener l) { 6432 getListenerInfo().mOnTouchListener = l; 6433 } 6434 6435 /** 6436 * Register a callback to be invoked when a generic motion event is sent to this view. 6437 * @param l the generic motion listener to attach to this view 6438 */ 6439 public void setOnGenericMotionListener(OnGenericMotionListener l) { 6440 getListenerInfo().mOnGenericMotionListener = l; 6441 } 6442 6443 /** 6444 * Register a callback to be invoked when a hover event is sent to this view. 6445 * @param l the hover listener to attach to this view 6446 */ 6447 public void setOnHoverListener(OnHoverListener l) { 6448 getListenerInfo().mOnHoverListener = l; 6449 } 6450 6451 /** 6452 * Register a drag event listener callback object for this View. The parameter is 6453 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 6454 * View, the system calls the 6455 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 6456 * @param l An implementation of {@link android.view.View.OnDragListener}. 6457 */ 6458 public void setOnDragListener(OnDragListener l) { 6459 getListenerInfo().mOnDragListener = l; 6460 } 6461 6462 /** 6463 * Give this view focus. This will cause 6464 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 6465 * 6466 * Note: this does not check whether this {@link View} should get focus, it just 6467 * gives it focus no matter what. It should only be called internally by framework 6468 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 6469 * 6470 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 6471 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 6472 * focus moved when requestFocus() is called. It may not always 6473 * apply, in which case use the default View.FOCUS_DOWN. 6474 * @param previouslyFocusedRect The rectangle of the view that had focus 6475 * prior in this View's coordinate system. 6476 */ 6477 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 6478 if (DBG) { 6479 System.out.println(this + " requestFocus()"); 6480 } 6481 6482 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 6483 mPrivateFlags |= PFLAG_FOCUSED; 6484 6485 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 6486 6487 if (mParent != null) { 6488 mParent.requestChildFocus(this, this); 6489 setFocusedInCluster(); 6490 } 6491 6492 if (mAttachInfo != null) { 6493 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 6494 } 6495 6496 onFocusChanged(true, direction, previouslyFocusedRect); 6497 refreshDrawableState(); 6498 } 6499 } 6500 6501 /** 6502 * Sets this view's preference for reveal behavior when it gains focus. 6503 * 6504 * <p>When set to true, this is a signal to ancestor views in the hierarchy that 6505 * this view would prefer to be brought fully into view when it gains focus. 6506 * For example, a text field that a user is meant to type into. Other views such 6507 * as scrolling containers may prefer to opt-out of this behavior.</p> 6508 * 6509 * <p>The default value for views is true, though subclasses may change this 6510 * based on their preferred behavior.</p> 6511 * 6512 * @param revealOnFocus true to request reveal on focus in ancestors, false otherwise 6513 * 6514 * @see #getRevealOnFocusHint() 6515 */ 6516 public final void setRevealOnFocusHint(boolean revealOnFocus) { 6517 if (revealOnFocus) { 6518 mPrivateFlags3 &= ~PFLAG3_NO_REVEAL_ON_FOCUS; 6519 } else { 6520 mPrivateFlags3 |= PFLAG3_NO_REVEAL_ON_FOCUS; 6521 } 6522 } 6523 6524 /** 6525 * Returns this view's preference for reveal behavior when it gains focus. 6526 * 6527 * <p>When this method returns true for a child view requesting focus, ancestor 6528 * views responding to a focus change in {@link ViewParent#requestChildFocus(View, View)} 6529 * should make a best effort to make the newly focused child fully visible to the user. 6530 * When it returns false, ancestor views should preferably not disrupt scroll positioning or 6531 * other properties affecting visibility to the user as part of the focus change.</p> 6532 * 6533 * @return true if this view would prefer to become fully visible when it gains focus, 6534 * false if it would prefer not to disrupt scroll positioning 6535 * 6536 * @see #setRevealOnFocusHint(boolean) 6537 */ 6538 public final boolean getRevealOnFocusHint() { 6539 return (mPrivateFlags3 & PFLAG3_NO_REVEAL_ON_FOCUS) == 0; 6540 } 6541 6542 /** 6543 * Populates <code>outRect</code> with the hotspot bounds. By default, 6544 * the hotspot bounds are identical to the screen bounds. 6545 * 6546 * @param outRect rect to populate with hotspot bounds 6547 * @hide Only for internal use by views and widgets. 6548 */ 6549 public void getHotspotBounds(Rect outRect) { 6550 final Drawable background = getBackground(); 6551 if (background != null) { 6552 background.getHotspotBounds(outRect); 6553 } else { 6554 getBoundsOnScreen(outRect); 6555 } 6556 } 6557 6558 /** 6559 * Request that a rectangle of this view be visible on the screen, 6560 * scrolling if necessary just enough. 6561 * 6562 * <p>A View should call this if it maintains some notion of which part 6563 * of its content is interesting. For example, a text editing view 6564 * should call this when its cursor moves. 6565 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6566 * It should not be affected by which part of the View is currently visible or its scroll 6567 * position. 6568 * 6569 * @param rectangle The rectangle in the View's content coordinate space 6570 * @return Whether any parent scrolled. 6571 */ 6572 public boolean requestRectangleOnScreen(Rect rectangle) { 6573 return requestRectangleOnScreen(rectangle, false); 6574 } 6575 6576 /** 6577 * Request that a rectangle of this view be visible on the screen, 6578 * scrolling if necessary just enough. 6579 * 6580 * <p>A View should call this if it maintains some notion of which part 6581 * of its content is interesting. For example, a text editing view 6582 * should call this when its cursor moves. 6583 * <p>The Rectangle passed into this method should be in the View's content coordinate space. 6584 * It should not be affected by which part of the View is currently visible or its scroll 6585 * position. 6586 * <p>When <code>immediate</code> is set to true, scrolling will not be 6587 * animated. 6588 * 6589 * @param rectangle The rectangle in the View's content coordinate space 6590 * @param immediate True to forbid animated scrolling, false otherwise 6591 * @return Whether any parent scrolled. 6592 */ 6593 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 6594 if (mParent == null) { 6595 return false; 6596 } 6597 6598 View child = this; 6599 6600 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 6601 position.set(rectangle); 6602 6603 ViewParent parent = mParent; 6604 boolean scrolled = false; 6605 while (parent != null) { 6606 rectangle.set((int) position.left, (int) position.top, 6607 (int) position.right, (int) position.bottom); 6608 6609 scrolled |= parent.requestChildRectangleOnScreen(child, rectangle, immediate); 6610 6611 if (!(parent instanceof View)) { 6612 break; 6613 } 6614 6615 // move it from child's content coordinate space to parent's content coordinate space 6616 position.offset(child.mLeft - child.getScrollX(), child.mTop -child.getScrollY()); 6617 6618 child = (View) parent; 6619 parent = child.getParent(); 6620 } 6621 6622 return scrolled; 6623 } 6624 6625 /** 6626 * Called when this view wants to give up focus. If focus is cleared 6627 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 6628 * <p> 6629 * <strong>Note:</strong> When a View clears focus the framework is trying 6630 * to give focus to the first focusable View from the top. Hence, if this 6631 * View is the first from the top that can take focus, then all callbacks 6632 * related to clearing focus will be invoked after which the framework will 6633 * give focus to this view. 6634 * </p> 6635 */ 6636 public void clearFocus() { 6637 if (DBG) { 6638 System.out.println(this + " clearFocus()"); 6639 } 6640 6641 clearFocusInternal(null, true, true); 6642 } 6643 6644 /** 6645 * Clears focus from the view, optionally propagating the change up through 6646 * the parent hierarchy and requesting that the root view place new focus. 6647 * 6648 * @param propagate whether to propagate the change up through the parent 6649 * hierarchy 6650 * @param refocus when propagate is true, specifies whether to request the 6651 * root view place new focus 6652 */ 6653 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 6654 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 6655 mPrivateFlags &= ~PFLAG_FOCUSED; 6656 6657 if (propagate && mParent != null) { 6658 mParent.clearChildFocus(this); 6659 } 6660 6661 onFocusChanged(false, 0, null); 6662 refreshDrawableState(); 6663 6664 if (propagate && (!refocus || !rootViewRequestFocus())) { 6665 notifyGlobalFocusCleared(this); 6666 } 6667 } 6668 } 6669 6670 void notifyGlobalFocusCleared(View oldFocus) { 6671 if (oldFocus != null && mAttachInfo != null) { 6672 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 6673 } 6674 } 6675 6676 boolean rootViewRequestFocus() { 6677 final View root = getRootView(); 6678 return root != null && root.requestFocus(); 6679 } 6680 6681 /** 6682 * Called internally by the view system when a new view is getting focus. 6683 * This is what clears the old focus. 6684 * <p> 6685 * <b>NOTE:</b> The parent view's focused child must be updated manually 6686 * after calling this method. Otherwise, the view hierarchy may be left in 6687 * an inconstent state. 6688 */ 6689 void unFocus(View focused) { 6690 if (DBG) { 6691 System.out.println(this + " unFocus()"); 6692 } 6693 6694 clearFocusInternal(focused, false, false); 6695 } 6696 6697 /** 6698 * Returns true if this view has focus itself, or is the ancestor of the 6699 * view that has focus. 6700 * 6701 * @return True if this view has or contains focus, false otherwise. 6702 */ 6703 @ViewDebug.ExportedProperty(category = "focus") 6704 public boolean hasFocus() { 6705 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6706 } 6707 6708 /** 6709 * Returns true if this view is focusable or if it contains a reachable View 6710 * for which {@link #hasFocusable()} returns {@code true}. A "reachable hasFocusable()" 6711 * is a view whose parents do not block descendants focus. 6712 * Only {@link #VISIBLE} views are considered focusable. 6713 * 6714 * <p>As of {@link Build.VERSION_CODES#O} views that are determined to be focusable 6715 * through {@link #FOCUSABLE_AUTO} will also cause this method to return {@code true}. 6716 * Apps that declare a {@link android.content.pm.ApplicationInfo#targetSdkVersion} of 6717 * earlier than {@link Build.VERSION_CODES#O} will continue to see this method return 6718 * {@code false} for views not explicitly marked as focusable. 6719 * Use {@link #hasExplicitFocusable()} if you require the pre-{@link Build.VERSION_CODES#O} 6720 * behavior.</p> 6721 * 6722 * @return {@code true} if the view is focusable or if the view contains a focusable 6723 * view, {@code false} otherwise 6724 * 6725 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 6726 * @see ViewGroup#getTouchscreenBlocksFocus() 6727 * @see #hasExplicitFocusable() 6728 */ 6729 public boolean hasFocusable() { 6730 return hasFocusable(!sHasFocusableExcludeAutoFocusable, false); 6731 } 6732 6733 /** 6734 * Returns true if this view is focusable or if it contains a reachable View 6735 * for which {@link #hasExplicitFocusable()} returns {@code true}. 6736 * A "reachable hasExplicitFocusable()" is a view whose parents do not block descendants focus. 6737 * Only {@link #VISIBLE} views for which {@link #getFocusable()} would return 6738 * {@link #FOCUSABLE} are considered focusable. 6739 * 6740 * <p>This method preserves the pre-{@link Build.VERSION_CODES#O} behavior of 6741 * {@link #hasFocusable()} in that only views explicitly set focusable will cause 6742 * this method to return true. A view set to {@link #FOCUSABLE_AUTO} that resolves 6743 * to focusable will not.</p> 6744 * 6745 * @return {@code true} if the view is focusable or if the view contains a focusable 6746 * view, {@code false} otherwise 6747 * 6748 * @see #hasFocusable() 6749 */ 6750 public boolean hasExplicitFocusable() { 6751 return hasFocusable(false, true); 6752 } 6753 6754 boolean hasFocusable(boolean allowAutoFocus, boolean dispatchExplicit) { 6755 if (!isFocusableInTouchMode()) { 6756 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 6757 final ViewGroup g = (ViewGroup) p; 6758 if (g.shouldBlockFocusForTouchscreen()) { 6759 return false; 6760 } 6761 } 6762 } 6763 6764 // Invisible and gone views are never focusable. 6765 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6766 return false; 6767 } 6768 6769 // Only use effective focusable value when allowed. 6770 if ((allowAutoFocus || getFocusable() != FOCUSABLE_AUTO) && isFocusable()) { 6771 return true; 6772 } 6773 6774 return false; 6775 } 6776 6777 /** 6778 * Called by the view system when the focus state of this view changes. 6779 * When the focus change event is caused by directional navigation, direction 6780 * and previouslyFocusedRect provide insight into where the focus is coming from. 6781 * When overriding, be sure to call up through to the super class so that 6782 * the standard focus handling will occur. 6783 * 6784 * @param gainFocus True if the View has focus; false otherwise. 6785 * @param direction The direction focus has moved when requestFocus() 6786 * is called to give this view focus. Values are 6787 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 6788 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 6789 * It may not always apply, in which case use the default. 6790 * @param previouslyFocusedRect The rectangle, in this view's coordinate 6791 * system, of the previously focused view. If applicable, this will be 6792 * passed in as finer grained information about where the focus is coming 6793 * from (in addition to direction). Will be <code>null</code> otherwise. 6794 */ 6795 @CallSuper 6796 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 6797 @Nullable Rect previouslyFocusedRect) { 6798 if (gainFocus) { 6799 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 6800 } else { 6801 notifyViewAccessibilityStateChangedIfNeeded( 6802 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6803 } 6804 6805 // Here we check whether we still need the default focus highlight, and switch it on/off. 6806 switchDefaultFocusHighlight(); 6807 6808 InputMethodManager imm = InputMethodManager.peekInstance(); 6809 if (!gainFocus) { 6810 if (isPressed()) { 6811 setPressed(false); 6812 } 6813 if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 6814 imm.focusOut(this); 6815 } 6816 onFocusLost(); 6817 } else if (imm != null && mAttachInfo != null && mAttachInfo.mHasWindowFocus) { 6818 imm.focusIn(this); 6819 } 6820 6821 invalidate(true); 6822 ListenerInfo li = mListenerInfo; 6823 if (li != null && li.mOnFocusChangeListener != null) { 6824 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 6825 } 6826 6827 if (mAttachInfo != null) { 6828 mAttachInfo.mKeyDispatchState.reset(this); 6829 } 6830 6831 notifyEnterOrExitForAutoFillIfNeeded(gainFocus); 6832 } 6833 6834 private void notifyEnterOrExitForAutoFillIfNeeded(boolean enter) { 6835 if (isAutofillable() && isAttachedToWindow() 6836 && getResolvedAutofillMode() == AUTOFILL_MODE_AUTO) { 6837 AutofillManager afm = getAutofillManager(); 6838 if (afm != null) { 6839 if (enter && hasWindowFocus() && isFocused()) { 6840 afm.notifyViewEntered(this); 6841 } else if (!hasWindowFocus() || !isFocused()) { 6842 afm.notifyViewExited(this); 6843 } 6844 } 6845 } 6846 } 6847 6848 /** 6849 * Sends an accessibility event of the given type. If accessibility is 6850 * not enabled this method has no effect. The default implementation calls 6851 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 6852 * to populate information about the event source (this View), then calls 6853 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 6854 * populate the text content of the event source including its descendants, 6855 * and last calls 6856 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 6857 * on its parent to request sending of the event to interested parties. 6858 * <p> 6859 * If an {@link AccessibilityDelegate} has been specified via calling 6860 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6861 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 6862 * responsible for handling this call. 6863 * </p> 6864 * 6865 * @param eventType The type of the event to send, as defined by several types from 6866 * {@link android.view.accessibility.AccessibilityEvent}, such as 6867 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 6868 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 6869 * 6870 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 6871 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6872 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 6873 * @see AccessibilityDelegate 6874 */ 6875 public void sendAccessibilityEvent(int eventType) { 6876 if (mAccessibilityDelegate != null) { 6877 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 6878 } else { 6879 sendAccessibilityEventInternal(eventType); 6880 } 6881 } 6882 6883 /** 6884 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 6885 * {@link AccessibilityEvent} to make an announcement which is related to some 6886 * sort of a context change for which none of the events representing UI transitions 6887 * is a good fit. For example, announcing a new page in a book. If accessibility 6888 * is not enabled this method does nothing. 6889 * 6890 * @param text The announcement text. 6891 */ 6892 public void announceForAccessibility(CharSequence text) { 6893 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 6894 AccessibilityEvent event = AccessibilityEvent.obtain( 6895 AccessibilityEvent.TYPE_ANNOUNCEMENT); 6896 onInitializeAccessibilityEvent(event); 6897 event.getText().add(text); 6898 event.setContentDescription(null); 6899 mParent.requestSendAccessibilityEvent(this, event); 6900 } 6901 } 6902 6903 /** 6904 * @see #sendAccessibilityEvent(int) 6905 * 6906 * Note: Called from the default {@link AccessibilityDelegate}. 6907 * 6908 * @hide 6909 */ 6910 public void sendAccessibilityEventInternal(int eventType) { 6911 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 6912 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 6913 } 6914 } 6915 6916 /** 6917 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 6918 * takes as an argument an empty {@link AccessibilityEvent} and does not 6919 * perform a check whether accessibility is enabled. 6920 * <p> 6921 * If an {@link AccessibilityDelegate} has been specified via calling 6922 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6923 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 6924 * is responsible for handling this call. 6925 * </p> 6926 * 6927 * @param event The event to send. 6928 * 6929 * @see #sendAccessibilityEvent(int) 6930 */ 6931 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 6932 if (mAccessibilityDelegate != null) { 6933 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 6934 } else { 6935 sendAccessibilityEventUncheckedInternal(event); 6936 } 6937 } 6938 6939 /** 6940 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 6941 * 6942 * Note: Called from the default {@link AccessibilityDelegate}. 6943 * 6944 * @hide 6945 */ 6946 public void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 6947 if (!isShown()) { 6948 return; 6949 } 6950 onInitializeAccessibilityEvent(event); 6951 // Only a subset of accessibility events populates text content. 6952 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 6953 dispatchPopulateAccessibilityEvent(event); 6954 } 6955 // In the beginning we called #isShown(), so we know that getParent() is not null. 6956 getParent().requestSendAccessibilityEvent(this, event); 6957 } 6958 6959 /** 6960 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 6961 * to its children for adding their text content to the event. Note that the 6962 * event text is populated in a separate dispatch path since we add to the 6963 * event not only the text of the source but also the text of all its descendants. 6964 * A typical implementation will call 6965 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 6966 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 6967 * on each child. Override this method if custom population of the event text 6968 * content is required. 6969 * <p> 6970 * If an {@link AccessibilityDelegate} has been specified via calling 6971 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 6972 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 6973 * is responsible for handling this call. 6974 * </p> 6975 * <p> 6976 * <em>Note:</em> Accessibility events of certain types are not dispatched for 6977 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 6978 * </p> 6979 * 6980 * @param event The event. 6981 * 6982 * @return True if the event population was completed. 6983 */ 6984 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 6985 if (mAccessibilityDelegate != null) { 6986 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 6987 } else { 6988 return dispatchPopulateAccessibilityEventInternal(event); 6989 } 6990 } 6991 6992 /** 6993 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 6994 * 6995 * Note: Called from the default {@link AccessibilityDelegate}. 6996 * 6997 * @hide 6998 */ 6999 public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 7000 onPopulateAccessibilityEvent(event); 7001 return false; 7002 } 7003 7004 /** 7005 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 7006 * giving a chance to this View to populate the accessibility event with its 7007 * text content. While this method is free to modify event 7008 * attributes other than text content, doing so should normally be performed in 7009 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 7010 * <p> 7011 * Example: Adding formatted date string to an accessibility event in addition 7012 * to the text added by the super implementation: 7013 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 7014 * super.onPopulateAccessibilityEvent(event); 7015 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 7016 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 7017 * mCurrentDate.getTimeInMillis(), flags); 7018 * event.getText().add(selectedDateUtterance); 7019 * }</pre> 7020 * <p> 7021 * If an {@link AccessibilityDelegate} has been specified via calling 7022 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7023 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 7024 * is responsible for handling this call. 7025 * </p> 7026 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 7027 * information to the event, in case the default implementation has basic information to add. 7028 * </p> 7029 * 7030 * @param event The accessibility event which to populate. 7031 * 7032 * @see #sendAccessibilityEvent(int) 7033 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7034 */ 7035 @CallSuper 7036 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 7037 if (mAccessibilityDelegate != null) { 7038 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 7039 } else { 7040 onPopulateAccessibilityEventInternal(event); 7041 } 7042 } 7043 7044 /** 7045 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 7046 * 7047 * Note: Called from the default {@link AccessibilityDelegate}. 7048 * 7049 * @hide 7050 */ 7051 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 7052 } 7053 7054 /** 7055 * Initializes an {@link AccessibilityEvent} with information about 7056 * this View which is the event source. In other words, the source of 7057 * an accessibility event is the view whose state change triggered firing 7058 * the event. 7059 * <p> 7060 * Example: Setting the password property of an event in addition 7061 * to properties set by the super implementation: 7062 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 7063 * super.onInitializeAccessibilityEvent(event); 7064 * event.setPassword(true); 7065 * }</pre> 7066 * <p> 7067 * If an {@link AccessibilityDelegate} has been specified via calling 7068 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7069 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 7070 * is responsible for handling this call. 7071 * </p> 7072 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 7073 * information to the event, in case the default implementation has basic information to add. 7074 * </p> 7075 * @param event The event to initialize. 7076 * 7077 * @see #sendAccessibilityEvent(int) 7078 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 7079 */ 7080 @CallSuper 7081 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 7082 if (mAccessibilityDelegate != null) { 7083 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 7084 } else { 7085 onInitializeAccessibilityEventInternal(event); 7086 } 7087 } 7088 7089 /** 7090 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 7091 * 7092 * Note: Called from the default {@link AccessibilityDelegate}. 7093 * 7094 * @hide 7095 */ 7096 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 7097 event.setSource(this); 7098 event.setClassName(getAccessibilityClassName()); 7099 event.setPackageName(getContext().getPackageName()); 7100 event.setEnabled(isEnabled()); 7101 event.setContentDescription(mContentDescription); 7102 7103 switch (event.getEventType()) { 7104 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 7105 ArrayList<View> focusablesTempList = (mAttachInfo != null) 7106 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 7107 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 7108 event.setItemCount(focusablesTempList.size()); 7109 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 7110 if (mAttachInfo != null) { 7111 focusablesTempList.clear(); 7112 } 7113 } break; 7114 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 7115 CharSequence text = getIterableTextForAccessibility(); 7116 if (text != null && text.length() > 0) { 7117 event.setFromIndex(getAccessibilitySelectionStart()); 7118 event.setToIndex(getAccessibilitySelectionEnd()); 7119 event.setItemCount(text.length()); 7120 } 7121 } break; 7122 } 7123 } 7124 7125 /** 7126 * Returns an {@link AccessibilityNodeInfo} representing this view from the 7127 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 7128 * This method is responsible for obtaining an accessibility node info from a 7129 * pool of reusable instances and calling 7130 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 7131 * initialize the former. 7132 * <p> 7133 * Note: The client is responsible for recycling the obtained instance by calling 7134 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 7135 * </p> 7136 * 7137 * @return A populated {@link AccessibilityNodeInfo}. 7138 * 7139 * @see AccessibilityNodeInfo 7140 */ 7141 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 7142 if (mAccessibilityDelegate != null) { 7143 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 7144 } else { 7145 return createAccessibilityNodeInfoInternal(); 7146 } 7147 } 7148 7149 /** 7150 * @see #createAccessibilityNodeInfo() 7151 * 7152 * @hide 7153 */ 7154 public AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 7155 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 7156 if (provider != null) { 7157 return provider.createAccessibilityNodeInfo(AccessibilityNodeProvider.HOST_VIEW_ID); 7158 } else { 7159 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 7160 onInitializeAccessibilityNodeInfo(info); 7161 return info; 7162 } 7163 } 7164 7165 /** 7166 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 7167 * The base implementation sets: 7168 * <ul> 7169 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 7170 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 7171 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 7172 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 7173 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 7174 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 7175 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 7176 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 7177 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 7178 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 7179 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 7180 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 7181 * <li>{@link AccessibilityNodeInfo#setContextClickable(boolean)}</li> 7182 * </ul> 7183 * <p> 7184 * Subclasses should override this method, call the super implementation, 7185 * and set additional attributes. 7186 * </p> 7187 * <p> 7188 * If an {@link AccessibilityDelegate} has been specified via calling 7189 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 7190 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 7191 * is responsible for handling this call. 7192 * </p> 7193 * 7194 * @param info The instance to initialize. 7195 */ 7196 @CallSuper 7197 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 7198 if (mAccessibilityDelegate != null) { 7199 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 7200 } else { 7201 onInitializeAccessibilityNodeInfoInternal(info); 7202 } 7203 } 7204 7205 /** 7206 * Gets the location of this view in screen coordinates. 7207 * 7208 * @param outRect The output location 7209 * @hide 7210 */ 7211 public void getBoundsOnScreen(Rect outRect) { 7212 getBoundsOnScreen(outRect, false); 7213 } 7214 7215 /** 7216 * Gets the location of this view in screen coordinates. 7217 * 7218 * @param outRect The output location 7219 * @param clipToParent Whether to clip child bounds to the parent ones. 7220 * @hide 7221 */ 7222 public void getBoundsOnScreen(Rect outRect, boolean clipToParent) { 7223 if (mAttachInfo == null) { 7224 return; 7225 } 7226 7227 RectF position = mAttachInfo.mTmpTransformRect; 7228 position.set(0, 0, mRight - mLeft, mBottom - mTop); 7229 7230 if (!hasIdentityMatrix()) { 7231 getMatrix().mapRect(position); 7232 } 7233 7234 position.offset(mLeft, mTop); 7235 7236 ViewParent parent = mParent; 7237 while (parent instanceof View) { 7238 View parentView = (View) parent; 7239 7240 position.offset(-parentView.mScrollX, -parentView.mScrollY); 7241 7242 if (clipToParent) { 7243 position.left = Math.max(position.left, 0); 7244 position.top = Math.max(position.top, 0); 7245 position.right = Math.min(position.right, parentView.getWidth()); 7246 position.bottom = Math.min(position.bottom, parentView.getHeight()); 7247 } 7248 7249 if (!parentView.hasIdentityMatrix()) { 7250 parentView.getMatrix().mapRect(position); 7251 } 7252 7253 position.offset(parentView.mLeft, parentView.mTop); 7254 7255 parent = parentView.mParent; 7256 } 7257 7258 if (parent instanceof ViewRootImpl) { 7259 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 7260 position.offset(0, -viewRootImpl.mCurScrollY); 7261 } 7262 7263 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 7264 7265 outRect.set(Math.round(position.left), Math.round(position.top), 7266 Math.round(position.right), Math.round(position.bottom)); 7267 } 7268 7269 /** 7270 * Return the class name of this object to be used for accessibility purposes. 7271 * Subclasses should only override this if they are implementing something that 7272 * should be seen as a completely new class of view when used by accessibility, 7273 * unrelated to the class it is deriving from. This is used to fill in 7274 * {@link AccessibilityNodeInfo#setClassName AccessibilityNodeInfo.setClassName}. 7275 */ 7276 public CharSequence getAccessibilityClassName() { 7277 return View.class.getName(); 7278 } 7279 7280 /** 7281 * Called when assist structure is being retrieved from a view as part of 7282 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData}. 7283 * @param structure Fill in with structured view data. The default implementation 7284 * fills in all data that can be inferred from the view itself. 7285 */ 7286 public void onProvideStructure(ViewStructure structure) { 7287 onProvideStructureForAssistOrAutofill(structure, false); 7288 } 7289 7290 /** 7291 * Called when assist structure is being retrieved from a view as part of an autofill request. 7292 * 7293 * <p>This method already provides most of what's needed for autofill, but should be overridden 7294 * when: 7295 * <ol> 7296 * <li>The view contents does not include PII (Personally Identifiable Information), so it 7297 * can call {@link ViewStructure#setDataIsSensitive(boolean)} passing {@code false}. 7298 * <li>It must set fields such {@link ViewStructure#setText(CharSequence)}, 7299 * {@link ViewStructure#setAutofillOptions(String[])}, or {@link ViewStructure#setUrl(String)}. 7300 * </ol> 7301 * 7302 * @param structure Fill in with structured view data. The default implementation 7303 * fills in all data that can be inferred from the view itself. 7304 * @param flags optional flags (currently {@code 0}). 7305 */ 7306 public void onProvideAutofillStructure(ViewStructure structure, int flags) { 7307 onProvideStructureForAssistOrAutofill(structure, true); 7308 } 7309 7310 private void setAutofillId(ViewStructure structure) { 7311 // The autofill id needs to be unique, but its value doesn't matter, 7312 // so it's better to reuse the accessibility id to save space. 7313 structure.setAutofillId(getAccessibilityViewId()); 7314 } 7315 7316 private void onProvideStructureForAssistOrAutofill(ViewStructure structure, 7317 boolean forAutofill) { 7318 final int id = mID; 7319 if (id != NO_ID && !isViewIdGenerated(id)) { 7320 String pkg, type, entry; 7321 try { 7322 final Resources res = getResources(); 7323 entry = res.getResourceEntryName(id); 7324 type = res.getResourceTypeName(id); 7325 pkg = res.getResourcePackageName(id); 7326 } catch (Resources.NotFoundException e) { 7327 entry = type = pkg = null; 7328 } 7329 structure.setId(id, pkg, type, entry); 7330 } else { 7331 structure.setId(id, null, null, null); 7332 } 7333 7334 if (forAutofill) { 7335 setAutofillId(structure); 7336 final @AutofillType int autofillType = getAutofillType(); 7337 // Don't need to fill autofill info if view does not support it. 7338 // For example, only TextViews that are editable support autofill 7339 if (autofillType != AUTOFILL_TYPE_NONE) { 7340 structure.setAutofillType(autofillType); 7341 structure.setAutofillHints(getAutofillHints()); 7342 structure.setAutofillValue(getAutofillValue()); 7343 } 7344 } 7345 7346 structure.setDimens(mLeft, mTop, mScrollX, mScrollY, mRight - mLeft, mBottom - mTop); 7347 if (!hasIdentityMatrix()) { 7348 structure.setTransformation(getMatrix()); 7349 } 7350 structure.setElevation(getZ()); 7351 structure.setVisibility(getVisibility()); 7352 structure.setEnabled(isEnabled()); 7353 if (isClickable()) { 7354 structure.setClickable(true); 7355 } 7356 if (isFocusable()) { 7357 structure.setFocusable(true); 7358 } 7359 if (isFocused()) { 7360 structure.setFocused(true); 7361 } 7362 if (isAccessibilityFocused()) { 7363 structure.setAccessibilityFocused(true); 7364 } 7365 if (isSelected()) { 7366 structure.setSelected(true); 7367 } 7368 if (isActivated()) { 7369 structure.setActivated(true); 7370 } 7371 if (isLongClickable()) { 7372 structure.setLongClickable(true); 7373 } 7374 if (this instanceof Checkable) { 7375 structure.setCheckable(true); 7376 if (((Checkable)this).isChecked()) { 7377 structure.setChecked(true); 7378 } 7379 } 7380 if (isOpaque()) { 7381 structure.setOpaque(true); 7382 } 7383 if (isContextClickable()) { 7384 structure.setContextClickable(true); 7385 } 7386 structure.setClassName(getAccessibilityClassName().toString()); 7387 structure.setContentDescription(getContentDescription()); 7388 } 7389 7390 /** 7391 * Called when assist structure is being retrieved from a view as part of 7392 * {@link android.app.Activity#onProvideAssistData Activity.onProvideAssistData} to 7393 * generate additional virtual structure under this view. The defaullt implementation 7394 * uses {@link #getAccessibilityNodeProvider()} to try to generate this from the 7395 * view's virtual accessibility nodes, if any. You can override this for a more 7396 * optimal implementation providing this data. 7397 */ 7398 public void onProvideVirtualStructure(ViewStructure structure) { 7399 onProvideVirtualStructureForAssistOrAutofill(structure, false); 7400 } 7401 7402 /** 7403 * Called when assist structure is being retrieved from a view as part of an autofill request 7404 * to generate additional virtual structure under this view. 7405 * 7406 * <p>The default implementation uses {@link #getAccessibilityNodeProvider()} to try to 7407 * generate this from the view's virtual accessibility nodes, if any. You can override this 7408 * for a more optimal implementation providing this data. 7409 * 7410 * <p>When implementing this method, subclasses must follow the rules below: 7411 * 7412 * <ol> 7413 * <li>Also implement {@link #autofill(SparseArray)} to autofill the virtual 7414 * children. 7415 * <li>Call 7416 * {@link android.view.autofill.AutofillManager#notifyViewEntered} and 7417 * {@link android.view.autofill.AutofillManager#notifyViewExited(View, int)} 7418 * when the focus inside the view changed. 7419 * <li>Call {@link android.view.autofill.AutofillManager#notifyValueChanged(View, int, 7420 * AutofillValue)} when the value of a child changed. 7421 * <li>Call {@link AutofillManager#commit()} when the autofill context 7422 * of the view structure changed and you want the current autofill interaction if such 7423 * to be commited. 7424 * <li>Call {@link AutofillManager#cancel()} ()} when the autofill context 7425 * of the view structure changed and you want the current autofill interaction if such 7426 * to be cancelled. 7427 * </ol> 7428 * 7429 * @param structure Fill in with structured view data. 7430 * @param flags optional flags (currently {@code 0}). 7431 */ 7432 public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) { 7433 onProvideVirtualStructureForAssistOrAutofill(structure, true); 7434 } 7435 7436 private void onProvideVirtualStructureForAssistOrAutofill(ViewStructure structure, 7437 boolean forAutofill) { 7438 if (forAutofill) { 7439 setAutofillId(structure); 7440 } 7441 // NOTE: currently flags are only used for AutoFill; if they're used for Assist as well, 7442 // this method should take a boolean with the type of request. 7443 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 7444 if (provider != null) { 7445 AccessibilityNodeInfo info = createAccessibilityNodeInfo(); 7446 structure.setChildCount(1); 7447 ViewStructure root = structure.newChild(0); 7448 populateVirtualStructure(root, provider, info, forAutofill); 7449 info.recycle(); 7450 } 7451 } 7452 7453 /** 7454 * Automatically fills the content of this view with the {@code value}. 7455 * 7456 * <p>By default does nothing, but views should override it (and {@link #getAutofillType()}, 7457 * {@link #getAutofillValue()}, and {@link #onProvideAutofillStructure(ViewStructure, int)} 7458 * to support the Autofill Framework. 7459 * 7460 * <p>Typically, it is implemented by: 7461 * 7462 * <ol> 7463 * <li>Calling the proper getter method on {@link AutofillValue} to fetch the actual value. 7464 * <li>Passing the actual value to the equivalent setter in the view. 7465 * <ol> 7466 * 7467 * <p>For example, a text-field view would call: 7468 * 7469 * <pre class="prettyprint"> 7470 * CharSequence text = value.getTextValue(); 7471 * if (text != null) { 7472 * setText(text); 7473 * } 7474 * </pre> 7475 * 7476 * @param value value to be autofilled. 7477 */ 7478 public void autofill(@SuppressWarnings("unused") AutofillValue value) { 7479 } 7480 7481 /** 7482 * Automatically fills the content of a virtual views. 7483 * 7484 * <p>See {@link #autofill(AutofillValue)} and 7485 * {@link #onProvideAutofillVirtualStructure(ViewStructure, int)} for more info. 7486 * 7487 * @param values map of values to be autofilled, keyed by virtual child id. 7488 */ 7489 public void autofill(@NonNull @SuppressWarnings("unused") SparseArray<AutofillValue> values) { 7490 } 7491 7492 /** 7493 * Describes the autofill type that should be used on calls to 7494 * {@link #autofill(AutofillValue)} and {@link #autofill(SparseArray)}. 7495 * 7496 * <p>By default returns {@link #AUTOFILL_TYPE_NONE}, but views should override it (and 7497 * {@link #autofill(AutofillValue)} to support the Autofill Framework. 7498 */ 7499 public @AutofillType int getAutofillType() { 7500 return AUTOFILL_TYPE_NONE; 7501 } 7502 7503 /** 7504 * Describes the content of a view so that a autofill service can fill in the appropriate data. 7505 * 7506 * @return The hints set via the attribute or {@code null} if no hint it set. 7507 * 7508 * @attr ref android.R.styleable#View_autofillHints 7509 */ 7510 @ViewDebug.ExportedProperty() 7511 @Nullable public String[] getAutofillHints() { 7512 return mAutofillHints; 7513 } 7514 7515 /** 7516 * Gets the {@link View}'s current autofill value. 7517 * 7518 * <p>By default returns {@code null}, but views should override it (and 7519 * {@link #autofill(AutofillValue)}, and {@link #getAutofillType()} to support the Autofill 7520 * Framework. 7521 */ 7522 @Nullable 7523 public AutofillValue getAutofillValue() { 7524 return null; 7525 } 7526 7527 /** 7528 * Gets the mode for determining whether this View is important for autofill. 7529 * 7530 * <p>See {@link #setImportantForAutofill(int)} for more info about this mode. 7531 * 7532 * @return {@link #IMPORTANT_FOR_AUTOFILL_AUTO} by default, or value passed to 7533 * {@link #setImportantForAutofill(int)}. 7534 * 7535 * @attr ref android.R.styleable#View_importantForAutofill 7536 */ 7537 @ViewDebug.ExportedProperty(mapping = { 7538 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_AUTO, to = "auto"), 7539 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_YES, to = "yes"), 7540 @ViewDebug.IntToString(from = IMPORTANT_FOR_AUTOFILL_NO, to = "no")}) 7541 public @AutofillImportance int getImportantForAutofill() { 7542 return (mPrivateFlags3 7543 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK) >> PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT; 7544 } 7545 7546 /** 7547 * Sets the mode for determining whether this View is important for autofill. 7548 * 7549 * <p>See {@link #setImportantForAutofill(int)} for more info about this mode. 7550 * 7551 * @param mode {@link #IMPORTANT_FOR_AUTOFILL_AUTO}, {@link #IMPORTANT_FOR_AUTOFILL_YES}, 7552 * or {@link #IMPORTANT_FOR_AUTOFILL_NO}. 7553 * 7554 * @attr ref android.R.styleable#View_importantForAutofill 7555 */ 7556 public void setImportantForAutofill(@AutofillImportance int mode) { 7557 mPrivateFlags3 &= ~PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK; 7558 mPrivateFlags3 |= (mode << PFLAG3_IMPORTANT_FOR_AUTOFILL_SHIFT) 7559 & PFLAG3_IMPORTANT_FOR_AUTOFILL_MASK; 7560 } 7561 7562 /** 7563 * Hints the Android System whether the {@link android.app.assist.AssistStructure.ViewNode} 7564 * associated with this View should be included in a {@link ViewStructure} used for 7565 * autofill purposes. 7566 * 7567 * <p>Generally speaking, a view is important for autofill if: 7568 * <ol> 7569 * <li>The view can-be autofilled by an {@link android.service.autofill.AutofillService}. 7570 * <li>The view contents can help an {@link android.service.autofill.AutofillService} to 7571 * autofill other views. 7572 * <ol> 7573 * 7574 * <p>For example, view containers should typically return {@code false} for performance reasons 7575 * (since the important info is provided by their children), but if the container is actually 7576 * whose children are part of a compound view, it should return {@code true} (and then override 7577 * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call 7578 * {@link #onProvideAutofillStructure(ViewStructure, int)} so its children are not included in 7579 * the structure). On the other hand, views representing labels or editable fields should 7580 * typically return {@code true}, but in some cases they could return {@code false} (for 7581 * example, if they're part of a "Captcha" mechanism). 7582 * 7583 * <p>By default, this method returns {@code true} if {@link #getImportantForAutofill()} returns 7584 * {@link #IMPORTANT_FOR_AUTOFILL_YES}, {@code false } if it returns 7585 * {@link #IMPORTANT_FOR_AUTOFILL_NO}, and use some heuristics to define the importance when it 7586 * returns {@link #IMPORTANT_FOR_AUTOFILL_AUTO}. Hence, it should rarely be overridden - Views 7587 * should use {@link #setImportantForAutofill(int)} instead. 7588 * 7589 * <p><strong>Note:</strong> returning {@code false} does not guarantee the view will be 7590 * excluded from the structure; for example, if the user explicitly requested auto-fill, the 7591 * View might be always included. 7592 * 7593 * <p>This decision applies just for the view, not its children - if the view children are not 7594 * important for autofill, the view should override 7595 * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} to simply call 7596 * {@link #onProvideAutofillStructure(ViewStructure, int)} (instead of calling 7597 * {@link #dispatchProvideAutofillStructure(ViewStructure, int)} for each child). 7598 * 7599 * @return whether the view is considered important for autofill. 7600 * 7601 * @see #IMPORTANT_FOR_AUTOFILL_AUTO 7602 * @see #IMPORTANT_FOR_AUTOFILL_YES 7603 * @see #IMPORTANT_FOR_AUTOFILL_NO 7604 */ 7605 public final boolean isImportantForAutofill() { 7606 final int flag = getImportantForAutofill(); 7607 7608 // First, check if view explicity set it to YES or NO 7609 if ((flag & IMPORTANT_FOR_AUTOFILL_YES) != 0) { 7610 return true; 7611 } 7612 if ((flag & IMPORTANT_FOR_AUTOFILL_NO) != 0) { 7613 return false; 7614 } 7615 7616 // Then use some heuristics to handle AUTO. 7617 7618 // Always include views that have a explicity resource id. 7619 final int id = mID; 7620 if (id != NO_ID && !isViewIdGenerated(id)) { 7621 final Resources res = getResources(); 7622 String entry = null; 7623 String pkg = null; 7624 try { 7625 entry = res.getResourceEntryName(id); 7626 pkg = res.getResourcePackageName(id); 7627 } catch (Resources.NotFoundException e) { 7628 // ignore 7629 } 7630 if (entry != null && pkg != null && pkg.equals(mContext.getPackageName())) { 7631 return true; 7632 } 7633 } 7634 7635 // Otherwise, assume it's not important... 7636 return false; 7637 } 7638 7639 @Nullable 7640 private AutofillManager getAutofillManager() { 7641 return mContext.getSystemService(AutofillManager.class); 7642 } 7643 7644 private boolean isAutofillable() { 7645 return getAutofillType() != AUTOFILL_TYPE_NONE && !isAutofillBlocked(); 7646 } 7647 7648 private void populateVirtualStructure(ViewStructure structure, 7649 AccessibilityNodeProvider provider, AccessibilityNodeInfo info, boolean forAutofill) { 7650 structure.setId(AccessibilityNodeInfo.getVirtualDescendantId(info.getSourceNodeId()), 7651 null, null, null); 7652 Rect rect = structure.getTempRect(); 7653 info.getBoundsInParent(rect); 7654 structure.setDimens(rect.left, rect.top, 0, 0, rect.width(), rect.height()); 7655 structure.setVisibility(VISIBLE); 7656 structure.setEnabled(info.isEnabled()); 7657 if (info.isClickable()) { 7658 structure.setClickable(true); 7659 } 7660 if (info.isFocusable()) { 7661 structure.setFocusable(true); 7662 } 7663 if (info.isFocused()) { 7664 structure.setFocused(true); 7665 } 7666 if (info.isAccessibilityFocused()) { 7667 structure.setAccessibilityFocused(true); 7668 } 7669 if (info.isSelected()) { 7670 structure.setSelected(true); 7671 } 7672 if (info.isLongClickable()) { 7673 structure.setLongClickable(true); 7674 } 7675 if (info.isCheckable()) { 7676 structure.setCheckable(true); 7677 if (info.isChecked()) { 7678 structure.setChecked(true); 7679 } 7680 } 7681 if (info.isContextClickable()) { 7682 structure.setContextClickable(true); 7683 } 7684 CharSequence cname = info.getClassName(); 7685 structure.setClassName(cname != null ? cname.toString() : null); 7686 structure.setContentDescription(info.getContentDescription()); 7687 if (!forAutofill && (info.getText() != null || info.getError() != null)) { 7688 // TODO(b/33197203) (b/33269702): when sanitized, try to use the Accessibility API to 7689 // just set sanitized values (like text coming from resource files), rather than not 7690 // setting it at all. 7691 structure.setText(info.getText(), info.getTextSelectionStart(), 7692 info.getTextSelectionEnd()); 7693 } 7694 final int NCHILDREN = info.getChildCount(); 7695 if (NCHILDREN > 0) { 7696 structure.setChildCount(NCHILDREN); 7697 for (int i=0; i<NCHILDREN; i++) { 7698 AccessibilityNodeInfo cinfo = provider.createAccessibilityNodeInfo( 7699 AccessibilityNodeInfo.getVirtualDescendantId(info.getChildId(i))); 7700 ViewStructure child = structure.newChild(i); 7701 if (forAutofill) { 7702 // TODO(b/33197203): add CTS test to autofill virtual children based on 7703 // Accessibility API. 7704 child.setAutofillId(structure, i); 7705 } 7706 populateVirtualStructure(child, provider, cinfo, forAutofill); 7707 cinfo.recycle(); 7708 } 7709 } 7710 } 7711 7712 /** 7713 * Dispatch creation of {@link ViewStructure} down the hierarchy. The default 7714 * implementation calls {@link #onProvideStructure} and 7715 * {@link #onProvideVirtualStructure}. 7716 */ 7717 public void dispatchProvideStructure(ViewStructure structure) { 7718 dispatchProvideStructureForAssistOrAutofill(structure, false); 7719 } 7720 7721 /** 7722 * Dispatch creation of {@link ViewStructure} down the hierarchy. 7723 * 7724 * <p>The structure must be filled according to the request type, which is set in the 7725 * {@code flags} parameter - see the documentation on each flag for more details. 7726 * 7727 * <p>The default implementation calls {@link #onProvideAutofillStructure(ViewStructure, int)} 7728 * and {@link #onProvideAutofillVirtualStructure(ViewStructure, int)}. 7729 * 7730 * @param structure Fill in with structured view data. 7731 * @param flags optional flags (currently {@code 0}). 7732 */ 7733 public void dispatchProvideAutofillStructure(ViewStructure structure, int flags) { 7734 dispatchProvideStructureForAssistOrAutofill(structure, true); 7735 } 7736 7737 private void dispatchProvideStructureForAssistOrAutofill(ViewStructure structure, 7738 boolean forAutofill) { 7739 boolean blocked = forAutofill ? isAutofillBlocked() : isAssistBlocked(); 7740 if (!blocked) { 7741 if (forAutofill) { 7742 setAutofillId(structure); 7743 // NOTE: flags are not currently supported, hence 0 7744 onProvideAutofillStructure(structure, 0); 7745 onProvideAutofillVirtualStructure(structure, 0); 7746 } else { 7747 onProvideStructure(structure); 7748 onProvideVirtualStructure(structure); 7749 } 7750 } else { 7751 structure.setClassName(getAccessibilityClassName().toString()); 7752 structure.setAssistBlocked(true); 7753 } 7754 } 7755 7756 /** 7757 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 7758 * 7759 * Note: Called from the default {@link AccessibilityDelegate}. 7760 * 7761 * @hide 7762 */ 7763 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 7764 if (mAttachInfo == null) { 7765 return; 7766 } 7767 7768 Rect bounds = mAttachInfo.mTmpInvalRect; 7769 7770 getDrawingRect(bounds); 7771 info.setBoundsInParent(bounds); 7772 7773 getBoundsOnScreen(bounds, true); 7774 info.setBoundsInScreen(bounds); 7775 7776 ViewParent parent = getParentForAccessibility(); 7777 if (parent instanceof View) { 7778 info.setParent((View) parent); 7779 } 7780 7781 if (mID != View.NO_ID) { 7782 View rootView = getRootView(); 7783 if (rootView == null) { 7784 rootView = this; 7785 } 7786 7787 View label = rootView.findLabelForView(this, mID); 7788 if (label != null) { 7789 info.setLabeledBy(label); 7790 } 7791 7792 if ((mAttachInfo.mAccessibilityFetchFlags 7793 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 7794 && Resources.resourceHasPackage(mID)) { 7795 try { 7796 String viewId = getResources().getResourceName(mID); 7797 info.setViewIdResourceName(viewId); 7798 } catch (Resources.NotFoundException nfe) { 7799 /* ignore */ 7800 } 7801 } 7802 } 7803 7804 if (mLabelForId != View.NO_ID) { 7805 View rootView = getRootView(); 7806 if (rootView == null) { 7807 rootView = this; 7808 } 7809 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 7810 if (labeled != null) { 7811 info.setLabelFor(labeled); 7812 } 7813 } 7814 7815 if (mAccessibilityTraversalBeforeId != View.NO_ID) { 7816 View rootView = getRootView(); 7817 if (rootView == null) { 7818 rootView = this; 7819 } 7820 View next = rootView.findViewInsideOutShouldExist(this, 7821 mAccessibilityTraversalBeforeId); 7822 if (next != null && next.includeForAccessibility()) { 7823 info.setTraversalBefore(next); 7824 } 7825 } 7826 7827 if (mAccessibilityTraversalAfterId != View.NO_ID) { 7828 View rootView = getRootView(); 7829 if (rootView == null) { 7830 rootView = this; 7831 } 7832 View next = rootView.findViewInsideOutShouldExist(this, 7833 mAccessibilityTraversalAfterId); 7834 if (next != null && next.includeForAccessibility()) { 7835 info.setTraversalAfter(next); 7836 } 7837 } 7838 7839 info.setVisibleToUser(isVisibleToUser()); 7840 7841 info.setImportantForAccessibility(isImportantForAccessibility()); 7842 info.setPackageName(mContext.getPackageName()); 7843 info.setClassName(getAccessibilityClassName()); 7844 info.setContentDescription(getContentDescription()); 7845 7846 info.setEnabled(isEnabled()); 7847 info.setClickable(isClickable()); 7848 info.setFocusable(isFocusable()); 7849 info.setFocused(isFocused()); 7850 info.setAccessibilityFocused(isAccessibilityFocused()); 7851 info.setSelected(isSelected()); 7852 info.setLongClickable(isLongClickable()); 7853 info.setContextClickable(isContextClickable()); 7854 info.setLiveRegion(getAccessibilityLiveRegion()); 7855 7856 // TODO: These make sense only if we are in an AdapterView but all 7857 // views can be selected. Maybe from accessibility perspective 7858 // we should report as selectable view in an AdapterView. 7859 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 7860 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 7861 7862 if (isFocusable()) { 7863 if (isFocused()) { 7864 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 7865 } else { 7866 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 7867 } 7868 } 7869 7870 if (!isAccessibilityFocused()) { 7871 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 7872 } else { 7873 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 7874 } 7875 7876 if (isClickable() && isEnabled()) { 7877 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 7878 } 7879 7880 if (isLongClickable() && isEnabled()) { 7881 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 7882 } 7883 7884 if (isContextClickable() && isEnabled()) { 7885 info.addAction(AccessibilityAction.ACTION_CONTEXT_CLICK); 7886 } 7887 7888 CharSequence text = getIterableTextForAccessibility(); 7889 if (text != null && text.length() > 0) { 7890 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 7891 7892 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 7893 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 7894 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 7895 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 7896 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 7897 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 7898 } 7899 7900 info.addAction(AccessibilityAction.ACTION_SHOW_ON_SCREEN); 7901 populateAccessibilityNodeInfoDrawingOrderInParent(info); 7902 } 7903 7904 /** 7905 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the 7906 * additional data. 7907 * <p> 7908 * This method only needs overloading if the node is marked as having extra data available. 7909 * </p> 7910 * 7911 * @param info The info to which to add the extra data. Never {@code null}. 7912 * @param extraDataKey A key specifying the type of extra data to add to the info. The 7913 * extra data should be added to the {@link Bundle} returned by 7914 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never 7915 * {@code null}. 7916 * @param arguments A {@link Bundle} holding any arguments relevant for this request. May be 7917 * {@code null} if the service provided no arguments. 7918 * 7919 * @see AccessibilityNodeInfo#setAvailableExtraData(List) 7920 */ 7921 public void addExtraDataToAccessibilityNodeInfo( 7922 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey, 7923 @Nullable Bundle arguments) { 7924 } 7925 7926 /** 7927 * Determine the order in which this view will be drawn relative to its siblings for a11y 7928 * 7929 * @param info The info whose drawing order should be populated 7930 */ 7931 private void populateAccessibilityNodeInfoDrawingOrderInParent(AccessibilityNodeInfo info) { 7932 /* 7933 * If the view's bounds haven't been set yet, layout has not completed. In that situation, 7934 * drawing order may not be well-defined, and some Views with custom drawing order may 7935 * not be initialized sufficiently to respond properly getChildDrawingOrder. 7936 */ 7937 if ((mPrivateFlags & PFLAG_HAS_BOUNDS) == 0) { 7938 info.setDrawingOrder(0); 7939 return; 7940 } 7941 int drawingOrderInParent = 1; 7942 // Iterate up the hierarchy if parents are not important for a11y 7943 View viewAtDrawingLevel = this; 7944 final ViewParent parent = getParentForAccessibility(); 7945 while (viewAtDrawingLevel != parent) { 7946 final ViewParent currentParent = viewAtDrawingLevel.getParent(); 7947 if (!(currentParent instanceof ViewGroup)) { 7948 // Should only happen for the Decor 7949 drawingOrderInParent = 0; 7950 break; 7951 } else { 7952 final ViewGroup parentGroup = (ViewGroup) currentParent; 7953 final int childCount = parentGroup.getChildCount(); 7954 if (childCount > 1) { 7955 List<View> preorderedList = parentGroup.buildOrderedChildList(); 7956 if (preorderedList != null) { 7957 final int childDrawIndex = preorderedList.indexOf(viewAtDrawingLevel); 7958 for (int i = 0; i < childDrawIndex; i++) { 7959 drawingOrderInParent += numViewsForAccessibility(preorderedList.get(i)); 7960 } 7961 } else { 7962 final int childIndex = parentGroup.indexOfChild(viewAtDrawingLevel); 7963 final boolean customOrder = parentGroup.isChildrenDrawingOrderEnabled(); 7964 final int childDrawIndex = ((childIndex >= 0) && customOrder) ? parentGroup 7965 .getChildDrawingOrder(childCount, childIndex) : childIndex; 7966 final int numChildrenToIterate = customOrder ? childCount : childDrawIndex; 7967 if (childDrawIndex != 0) { 7968 for (int i = 0; i < numChildrenToIterate; i++) { 7969 final int otherDrawIndex = (customOrder ? 7970 parentGroup.getChildDrawingOrder(childCount, i) : i); 7971 if (otherDrawIndex < childDrawIndex) { 7972 drawingOrderInParent += 7973 numViewsForAccessibility(parentGroup.getChildAt(i)); 7974 } 7975 } 7976 } 7977 } 7978 } 7979 } 7980 viewAtDrawingLevel = (View) currentParent; 7981 } 7982 info.setDrawingOrder(drawingOrderInParent); 7983 } 7984 7985 private static int numViewsForAccessibility(View view) { 7986 if (view != null) { 7987 if (view.includeForAccessibility()) { 7988 return 1; 7989 } else if (view instanceof ViewGroup) { 7990 return ((ViewGroup) view).getNumChildrenForAccessibility(); 7991 } 7992 } 7993 return 0; 7994 } 7995 7996 private View findLabelForView(View view, int labeledId) { 7997 if (mMatchLabelForPredicate == null) { 7998 mMatchLabelForPredicate = new MatchLabelForPredicate(); 7999 } 8000 mMatchLabelForPredicate.mLabeledId = labeledId; 8001 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 8002 } 8003 8004 /** 8005 * Computes whether this view is visible to the user. Such a view is 8006 * attached, visible, all its predecessors are visible, it is not clipped 8007 * entirely by its predecessors, and has an alpha greater than zero. 8008 * 8009 * @return Whether the view is visible on the screen. 8010 * 8011 * @hide 8012 */ 8013 protected boolean isVisibleToUser() { 8014 return isVisibleToUser(null); 8015 } 8016 8017 /** 8018 * Computes whether the given portion of this view is visible to the user. 8019 * Such a view is attached, visible, all its predecessors are visible, 8020 * has an alpha greater than zero, and the specified portion is not 8021 * clipped entirely by its predecessors. 8022 * 8023 * @param boundInView the portion of the view to test; coordinates should be relative; may be 8024 * <code>null</code>, and the entire view will be tested in this case. 8025 * When <code>true</code> is returned by the function, the actual visible 8026 * region will be stored in this parameter; that is, if boundInView is fully 8027 * contained within the view, no modification will be made, otherwise regions 8028 * outside of the visible area of the view will be clipped. 8029 * 8030 * @return Whether the specified portion of the view is visible on the screen. 8031 * 8032 * @hide 8033 */ 8034 protected boolean isVisibleToUser(Rect boundInView) { 8035 if (mAttachInfo != null) { 8036 // Attached to invisible window means this view is not visible. 8037 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 8038 return false; 8039 } 8040 // An invisible predecessor or one with alpha zero means 8041 // that this view is not visible to the user. 8042 Object current = this; 8043 while (current instanceof View) { 8044 View view = (View) current; 8045 // We have attach info so this view is attached and there is no 8046 // need to check whether we reach to ViewRootImpl on the way up. 8047 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 8048 view.getVisibility() != VISIBLE) { 8049 return false; 8050 } 8051 current = view.mParent; 8052 } 8053 // Check if the view is entirely covered by its predecessors. 8054 Rect visibleRect = mAttachInfo.mTmpInvalRect; 8055 Point offset = mAttachInfo.mPoint; 8056 if (!getGlobalVisibleRect(visibleRect, offset)) { 8057 return false; 8058 } 8059 // Check if the visible portion intersects the rectangle of interest. 8060 if (boundInView != null) { 8061 visibleRect.offset(-offset.x, -offset.y); 8062 return boundInView.intersect(visibleRect); 8063 } 8064 return true; 8065 } 8066 return false; 8067 } 8068 8069 /** 8070 * Returns the delegate for implementing accessibility support via 8071 * composition. For more details see {@link AccessibilityDelegate}. 8072 * 8073 * @return The delegate, or null if none set. 8074 * 8075 * @hide 8076 */ 8077 public AccessibilityDelegate getAccessibilityDelegate() { 8078 return mAccessibilityDelegate; 8079 } 8080 8081 /** 8082 * Sets a delegate for implementing accessibility support via composition 8083 * (as opposed to inheritance). For more details, see 8084 * {@link AccessibilityDelegate}. 8085 * <p> 8086 * <strong>Note:</strong> On platform versions prior to 8087 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 8088 * views in the {@code android.widget.*} package are called <i>before</i> 8089 * host methods. This prevents certain properties such as class name from 8090 * being modified by overriding 8091 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 8092 * as any changes will be overwritten by the host class. 8093 * <p> 8094 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 8095 * methods are called <i>after</i> host methods, which all properties to be 8096 * modified without being overwritten by the host class. 8097 * 8098 * @param delegate the object to which accessibility method calls should be 8099 * delegated 8100 * @see AccessibilityDelegate 8101 */ 8102 public void setAccessibilityDelegate(@Nullable AccessibilityDelegate delegate) { 8103 mAccessibilityDelegate = delegate; 8104 } 8105 8106 /** 8107 * Gets the provider for managing a virtual view hierarchy rooted at this View 8108 * and reported to {@link android.accessibilityservice.AccessibilityService}s 8109 * that explore the window content. 8110 * <p> 8111 * If this method returns an instance, this instance is responsible for managing 8112 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 8113 * View including the one representing the View itself. Similarly the returned 8114 * instance is responsible for performing accessibility actions on any virtual 8115 * view or the root view itself. 8116 * </p> 8117 * <p> 8118 * If an {@link AccessibilityDelegate} has been specified via calling 8119 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8120 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 8121 * is responsible for handling this call. 8122 * </p> 8123 * 8124 * @return The provider. 8125 * 8126 * @see AccessibilityNodeProvider 8127 */ 8128 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 8129 if (mAccessibilityDelegate != null) { 8130 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 8131 } else { 8132 return null; 8133 } 8134 } 8135 8136 /** 8137 * Gets the unique identifier of this view on the screen for accessibility purposes. 8138 * 8139 * @return The view accessibility id. 8140 * 8141 * @hide 8142 */ 8143 public int getAccessibilityViewId() { 8144 if (mAccessibilityViewId == NO_ID) { 8145 mAccessibilityViewId = sNextAccessibilityViewId++; 8146 } 8147 return mAccessibilityViewId; 8148 } 8149 8150 /** 8151 * Gets the unique identifier of the window in which this View reseides. 8152 * 8153 * @return The window accessibility id. 8154 * 8155 * @hide 8156 */ 8157 public int getAccessibilityWindowId() { 8158 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 8159 : AccessibilityWindowInfo.UNDEFINED_WINDOW_ID; 8160 } 8161 8162 /** 8163 * Returns the {@link View}'s content description. 8164 * <p> 8165 * <strong>Note:</strong> Do not override this method, as it will have no 8166 * effect on the content description presented to accessibility services. 8167 * You must call {@link #setContentDescription(CharSequence)} to modify the 8168 * content description. 8169 * 8170 * @return the content description 8171 * @see #setContentDescription(CharSequence) 8172 * @attr ref android.R.styleable#View_contentDescription 8173 */ 8174 @ViewDebug.ExportedProperty(category = "accessibility") 8175 public CharSequence getContentDescription() { 8176 return mContentDescription; 8177 } 8178 8179 /** 8180 * Sets the {@link View}'s content description. 8181 * <p> 8182 * A content description briefly describes the view and is primarily used 8183 * for accessibility support to determine how a view should be presented to 8184 * the user. In the case of a view with no textual representation, such as 8185 * {@link android.widget.ImageButton}, a useful content description 8186 * explains what the view does. For example, an image button with a phone 8187 * icon that is used to place a call may use "Call" as its content 8188 * description. An image of a floppy disk that is used to save a file may 8189 * use "Save". 8190 * 8191 * @param contentDescription The content description. 8192 * @see #getContentDescription() 8193 * @attr ref android.R.styleable#View_contentDescription 8194 */ 8195 @RemotableViewMethod 8196 public void setContentDescription(CharSequence contentDescription) { 8197 if (mContentDescription == null) { 8198 if (contentDescription == null) { 8199 return; 8200 } 8201 } else if (mContentDescription.equals(contentDescription)) { 8202 return; 8203 } 8204 mContentDescription = contentDescription; 8205 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 8206 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 8207 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 8208 notifySubtreeAccessibilityStateChangedIfNeeded(); 8209 } else { 8210 notifyViewAccessibilityStateChangedIfNeeded( 8211 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 8212 } 8213 } 8214 8215 /** 8216 * Sets the id of a view before which this one is visited in accessibility traversal. 8217 * A screen-reader must visit the content of this view before the content of the one 8218 * it precedes. For example, if view B is set to be before view A, then a screen-reader 8219 * will traverse the entire content of B before traversing the entire content of A, 8220 * regardles of what traversal strategy it is using. 8221 * <p> 8222 * Views that do not have specified before/after relationships are traversed in order 8223 * determined by the screen-reader. 8224 * </p> 8225 * <p> 8226 * Setting that this view is before a view that is not important for accessibility 8227 * or if this view is not important for accessibility will have no effect as the 8228 * screen-reader is not aware of unimportant views. 8229 * </p> 8230 * 8231 * @param beforeId The id of a view this one precedes in accessibility traversal. 8232 * 8233 * @attr ref android.R.styleable#View_accessibilityTraversalBefore 8234 * 8235 * @see #setImportantForAccessibility(int) 8236 */ 8237 @RemotableViewMethod 8238 public void setAccessibilityTraversalBefore(int beforeId) { 8239 if (mAccessibilityTraversalBeforeId == beforeId) { 8240 return; 8241 } 8242 mAccessibilityTraversalBeforeId = beforeId; 8243 notifyViewAccessibilityStateChangedIfNeeded( 8244 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8245 } 8246 8247 /** 8248 * Gets the id of a view before which this one is visited in accessibility traversal. 8249 * 8250 * @return The id of a view this one precedes in accessibility traversal if 8251 * specified, otherwise {@link #NO_ID}. 8252 * 8253 * @see #setAccessibilityTraversalBefore(int) 8254 */ 8255 public int getAccessibilityTraversalBefore() { 8256 return mAccessibilityTraversalBeforeId; 8257 } 8258 8259 /** 8260 * Sets the id of a view after which this one is visited in accessibility traversal. 8261 * A screen-reader must visit the content of the other view before the content of this 8262 * one. For example, if view B is set to be after view A, then a screen-reader 8263 * will traverse the entire content of A before traversing the entire content of B, 8264 * regardles of what traversal strategy it is using. 8265 * <p> 8266 * Views that do not have specified before/after relationships are traversed in order 8267 * determined by the screen-reader. 8268 * </p> 8269 * <p> 8270 * Setting that this view is after a view that is not important for accessibility 8271 * or if this view is not important for accessibility will have no effect as the 8272 * screen-reader is not aware of unimportant views. 8273 * </p> 8274 * 8275 * @param afterId The id of a view this one succedees in accessibility traversal. 8276 * 8277 * @attr ref android.R.styleable#View_accessibilityTraversalAfter 8278 * 8279 * @see #setImportantForAccessibility(int) 8280 */ 8281 @RemotableViewMethod 8282 public void setAccessibilityTraversalAfter(int afterId) { 8283 if (mAccessibilityTraversalAfterId == afterId) { 8284 return; 8285 } 8286 mAccessibilityTraversalAfterId = afterId; 8287 notifyViewAccessibilityStateChangedIfNeeded( 8288 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8289 } 8290 8291 /** 8292 * Gets the id of a view after which this one is visited in accessibility traversal. 8293 * 8294 * @return The id of a view this one succeedes in accessibility traversal if 8295 * specified, otherwise {@link #NO_ID}. 8296 * 8297 * @see #setAccessibilityTraversalAfter(int) 8298 */ 8299 public int getAccessibilityTraversalAfter() { 8300 return mAccessibilityTraversalAfterId; 8301 } 8302 8303 /** 8304 * Gets the id of a view for which this view serves as a label for 8305 * accessibility purposes. 8306 * 8307 * @return The labeled view id. 8308 */ 8309 @ViewDebug.ExportedProperty(category = "accessibility") 8310 public int getLabelFor() { 8311 return mLabelForId; 8312 } 8313 8314 /** 8315 * Sets the id of a view for which this view serves as a label for 8316 * accessibility purposes. 8317 * 8318 * @param id The labeled view id. 8319 */ 8320 @RemotableViewMethod 8321 public void setLabelFor(@IdRes int id) { 8322 if (mLabelForId == id) { 8323 return; 8324 } 8325 mLabelForId = id; 8326 if (mLabelForId != View.NO_ID 8327 && mID == View.NO_ID) { 8328 mID = generateViewId(); 8329 } 8330 notifyViewAccessibilityStateChangedIfNeeded( 8331 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8332 } 8333 8334 /** 8335 * Invoked whenever this view loses focus, either by losing window focus or by losing 8336 * focus within its window. This method can be used to clear any state tied to the 8337 * focus. For instance, if a button is held pressed with the trackball and the window 8338 * loses focus, this method can be used to cancel the press. 8339 * 8340 * Subclasses of View overriding this method should always call super.onFocusLost(). 8341 * 8342 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 8343 * @see #onWindowFocusChanged(boolean) 8344 * 8345 * @hide pending API council approval 8346 */ 8347 @CallSuper 8348 protected void onFocusLost() { 8349 resetPressedState(); 8350 } 8351 8352 private void resetPressedState() { 8353 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8354 return; 8355 } 8356 8357 if (isPressed()) { 8358 setPressed(false); 8359 8360 if (!mHasPerformedLongPress) { 8361 removeLongPressCallback(); 8362 } 8363 } 8364 } 8365 8366 /** 8367 * Returns true if this view has focus 8368 * 8369 * @return True if this view has focus, false otherwise. 8370 */ 8371 @ViewDebug.ExportedProperty(category = "focus") 8372 public boolean isFocused() { 8373 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 8374 } 8375 8376 /** 8377 * Find the view in the hierarchy rooted at this view that currently has 8378 * focus. 8379 * 8380 * @return The view that currently has focus, or null if no focused view can 8381 * be found. 8382 */ 8383 public View findFocus() { 8384 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 8385 } 8386 8387 /** 8388 * Indicates whether this view is one of the set of scrollable containers in 8389 * its window. 8390 * 8391 * @return whether this view is one of the set of scrollable containers in 8392 * its window 8393 * 8394 * @attr ref android.R.styleable#View_isScrollContainer 8395 */ 8396 public boolean isScrollContainer() { 8397 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 8398 } 8399 8400 /** 8401 * Change whether this view is one of the set of scrollable containers in 8402 * its window. This will be used to determine whether the window can 8403 * resize or must pan when a soft input area is open -- scrollable 8404 * containers allow the window to use resize mode since the container 8405 * will appropriately shrink. 8406 * 8407 * @attr ref android.R.styleable#View_isScrollContainer 8408 */ 8409 public void setScrollContainer(boolean isScrollContainer) { 8410 if (isScrollContainer) { 8411 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 8412 mAttachInfo.mScrollContainers.add(this); 8413 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 8414 } 8415 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 8416 } else { 8417 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 8418 mAttachInfo.mScrollContainers.remove(this); 8419 } 8420 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 8421 } 8422 } 8423 8424 /** 8425 * Returns the quality of the drawing cache. 8426 * 8427 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 8428 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 8429 * 8430 * @see #setDrawingCacheQuality(int) 8431 * @see #setDrawingCacheEnabled(boolean) 8432 * @see #isDrawingCacheEnabled() 8433 * 8434 * @attr ref android.R.styleable#View_drawingCacheQuality 8435 */ 8436 @DrawingCacheQuality 8437 public int getDrawingCacheQuality() { 8438 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 8439 } 8440 8441 /** 8442 * Set the drawing cache quality of this view. This value is used only when the 8443 * drawing cache is enabled 8444 * 8445 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 8446 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 8447 * 8448 * @see #getDrawingCacheQuality() 8449 * @see #setDrawingCacheEnabled(boolean) 8450 * @see #isDrawingCacheEnabled() 8451 * 8452 * @attr ref android.R.styleable#View_drawingCacheQuality 8453 */ 8454 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 8455 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 8456 } 8457 8458 /** 8459 * Returns whether the screen should remain on, corresponding to the current 8460 * value of {@link #KEEP_SCREEN_ON}. 8461 * 8462 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 8463 * 8464 * @see #setKeepScreenOn(boolean) 8465 * 8466 * @attr ref android.R.styleable#View_keepScreenOn 8467 */ 8468 public boolean getKeepScreenOn() { 8469 return (mViewFlags & KEEP_SCREEN_ON) != 0; 8470 } 8471 8472 /** 8473 * Controls whether the screen should remain on, modifying the 8474 * value of {@link #KEEP_SCREEN_ON}. 8475 * 8476 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 8477 * 8478 * @see #getKeepScreenOn() 8479 * 8480 * @attr ref android.R.styleable#View_keepScreenOn 8481 */ 8482 public void setKeepScreenOn(boolean keepScreenOn) { 8483 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 8484 } 8485 8486 /** 8487 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 8488 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8489 * 8490 * @attr ref android.R.styleable#View_nextFocusLeft 8491 */ 8492 public int getNextFocusLeftId() { 8493 return mNextFocusLeftId; 8494 } 8495 8496 /** 8497 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 8498 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 8499 * decide automatically. 8500 * 8501 * @attr ref android.R.styleable#View_nextFocusLeft 8502 */ 8503 public void setNextFocusLeftId(int nextFocusLeftId) { 8504 mNextFocusLeftId = nextFocusLeftId; 8505 } 8506 8507 /** 8508 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 8509 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8510 * 8511 * @attr ref android.R.styleable#View_nextFocusRight 8512 */ 8513 public int getNextFocusRightId() { 8514 return mNextFocusRightId; 8515 } 8516 8517 /** 8518 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 8519 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 8520 * decide automatically. 8521 * 8522 * @attr ref android.R.styleable#View_nextFocusRight 8523 */ 8524 public void setNextFocusRightId(int nextFocusRightId) { 8525 mNextFocusRightId = nextFocusRightId; 8526 } 8527 8528 /** 8529 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 8530 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8531 * 8532 * @attr ref android.R.styleable#View_nextFocusUp 8533 */ 8534 public int getNextFocusUpId() { 8535 return mNextFocusUpId; 8536 } 8537 8538 /** 8539 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 8540 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 8541 * decide automatically. 8542 * 8543 * @attr ref android.R.styleable#View_nextFocusUp 8544 */ 8545 public void setNextFocusUpId(int nextFocusUpId) { 8546 mNextFocusUpId = nextFocusUpId; 8547 } 8548 8549 /** 8550 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 8551 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8552 * 8553 * @attr ref android.R.styleable#View_nextFocusDown 8554 */ 8555 public int getNextFocusDownId() { 8556 return mNextFocusDownId; 8557 } 8558 8559 /** 8560 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 8561 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 8562 * decide automatically. 8563 * 8564 * @attr ref android.R.styleable#View_nextFocusDown 8565 */ 8566 public void setNextFocusDownId(int nextFocusDownId) { 8567 mNextFocusDownId = nextFocusDownId; 8568 } 8569 8570 /** 8571 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 8572 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 8573 * 8574 * @attr ref android.R.styleable#View_nextFocusForward 8575 */ 8576 public int getNextFocusForwardId() { 8577 return mNextFocusForwardId; 8578 } 8579 8580 /** 8581 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 8582 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 8583 * decide automatically. 8584 * 8585 * @attr ref android.R.styleable#View_nextFocusForward 8586 */ 8587 public void setNextFocusForwardId(int nextFocusForwardId) { 8588 mNextFocusForwardId = nextFocusForwardId; 8589 } 8590 8591 /** 8592 * Gets the id of the root of the next keyboard navigation cluster. 8593 * @return The next keyboard navigation cluster ID, or {@link #NO_ID} if the framework should 8594 * decide automatically. 8595 * 8596 * @attr ref android.R.styleable#View_nextClusterForward 8597 */ 8598 public int getNextClusterForwardId() { 8599 return mNextClusterForwardId; 8600 } 8601 8602 /** 8603 * Sets the id of the view to use as the root of the next keyboard navigation cluster. 8604 * @param nextClusterForwardId The next cluster ID, or {@link #NO_ID} if the framework should 8605 * decide automatically. 8606 * 8607 * @attr ref android.R.styleable#View_nextClusterForward 8608 */ 8609 public void setNextClusterForwardId(int nextClusterForwardId) { 8610 mNextClusterForwardId = nextClusterForwardId; 8611 } 8612 8613 /** 8614 * Returns the visibility of this view and all of its ancestors 8615 * 8616 * @return True if this view and all of its ancestors are {@link #VISIBLE} 8617 */ 8618 public boolean isShown() { 8619 View current = this; 8620 //noinspection ConstantConditions 8621 do { 8622 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 8623 return false; 8624 } 8625 ViewParent parent = current.mParent; 8626 if (parent == null) { 8627 return false; // We are not attached to the view root 8628 } 8629 if (!(parent instanceof View)) { 8630 return true; 8631 } 8632 current = (View) parent; 8633 } while (current != null); 8634 8635 return false; 8636 } 8637 8638 /** 8639 * Called by the view hierarchy when the content insets for a window have 8640 * changed, to allow it to adjust its content to fit within those windows. 8641 * The content insets tell you the space that the status bar, input method, 8642 * and other system windows infringe on the application's window. 8643 * 8644 * <p>You do not normally need to deal with this function, since the default 8645 * window decoration given to applications takes care of applying it to the 8646 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 8647 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 8648 * and your content can be placed under those system elements. You can then 8649 * use this method within your view hierarchy if you have parts of your UI 8650 * which you would like to ensure are not being covered. 8651 * 8652 * <p>The default implementation of this method simply applies the content 8653 * insets to the view's padding, consuming that content (modifying the 8654 * insets to be 0), and returning true. This behavior is off by default, but can 8655 * be enabled through {@link #setFitsSystemWindows(boolean)}. 8656 * 8657 * <p>This function's traversal down the hierarchy is depth-first. The same content 8658 * insets object is propagated down the hierarchy, so any changes made to it will 8659 * be seen by all following views (including potentially ones above in 8660 * the hierarchy since this is a depth-first traversal). The first view 8661 * that returns true will abort the entire traversal. 8662 * 8663 * <p>The default implementation works well for a situation where it is 8664 * used with a container that covers the entire window, allowing it to 8665 * apply the appropriate insets to its content on all edges. If you need 8666 * a more complicated layout (such as two different views fitting system 8667 * windows, one on the top of the window, and one on the bottom), 8668 * you can override the method and handle the insets however you would like. 8669 * Note that the insets provided by the framework are always relative to the 8670 * far edges of the window, not accounting for the location of the called view 8671 * within that window. (In fact when this method is called you do not yet know 8672 * where the layout will place the view, as it is done before layout happens.) 8673 * 8674 * <p>Note: unlike many View methods, there is no dispatch phase to this 8675 * call. If you are overriding it in a ViewGroup and want to allow the 8676 * call to continue to your children, you must be sure to call the super 8677 * implementation. 8678 * 8679 * <p>Here is a sample layout that makes use of fitting system windows 8680 * to have controls for a video view placed inside of the window decorations 8681 * that it hides and shows. This can be used with code like the second 8682 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 8683 * 8684 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 8685 * 8686 * @param insets Current content insets of the window. Prior to 8687 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 8688 * the insets or else you and Android will be unhappy. 8689 * 8690 * @return {@code true} if this view applied the insets and it should not 8691 * continue propagating further down the hierarchy, {@code false} otherwise. 8692 * @see #getFitsSystemWindows() 8693 * @see #setFitsSystemWindows(boolean) 8694 * @see #setSystemUiVisibility(int) 8695 * 8696 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 8697 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 8698 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 8699 * to implement handling their own insets. 8700 */ 8701 @Deprecated 8702 protected boolean fitSystemWindows(Rect insets) { 8703 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 8704 if (insets == null) { 8705 // Null insets by definition have already been consumed. 8706 // This call cannot apply insets since there are none to apply, 8707 // so return false. 8708 return false; 8709 } 8710 // If we're not in the process of dispatching the newer apply insets call, 8711 // that means we're not in the compatibility path. Dispatch into the newer 8712 // apply insets path and take things from there. 8713 try { 8714 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 8715 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 8716 } finally { 8717 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 8718 } 8719 } else { 8720 // We're being called from the newer apply insets path. 8721 // Perform the standard fallback behavior. 8722 return fitSystemWindowsInt(insets); 8723 } 8724 } 8725 8726 private boolean fitSystemWindowsInt(Rect insets) { 8727 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 8728 mUserPaddingStart = UNDEFINED_PADDING; 8729 mUserPaddingEnd = UNDEFINED_PADDING; 8730 Rect localInsets = sThreadLocal.get(); 8731 if (localInsets == null) { 8732 localInsets = new Rect(); 8733 sThreadLocal.set(localInsets); 8734 } 8735 boolean res = computeFitSystemWindows(insets, localInsets); 8736 mUserPaddingLeftInitial = localInsets.left; 8737 mUserPaddingRightInitial = localInsets.right; 8738 internalSetPadding(localInsets.left, localInsets.top, 8739 localInsets.right, localInsets.bottom); 8740 return res; 8741 } 8742 return false; 8743 } 8744 8745 /** 8746 * Called when the view should apply {@link WindowInsets} according to its internal policy. 8747 * 8748 * <p>This method should be overridden by views that wish to apply a policy different from or 8749 * in addition to the default behavior. Clients that wish to force a view subtree 8750 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 8751 * 8752 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 8753 * it will be called during dispatch instead of this method. The listener may optionally 8754 * call this method from its own implementation if it wishes to apply the view's default 8755 * insets policy in addition to its own.</p> 8756 * 8757 * <p>Implementations of this method should either return the insets parameter unchanged 8758 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 8759 * that this view applied itself. This allows new inset types added in future platform 8760 * versions to pass through existing implementations unchanged without being erroneously 8761 * consumed.</p> 8762 * 8763 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 8764 * property is set then the view will consume the system window insets and apply them 8765 * as padding for the view.</p> 8766 * 8767 * @param insets Insets to apply 8768 * @return The supplied insets with any applied insets consumed 8769 */ 8770 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 8771 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 8772 // We weren't called from within a direct call to fitSystemWindows, 8773 // call into it as a fallback in case we're in a class that overrides it 8774 // and has logic to perform. 8775 if (fitSystemWindows(insets.getSystemWindowInsets())) { 8776 return insets.consumeSystemWindowInsets(); 8777 } 8778 } else { 8779 // We were called from within a direct call to fitSystemWindows. 8780 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 8781 return insets.consumeSystemWindowInsets(); 8782 } 8783 } 8784 return insets; 8785 } 8786 8787 /** 8788 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 8789 * window insets to this view. The listener's 8790 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 8791 * method will be called instead of the view's 8792 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 8793 * 8794 * @param listener Listener to set 8795 * 8796 * @see #onApplyWindowInsets(WindowInsets) 8797 */ 8798 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 8799 getListenerInfo().mOnApplyWindowInsetsListener = listener; 8800 } 8801 8802 /** 8803 * Request to apply the given window insets to this view or another view in its subtree. 8804 * 8805 * <p>This method should be called by clients wishing to apply insets corresponding to areas 8806 * obscured by window decorations or overlays. This can include the status and navigation bars, 8807 * action bars, input methods and more. New inset categories may be added in the future. 8808 * The method returns the insets provided minus any that were applied by this view or its 8809 * children.</p> 8810 * 8811 * <p>Clients wishing to provide custom behavior should override the 8812 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 8813 * {@link OnApplyWindowInsetsListener} via the 8814 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 8815 * method.</p> 8816 * 8817 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 8818 * </p> 8819 * 8820 * @param insets Insets to apply 8821 * @return The provided insets minus the insets that were consumed 8822 */ 8823 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 8824 try { 8825 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 8826 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 8827 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 8828 } else { 8829 return onApplyWindowInsets(insets); 8830 } 8831 } finally { 8832 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 8833 } 8834 } 8835 8836 /** 8837 * Compute the view's coordinate within the surface. 8838 * 8839 * <p>Computes the coordinates of this view in its surface. The argument 8840 * must be an array of two integers. After the method returns, the array 8841 * contains the x and y location in that order.</p> 8842 * @hide 8843 * @param location an array of two integers in which to hold the coordinates 8844 */ 8845 public void getLocationInSurface(@Size(2) int[] location) { 8846 getLocationInWindow(location); 8847 if (mAttachInfo != null && mAttachInfo.mViewRootImpl != null) { 8848 location[0] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.left; 8849 location[1] += mAttachInfo.mViewRootImpl.mWindowAttributes.surfaceInsets.top; 8850 } 8851 } 8852 8853 /** 8854 * Provide original WindowInsets that are dispatched to the view hierarchy. The insets are 8855 * only available if the view is attached. 8856 * 8857 * @return WindowInsets from the top of the view hierarchy or null if View is detached 8858 */ 8859 public WindowInsets getRootWindowInsets() { 8860 if (mAttachInfo != null) { 8861 return mAttachInfo.mViewRootImpl.getWindowInsets(false /* forceConstruct */); 8862 } 8863 return null; 8864 } 8865 8866 /** 8867 * @hide Compute the insets that should be consumed by this view and the ones 8868 * that should propagate to those under it. 8869 */ 8870 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 8871 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 8872 || mAttachInfo == null 8873 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 8874 && !mAttachInfo.mOverscanRequested)) { 8875 outLocalInsets.set(inoutInsets); 8876 inoutInsets.set(0, 0, 0, 0); 8877 return true; 8878 } else { 8879 // The application wants to take care of fitting system window for 8880 // the content... however we still need to take care of any overscan here. 8881 final Rect overscan = mAttachInfo.mOverscanInsets; 8882 outLocalInsets.set(overscan); 8883 inoutInsets.left -= overscan.left; 8884 inoutInsets.top -= overscan.top; 8885 inoutInsets.right -= overscan.right; 8886 inoutInsets.bottom -= overscan.bottom; 8887 return false; 8888 } 8889 } 8890 8891 /** 8892 * Compute insets that should be consumed by this view and the ones that should propagate 8893 * to those under it. 8894 * 8895 * @param in Insets currently being processed by this View, likely received as a parameter 8896 * to {@link #onApplyWindowInsets(WindowInsets)}. 8897 * @param outLocalInsets A Rect that will receive the insets that should be consumed 8898 * by this view 8899 * @return Insets that should be passed along to views under this one 8900 */ 8901 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 8902 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 8903 || mAttachInfo == null 8904 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 8905 outLocalInsets.set(in.getSystemWindowInsets()); 8906 return in.consumeSystemWindowInsets(); 8907 } else { 8908 outLocalInsets.set(0, 0, 0, 0); 8909 return in; 8910 } 8911 } 8912 8913 /** 8914 * Sets whether or not this view should account for system screen decorations 8915 * such as the status bar and inset its content; that is, controlling whether 8916 * the default implementation of {@link #fitSystemWindows(Rect)} will be 8917 * executed. See that method for more details. 8918 * 8919 * <p>Note that if you are providing your own implementation of 8920 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 8921 * flag to true -- your implementation will be overriding the default 8922 * implementation that checks this flag. 8923 * 8924 * @param fitSystemWindows If true, then the default implementation of 8925 * {@link #fitSystemWindows(Rect)} will be executed. 8926 * 8927 * @attr ref android.R.styleable#View_fitsSystemWindows 8928 * @see #getFitsSystemWindows() 8929 * @see #fitSystemWindows(Rect) 8930 * @see #setSystemUiVisibility(int) 8931 */ 8932 public void setFitsSystemWindows(boolean fitSystemWindows) { 8933 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 8934 } 8935 8936 /** 8937 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 8938 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 8939 * will be executed. 8940 * 8941 * @return {@code true} if the default implementation of 8942 * {@link #fitSystemWindows(Rect)} will be executed. 8943 * 8944 * @attr ref android.R.styleable#View_fitsSystemWindows 8945 * @see #setFitsSystemWindows(boolean) 8946 * @see #fitSystemWindows(Rect) 8947 * @see #setSystemUiVisibility(int) 8948 */ 8949 @ViewDebug.ExportedProperty 8950 public boolean getFitsSystemWindows() { 8951 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 8952 } 8953 8954 /** @hide */ 8955 public boolean fitsSystemWindows() { 8956 return getFitsSystemWindows(); 8957 } 8958 8959 /** 8960 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 8961 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 8962 */ 8963 @Deprecated 8964 public void requestFitSystemWindows() { 8965 if (mParent != null) { 8966 mParent.requestFitSystemWindows(); 8967 } 8968 } 8969 8970 /** 8971 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 8972 */ 8973 public void requestApplyInsets() { 8974 requestFitSystemWindows(); 8975 } 8976 8977 /** 8978 * For use by PhoneWindow to make its own system window fitting optional. 8979 * @hide 8980 */ 8981 public void makeOptionalFitsSystemWindows() { 8982 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 8983 } 8984 8985 /** 8986 * Returns the outsets, which areas of the device that aren't a surface, but we would like to 8987 * treat them as such. 8988 * @hide 8989 */ 8990 public void getOutsets(Rect outOutsetRect) { 8991 if (mAttachInfo != null) { 8992 outOutsetRect.set(mAttachInfo.mOutsets); 8993 } else { 8994 outOutsetRect.setEmpty(); 8995 } 8996 } 8997 8998 /** 8999 * Returns the visibility status for this view. 9000 * 9001 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9002 * @attr ref android.R.styleable#View_visibility 9003 */ 9004 @ViewDebug.ExportedProperty(mapping = { 9005 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 9006 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 9007 @ViewDebug.IntToString(from = GONE, to = "GONE") 9008 }) 9009 @Visibility 9010 public int getVisibility() { 9011 return mViewFlags & VISIBILITY_MASK; 9012 } 9013 9014 /** 9015 * Set the visibility state of this view. 9016 * 9017 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 9018 * @attr ref android.R.styleable#View_visibility 9019 */ 9020 @RemotableViewMethod 9021 public void setVisibility(@Visibility int visibility) { 9022 setFlags(visibility, VISIBILITY_MASK); 9023 } 9024 9025 /** 9026 * Returns the enabled status for this view. The interpretation of the 9027 * enabled state varies by subclass. 9028 * 9029 * @return True if this view is enabled, false otherwise. 9030 */ 9031 @ViewDebug.ExportedProperty 9032 public boolean isEnabled() { 9033 return (mViewFlags & ENABLED_MASK) == ENABLED; 9034 } 9035 9036 /** 9037 * Set the enabled state of this view. The interpretation of the enabled 9038 * state varies by subclass. 9039 * 9040 * @param enabled True if this view is enabled, false otherwise. 9041 */ 9042 @RemotableViewMethod 9043 public void setEnabled(boolean enabled) { 9044 if (enabled == isEnabled()) return; 9045 9046 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 9047 9048 /* 9049 * The View most likely has to change its appearance, so refresh 9050 * the drawable state. 9051 */ 9052 refreshDrawableState(); 9053 9054 // Invalidate too, since the default behavior for views is to be 9055 // be drawn at 50% alpha rather than to change the drawable. 9056 invalidate(true); 9057 9058 if (!enabled) { 9059 cancelPendingInputEvents(); 9060 } 9061 } 9062 9063 /** 9064 * Set whether this view can receive the focus. 9065 * <p> 9066 * Setting this to false will also ensure that this view is not focusable 9067 * in touch mode. 9068 * 9069 * @param focusable If true, this view can receive the focus. 9070 * 9071 * @see #setFocusableInTouchMode(boolean) 9072 * @see #setFocusable(int) 9073 * @attr ref android.R.styleable#View_focusable 9074 */ 9075 public void setFocusable(boolean focusable) { 9076 setFocusable(focusable ? FOCUSABLE : NOT_FOCUSABLE); 9077 } 9078 9079 /** 9080 * Sets whether this view can receive focus. 9081 * <p> 9082 * Setting this to {@link #FOCUSABLE_AUTO} tells the framework to determine focusability 9083 * automatically based on the view's interactivity. This is the default. 9084 * <p> 9085 * Setting this to NOT_FOCUSABLE will ensure that this view is also not focusable 9086 * in touch mode. 9087 * 9088 * @param focusable One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, 9089 * or {@link #FOCUSABLE_AUTO}. 9090 * @see #setFocusableInTouchMode(boolean) 9091 * @attr ref android.R.styleable#View_focusable 9092 */ 9093 public void setFocusable(@Focusable int focusable) { 9094 if ((focusable & (FOCUSABLE_AUTO | FOCUSABLE)) == 0) { 9095 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 9096 } 9097 setFlags(focusable, FOCUSABLE_MASK); 9098 } 9099 9100 /** 9101 * Set whether this view can receive focus while in touch mode. 9102 * 9103 * Setting this to true will also ensure that this view is focusable. 9104 * 9105 * @param focusableInTouchMode If true, this view can receive the focus while 9106 * in touch mode. 9107 * 9108 * @see #setFocusable(boolean) 9109 * @attr ref android.R.styleable#View_focusableInTouchMode 9110 */ 9111 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 9112 // Focusable in touch mode should always be set before the focusable flag 9113 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 9114 // which, in touch mode, will not successfully request focus on this view 9115 // because the focusable in touch mode flag is not set 9116 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 9117 9118 // Clear FOCUSABLE_AUTO if set. 9119 if (focusableInTouchMode) { 9120 // Clears FOCUSABLE_AUTO if set. 9121 setFlags(FOCUSABLE, FOCUSABLE_MASK); 9122 } 9123 } 9124 9125 /** 9126 * Set autofill mode for the view. 9127 * 9128 * @param autofillMode One of {@link #AUTOFILL_MODE_INHERIT}, {@link #AUTOFILL_MODE_AUTO}, 9129 * or {@link #AUTOFILL_MODE_MANUAL}. 9130 * @attr ref android.R.styleable#View_autofillMode 9131 */ 9132 public void setAutofillMode(@AutofillMode int autofillMode) { 9133 Preconditions.checkArgumentInRange(autofillMode, AUTOFILL_MODE_INHERIT, 9134 AUTOFILL_MODE_MANUAL, "autofillMode"); 9135 9136 mPrivateFlags3 &= ~PFLAG3_AUTOFILL_MODE_MASK; 9137 mPrivateFlags3 |= autofillMode << PFLAG3_AUTOFILL_MODE_SHIFT; 9138 } 9139 9140 /** 9141 * Sets the hints that helps the autofill service to select the appropriate data to fill the 9142 * view. 9143 * 9144 * @param autofillHints The autofill hints to set. If the array is emtpy, {@code null} is set. 9145 * @attr ref android.R.styleable#View_autofillHints 9146 */ 9147 public void setAutofillHints(@Nullable String... autofillHints) { 9148 if (autofillHints == null || autofillHints.length == 0) { 9149 mAutofillHints = null; 9150 } else { 9151 mAutofillHints = autofillHints; 9152 } 9153 } 9154 9155 /** 9156 * Set whether this view should have sound effects enabled for events such as 9157 * clicking and touching. 9158 * 9159 * <p>You may wish to disable sound effects for a view if you already play sounds, 9160 * for instance, a dial key that plays dtmf tones. 9161 * 9162 * @param soundEffectsEnabled whether sound effects are enabled for this view. 9163 * @see #isSoundEffectsEnabled() 9164 * @see #playSoundEffect(int) 9165 * @attr ref android.R.styleable#View_soundEffectsEnabled 9166 */ 9167 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 9168 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 9169 } 9170 9171 /** 9172 * @return whether this view should have sound effects enabled for events such as 9173 * clicking and touching. 9174 * 9175 * @see #setSoundEffectsEnabled(boolean) 9176 * @see #playSoundEffect(int) 9177 * @attr ref android.R.styleable#View_soundEffectsEnabled 9178 */ 9179 @ViewDebug.ExportedProperty 9180 public boolean isSoundEffectsEnabled() { 9181 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 9182 } 9183 9184 /** 9185 * Set whether this view should have haptic feedback for events such as 9186 * long presses. 9187 * 9188 * <p>You may wish to disable haptic feedback if your view already controls 9189 * its own haptic feedback. 9190 * 9191 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 9192 * @see #isHapticFeedbackEnabled() 9193 * @see #performHapticFeedback(int) 9194 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 9195 */ 9196 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 9197 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 9198 } 9199 9200 /** 9201 * @return whether this view should have haptic feedback enabled for events 9202 * long presses. 9203 * 9204 * @see #setHapticFeedbackEnabled(boolean) 9205 * @see #performHapticFeedback(int) 9206 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 9207 */ 9208 @ViewDebug.ExportedProperty 9209 public boolean isHapticFeedbackEnabled() { 9210 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 9211 } 9212 9213 /** 9214 * Returns the layout direction for this view. 9215 * 9216 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 9217 * {@link #LAYOUT_DIRECTION_RTL}, 9218 * {@link #LAYOUT_DIRECTION_INHERIT} or 9219 * {@link #LAYOUT_DIRECTION_LOCALE}. 9220 * 9221 * @attr ref android.R.styleable#View_layoutDirection 9222 * 9223 * @hide 9224 */ 9225 @ViewDebug.ExportedProperty(category = "layout", mapping = { 9226 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 9227 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 9228 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 9229 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 9230 }) 9231 @LayoutDir 9232 public int getRawLayoutDirection() { 9233 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 9234 } 9235 9236 /** 9237 * Set the layout direction for this view. This will propagate a reset of layout direction 9238 * resolution to the view's children and resolve layout direction for this view. 9239 * 9240 * @param layoutDirection the layout direction to set. Should be one of: 9241 * 9242 * {@link #LAYOUT_DIRECTION_LTR}, 9243 * {@link #LAYOUT_DIRECTION_RTL}, 9244 * {@link #LAYOUT_DIRECTION_INHERIT}, 9245 * {@link #LAYOUT_DIRECTION_LOCALE}. 9246 * 9247 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 9248 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 9249 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 9250 * 9251 * @attr ref android.R.styleable#View_layoutDirection 9252 */ 9253 @RemotableViewMethod 9254 public void setLayoutDirection(@LayoutDir int layoutDirection) { 9255 if (getRawLayoutDirection() != layoutDirection) { 9256 // Reset the current layout direction and the resolved one 9257 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 9258 resetRtlProperties(); 9259 // Set the new layout direction (filtered) 9260 mPrivateFlags2 |= 9261 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 9262 // We need to resolve all RTL properties as they all depend on layout direction 9263 resolveRtlPropertiesIfNeeded(); 9264 requestLayout(); 9265 invalidate(true); 9266 } 9267 } 9268 9269 /** 9270 * Returns the resolved layout direction for this view. 9271 * 9272 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 9273 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 9274 * 9275 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 9276 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 9277 * 9278 * @attr ref android.R.styleable#View_layoutDirection 9279 */ 9280 @ViewDebug.ExportedProperty(category = "layout", mapping = { 9281 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 9282 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 9283 }) 9284 @ResolvedLayoutDir 9285 public int getLayoutDirection() { 9286 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 9287 if (targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1) { 9288 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 9289 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 9290 } 9291 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 9292 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 9293 } 9294 9295 /** 9296 * Indicates whether or not this view's layout is right-to-left. This is resolved from 9297 * layout attribute and/or the inherited value from the parent 9298 * 9299 * @return true if the layout is right-to-left. 9300 * 9301 * @hide 9302 */ 9303 @ViewDebug.ExportedProperty(category = "layout") 9304 public boolean isLayoutRtl() { 9305 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 9306 } 9307 9308 /** 9309 * Indicates whether the view is currently tracking transient state that the 9310 * app should not need to concern itself with saving and restoring, but that 9311 * the framework should take special note to preserve when possible. 9312 * 9313 * <p>A view with transient state cannot be trivially rebound from an external 9314 * data source, such as an adapter binding item views in a list. This may be 9315 * because the view is performing an animation, tracking user selection 9316 * of content, or similar.</p> 9317 * 9318 * @return true if the view has transient state 9319 */ 9320 @ViewDebug.ExportedProperty(category = "layout") 9321 public boolean hasTransientState() { 9322 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 9323 } 9324 9325 /** 9326 * Set whether this view is currently tracking transient state that the 9327 * framework should attempt to preserve when possible. This flag is reference counted, 9328 * so every call to setHasTransientState(true) should be paired with a later call 9329 * to setHasTransientState(false). 9330 * 9331 * <p>A view with transient state cannot be trivially rebound from an external 9332 * data source, such as an adapter binding item views in a list. This may be 9333 * because the view is performing an animation, tracking user selection 9334 * of content, or similar.</p> 9335 * 9336 * @param hasTransientState true if this view has transient state 9337 */ 9338 public void setHasTransientState(boolean hasTransientState) { 9339 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 9340 mTransientStateCount - 1; 9341 if (mTransientStateCount < 0) { 9342 mTransientStateCount = 0; 9343 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 9344 "unmatched pair of setHasTransientState calls"); 9345 } else if ((hasTransientState && mTransientStateCount == 1) || 9346 (!hasTransientState && mTransientStateCount == 0)) { 9347 // update flag if we've just incremented up from 0 or decremented down to 0 9348 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 9349 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 9350 if (mParent != null) { 9351 try { 9352 mParent.childHasTransientStateChanged(this, hasTransientState); 9353 } catch (AbstractMethodError e) { 9354 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 9355 " does not fully implement ViewParent", e); 9356 } 9357 } 9358 } 9359 } 9360 9361 /** 9362 * Returns true if this view is currently attached to a window. 9363 */ 9364 public boolean isAttachedToWindow() { 9365 return mAttachInfo != null; 9366 } 9367 9368 /** 9369 * Returns true if this view has been through at least one layout since it 9370 * was last attached to or detached from a window. 9371 */ 9372 public boolean isLaidOut() { 9373 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 9374 } 9375 9376 /** 9377 * If this view doesn't do any drawing on its own, set this flag to 9378 * allow further optimizations. By default, this flag is not set on 9379 * View, but could be set on some View subclasses such as ViewGroup. 9380 * 9381 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 9382 * you should clear this flag. 9383 * 9384 * @param willNotDraw whether or not this View draw on its own 9385 */ 9386 public void setWillNotDraw(boolean willNotDraw) { 9387 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 9388 } 9389 9390 /** 9391 * Returns whether or not this View draws on its own. 9392 * 9393 * @return true if this view has nothing to draw, false otherwise 9394 */ 9395 @ViewDebug.ExportedProperty(category = "drawing") 9396 public boolean willNotDraw() { 9397 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 9398 } 9399 9400 /** 9401 * When a View's drawing cache is enabled, drawing is redirected to an 9402 * offscreen bitmap. Some views, like an ImageView, must be able to 9403 * bypass this mechanism if they already draw a single bitmap, to avoid 9404 * unnecessary usage of the memory. 9405 * 9406 * @param willNotCacheDrawing true if this view does not cache its 9407 * drawing, false otherwise 9408 */ 9409 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 9410 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 9411 } 9412 9413 /** 9414 * Returns whether or not this View can cache its drawing or not. 9415 * 9416 * @return true if this view does not cache its drawing, false otherwise 9417 */ 9418 @ViewDebug.ExportedProperty(category = "drawing") 9419 public boolean willNotCacheDrawing() { 9420 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 9421 } 9422 9423 /** 9424 * Indicates whether this view reacts to click events or not. 9425 * 9426 * @return true if the view is clickable, false otherwise 9427 * 9428 * @see #setClickable(boolean) 9429 * @attr ref android.R.styleable#View_clickable 9430 */ 9431 @ViewDebug.ExportedProperty 9432 public boolean isClickable() { 9433 return (mViewFlags & CLICKABLE) == CLICKABLE; 9434 } 9435 9436 /** 9437 * Enables or disables click events for this view. When a view 9438 * is clickable it will change its state to "pressed" on every click. 9439 * Subclasses should set the view clickable to visually react to 9440 * user's clicks. 9441 * 9442 * @param clickable true to make the view clickable, false otherwise 9443 * 9444 * @see #isClickable() 9445 * @attr ref android.R.styleable#View_clickable 9446 */ 9447 public void setClickable(boolean clickable) { 9448 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 9449 } 9450 9451 /** 9452 * Indicates whether this view reacts to long click events or not. 9453 * 9454 * @return true if the view is long clickable, false otherwise 9455 * 9456 * @see #setLongClickable(boolean) 9457 * @attr ref android.R.styleable#View_longClickable 9458 */ 9459 public boolean isLongClickable() { 9460 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9461 } 9462 9463 /** 9464 * Enables or disables long click events for this view. When a view is long 9465 * clickable it reacts to the user holding down the button for a longer 9466 * duration than a tap. This event can either launch the listener or a 9467 * context menu. 9468 * 9469 * @param longClickable true to make the view long clickable, false otherwise 9470 * @see #isLongClickable() 9471 * @attr ref android.R.styleable#View_longClickable 9472 */ 9473 public void setLongClickable(boolean longClickable) { 9474 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 9475 } 9476 9477 /** 9478 * Indicates whether this view reacts to context clicks or not. 9479 * 9480 * @return true if the view is context clickable, false otherwise 9481 * @see #setContextClickable(boolean) 9482 * @attr ref android.R.styleable#View_contextClickable 9483 */ 9484 public boolean isContextClickable() { 9485 return (mViewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 9486 } 9487 9488 /** 9489 * Enables or disables context clicking for this view. This event can launch the listener. 9490 * 9491 * @param contextClickable true to make the view react to a context click, false otherwise 9492 * @see #isContextClickable() 9493 * @attr ref android.R.styleable#View_contextClickable 9494 */ 9495 public void setContextClickable(boolean contextClickable) { 9496 setFlags(contextClickable ? CONTEXT_CLICKABLE : 0, CONTEXT_CLICKABLE); 9497 } 9498 9499 /** 9500 * Sets the pressed state for this view and provides a touch coordinate for 9501 * animation hinting. 9502 * 9503 * @param pressed Pass true to set the View's internal state to "pressed", 9504 * or false to reverts the View's internal state from a 9505 * previously set "pressed" state. 9506 * @param x The x coordinate of the touch that caused the press 9507 * @param y The y coordinate of the touch that caused the press 9508 */ 9509 private void setPressed(boolean pressed, float x, float y) { 9510 if (pressed) { 9511 drawableHotspotChanged(x, y); 9512 } 9513 9514 setPressed(pressed); 9515 } 9516 9517 /** 9518 * Sets the pressed state for this view. 9519 * 9520 * @see #isClickable() 9521 * @see #setClickable(boolean) 9522 * 9523 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 9524 * the View's internal state from a previously set "pressed" state. 9525 */ 9526 public void setPressed(boolean pressed) { 9527 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 9528 9529 if (pressed) { 9530 mPrivateFlags |= PFLAG_PRESSED; 9531 } else { 9532 mPrivateFlags &= ~PFLAG_PRESSED; 9533 } 9534 9535 if (needsRefresh) { 9536 refreshDrawableState(); 9537 } 9538 dispatchSetPressed(pressed); 9539 } 9540 9541 /** 9542 * Dispatch setPressed to all of this View's children. 9543 * 9544 * @see #setPressed(boolean) 9545 * 9546 * @param pressed The new pressed state 9547 */ 9548 protected void dispatchSetPressed(boolean pressed) { 9549 } 9550 9551 /** 9552 * Indicates whether the view is currently in pressed state. Unless 9553 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 9554 * the pressed state. 9555 * 9556 * @see #setPressed(boolean) 9557 * @see #isClickable() 9558 * @see #setClickable(boolean) 9559 * 9560 * @return true if the view is currently pressed, false otherwise 9561 */ 9562 @ViewDebug.ExportedProperty 9563 public boolean isPressed() { 9564 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 9565 } 9566 9567 /** 9568 * @hide 9569 * Indicates whether this view will participate in data collection through 9570 * {@link ViewStructure}. If true, it will not provide any data 9571 * for itself or its children. If false, the normal data collection will be allowed. 9572 * 9573 * @return Returns false if assist data collection is not blocked, else true. 9574 * 9575 * @see #setAssistBlocked(boolean) 9576 * @attr ref android.R.styleable#View_assistBlocked 9577 */ 9578 public boolean isAssistBlocked() { 9579 return (mPrivateFlags3 & PFLAG3_ASSIST_BLOCKED) != 0; 9580 } 9581 9582 /** 9583 * @hide 9584 * Indicates whether this view will participate in data collection through 9585 * {@link ViewStructure} for autofill purposes. 9586 * 9587 * <p>If {@code true}, it will not provide any data for itself or its children. 9588 * <p>If {@code false}, the normal data collection will be allowed. 9589 * 9590 * @return Returns {@code false} if assist data collection for autofill is not blocked, 9591 * else {@code true}. 9592 * 9593 * TODO(b/33197203): update / remove javadoc tags below 9594 * @see #setAssistBlocked(boolean) 9595 * @attr ref android.R.styleable#View_assistBlocked 9596 */ 9597 public boolean isAutofillBlocked() { 9598 return false; // TODO(b/33197203): properly implement it 9599 } 9600 9601 /** 9602 * @hide 9603 * Controls whether assist data collection from this view and its children is enabled 9604 * (that is, whether {@link #onProvideStructure} and 9605 * {@link #onProvideVirtualStructure} will be called). The default value is false, 9606 * allowing normal assist collection. Setting this to false will disable assist collection. 9607 * 9608 * @param enabled Set to true to <em>disable</em> assist data collection, or false 9609 * (the default) to allow it. 9610 * 9611 * @see #isAssistBlocked() 9612 * @see #onProvideStructure 9613 * @see #onProvideVirtualStructure 9614 * @attr ref android.R.styleable#View_assistBlocked 9615 */ 9616 public void setAssistBlocked(boolean enabled) { 9617 if (enabled) { 9618 mPrivateFlags3 |= PFLAG3_ASSIST_BLOCKED; 9619 } else { 9620 mPrivateFlags3 &= ~PFLAG3_ASSIST_BLOCKED; 9621 } 9622 } 9623 9624 /** 9625 * Indicates whether this view will save its state (that is, 9626 * whether its {@link #onSaveInstanceState} method will be called). 9627 * 9628 * @return Returns true if the view state saving is enabled, else false. 9629 * 9630 * @see #setSaveEnabled(boolean) 9631 * @attr ref android.R.styleable#View_saveEnabled 9632 */ 9633 public boolean isSaveEnabled() { 9634 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 9635 } 9636 9637 /** 9638 * Controls whether the saving of this view's state is 9639 * enabled (that is, whether its {@link #onSaveInstanceState} method 9640 * will be called). Note that even if freezing is enabled, the 9641 * view still must have an id assigned to it (via {@link #setId(int)}) 9642 * for its state to be saved. This flag can only disable the 9643 * saving of this view; any child views may still have their state saved. 9644 * 9645 * @param enabled Set to false to <em>disable</em> state saving, or true 9646 * (the default) to allow it. 9647 * 9648 * @see #isSaveEnabled() 9649 * @see #setId(int) 9650 * @see #onSaveInstanceState() 9651 * @attr ref android.R.styleable#View_saveEnabled 9652 */ 9653 public void setSaveEnabled(boolean enabled) { 9654 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 9655 } 9656 9657 /** 9658 * Gets whether the framework should discard touches when the view's 9659 * window is obscured by another visible window. 9660 * Refer to the {@link View} security documentation for more details. 9661 * 9662 * @return True if touch filtering is enabled. 9663 * 9664 * @see #setFilterTouchesWhenObscured(boolean) 9665 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 9666 */ 9667 @ViewDebug.ExportedProperty 9668 public boolean getFilterTouchesWhenObscured() { 9669 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 9670 } 9671 9672 /** 9673 * Sets whether the framework should discard touches when the view's 9674 * window is obscured by another visible window. 9675 * Refer to the {@link View} security documentation for more details. 9676 * 9677 * @param enabled True if touch filtering should be enabled. 9678 * 9679 * @see #getFilterTouchesWhenObscured 9680 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 9681 */ 9682 public void setFilterTouchesWhenObscured(boolean enabled) { 9683 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 9684 FILTER_TOUCHES_WHEN_OBSCURED); 9685 } 9686 9687 /** 9688 * Indicates whether the entire hierarchy under this view will save its 9689 * state when a state saving traversal occurs from its parent. The default 9690 * is true; if false, these views will not be saved unless 9691 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 9692 * 9693 * @return Returns true if the view state saving from parent is enabled, else false. 9694 * 9695 * @see #setSaveFromParentEnabled(boolean) 9696 */ 9697 public boolean isSaveFromParentEnabled() { 9698 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 9699 } 9700 9701 /** 9702 * Controls whether the entire hierarchy under this view will save its 9703 * state when a state saving traversal occurs from its parent. The default 9704 * is true; if false, these views will not be saved unless 9705 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 9706 * 9707 * @param enabled Set to false to <em>disable</em> state saving, or true 9708 * (the default) to allow it. 9709 * 9710 * @see #isSaveFromParentEnabled() 9711 * @see #setId(int) 9712 * @see #onSaveInstanceState() 9713 */ 9714 public void setSaveFromParentEnabled(boolean enabled) { 9715 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 9716 } 9717 9718 9719 /** 9720 * Returns whether this View is currently able to take focus. 9721 * 9722 * @return True if this view can take focus, or false otherwise. 9723 */ 9724 @ViewDebug.ExportedProperty(category = "focus") 9725 public final boolean isFocusable() { 9726 return FOCUSABLE == (mViewFlags & FOCUSABLE); 9727 } 9728 9729 /** 9730 * Returns the focusable setting for this view. 9731 * 9732 * @return One of {@link #NOT_FOCUSABLE}, {@link #FOCUSABLE}, or {@link #FOCUSABLE_AUTO}. 9733 * @attr ref android.R.styleable#View_focusable 9734 */ 9735 @ViewDebug.ExportedProperty(mapping = { 9736 @ViewDebug.IntToString(from = NOT_FOCUSABLE, to = "NOT_FOCUSABLE"), 9737 @ViewDebug.IntToString(from = FOCUSABLE, to = "FOCUSABLE"), 9738 @ViewDebug.IntToString(from = FOCUSABLE_AUTO, to = "FOCUSABLE_AUTO") 9739 }) 9740 @Focusable 9741 public int getFocusable() { 9742 return (mViewFlags & FOCUSABLE_AUTO) > 0 ? FOCUSABLE_AUTO : mViewFlags & FOCUSABLE; 9743 } 9744 9745 /** 9746 * When a view is focusable, it may not want to take focus when in touch mode. 9747 * For example, a button would like focus when the user is navigating via a D-pad 9748 * so that the user can click on it, but once the user starts touching the screen, 9749 * the button shouldn't take focus 9750 * @return Whether the view is focusable in touch mode. 9751 * @attr ref android.R.styleable#View_focusableInTouchMode 9752 */ 9753 @ViewDebug.ExportedProperty 9754 public final boolean isFocusableInTouchMode() { 9755 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 9756 } 9757 9758 /** 9759 * Returns the autofill mode for this view. 9760 * 9761 * @return One of {@link #AUTOFILL_MODE_INHERIT}, {@link #AUTOFILL_MODE_AUTO}, or 9762 * {@link #AUTOFILL_MODE_MANUAL}. 9763 * @attr ref android.R.styleable#View_autofillMode 9764 */ 9765 @ViewDebug.ExportedProperty(mapping = { 9766 @ViewDebug.IntToString(from = AUTOFILL_MODE_INHERIT, to = "AUTOFILL_MODE_INHERIT"), 9767 @ViewDebug.IntToString(from = AUTOFILL_MODE_AUTO, to = "AUTOFILL_MODE_AUTO"), 9768 @ViewDebug.IntToString(from = AUTOFILL_MODE_MANUAL, to = "AUTOFILL_MODE_MANUAL") 9769 }) 9770 @AutofillMode 9771 public int getAutofillMode() { 9772 return (mPrivateFlags3 & PFLAG3_AUTOFILL_MODE_MASK) >> PFLAG3_AUTOFILL_MODE_SHIFT; 9773 } 9774 9775 /** 9776 * Returns the resolved autofill mode for this view. 9777 * 9778 * This is the same as {@link #getAutofillMode()} but if the mode is 9779 * {@link #AUTOFILL_MODE_INHERIT} the parents autofill mode will be returned. 9780 * 9781 * @return One of {@link #AUTOFILL_MODE_AUTO}, or {@link #AUTOFILL_MODE_MANUAL}. If the auto- 9782 * fill mode can not be resolved e.g. {@link #getAutofillMode()} is 9783 * {@link #AUTOFILL_MODE_INHERIT} and the {@link View} is detached 9784 * {@link #AUTOFILL_MODE_AUTO} is returned. 9785 */ 9786 public @AutofillMode int getResolvedAutofillMode() { 9787 @AutofillMode int autofillMode = getAutofillMode(); 9788 9789 if (autofillMode == AUTOFILL_MODE_INHERIT) { 9790 if (mParent == null) { 9791 return AUTOFILL_MODE_AUTO; 9792 } else { 9793 return mParent.getResolvedAutofillMode(); 9794 } 9795 } else { 9796 return autofillMode; 9797 } 9798 } 9799 9800 /** 9801 * Find the nearest view in the specified direction that can take focus. 9802 * This does not actually give focus to that view. 9803 * 9804 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 9805 * 9806 * @return The nearest focusable in the specified direction, or null if none 9807 * can be found. 9808 */ 9809 public View focusSearch(@FocusRealDirection int direction) { 9810 if (mParent != null) { 9811 return mParent.focusSearch(this, direction); 9812 } else { 9813 return null; 9814 } 9815 } 9816 9817 /** 9818 * Returns whether this View is a root of a keyboard navigation cluster. 9819 * 9820 * @return True if this view is a root of a cluster, or false otherwise. 9821 * @attr ref android.R.styleable#View_keyboardNavigationCluster 9822 */ 9823 @ViewDebug.ExportedProperty(category = "keyboardNavigationCluster") 9824 public final boolean isKeyboardNavigationCluster() { 9825 return (mPrivateFlags3 & PFLAG3_CLUSTER) != 0; 9826 } 9827 9828 /** 9829 * Set whether this view is a root of a keyboard navigation cluster. 9830 * 9831 * @param isCluster If true, this view is a root of a cluster. 9832 * 9833 * @attr ref android.R.styleable#View_keyboardNavigationCluster 9834 */ 9835 public void setKeyboardNavigationCluster(boolean isCluster) { 9836 if (isCluster) { 9837 mPrivateFlags3 |= PFLAG3_CLUSTER; 9838 } else { 9839 mPrivateFlags3 &= ~PFLAG3_CLUSTER; 9840 } 9841 } 9842 9843 /** 9844 * Sets this View as the one which receives focus the next time cluster navigation jumps 9845 * to the cluster containing this View. This does NOT change focus even if the cluster 9846 * containing this view is current. 9847 * 9848 * @hide 9849 */ 9850 public void setFocusedInCluster() { 9851 if (mParent instanceof ViewGroup) { 9852 ((ViewGroup) mParent).setFocusInCluster(this); 9853 } 9854 } 9855 9856 /** 9857 * Returns whether this View should receive focus when the focus is restored for the view 9858 * hierarchy containing this view. 9859 * <p> 9860 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 9861 * window or serves as a target of cluster navigation. 9862 * 9863 * @see #restoreDefaultFocus() 9864 * 9865 * @return {@code true} if this view is the default-focus view, {@code false} otherwise 9866 * @attr ref android.R.styleable#View_focusedByDefault 9867 */ 9868 @ViewDebug.ExportedProperty(category = "focusedByDefault") 9869 public final boolean isFocusedByDefault() { 9870 return (mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0; 9871 } 9872 9873 /** 9874 * Sets whether this View should receive focus when the focus is restored for the view 9875 * hierarchy containing this view. 9876 * <p> 9877 * Focus gets restored for a view hierarchy when the root of the hierarchy gets added to a 9878 * window or serves as a target of cluster navigation. 9879 * 9880 * @param isFocusedByDefault {@code true} to set this view as the default-focus view, 9881 * {@code false} otherwise. 9882 * 9883 * @see #restoreDefaultFocus() 9884 * 9885 * @attr ref android.R.styleable#View_focusedByDefault 9886 */ 9887 public void setFocusedByDefault(boolean isFocusedByDefault) { 9888 if (isFocusedByDefault == ((mPrivateFlags3 & PFLAG3_FOCUSED_BY_DEFAULT) != 0)) { 9889 return; 9890 } 9891 9892 if (isFocusedByDefault) { 9893 mPrivateFlags3 |= PFLAG3_FOCUSED_BY_DEFAULT; 9894 } else { 9895 mPrivateFlags3 &= ~PFLAG3_FOCUSED_BY_DEFAULT; 9896 } 9897 9898 if (mParent instanceof ViewGroup) { 9899 if (isFocusedByDefault) { 9900 ((ViewGroup) mParent).setDefaultFocus(this); 9901 } else { 9902 ((ViewGroup) mParent).clearDefaultFocus(this); 9903 } 9904 } 9905 } 9906 9907 /** 9908 * Returns whether the view hierarchy with this view as a root contain a default-focus view. 9909 * 9910 * @return {@code true} if this view has default focus, {@code false} otherwise 9911 */ 9912 boolean hasDefaultFocus() { 9913 return isFocusedByDefault(); 9914 } 9915 9916 /** 9917 * Find the nearest keyboard navigation cluster in the specified direction. 9918 * This does not actually give focus to that cluster. 9919 * 9920 * @param currentCluster The starting point of the search. Null means the current cluster is not 9921 * found yet 9922 * @param direction Direction to look 9923 * 9924 * @return The nearest keyboard navigation cluster in the specified direction, or null if none 9925 * can be found 9926 */ 9927 public View keyboardNavigationClusterSearch(View currentCluster, 9928 @FocusDirection int direction) { 9929 if (isKeyboardNavigationCluster()) { 9930 currentCluster = this; 9931 } 9932 if (isRootNamespace()) { 9933 // Root namespace means we should consider ourselves the top of the 9934 // tree for group searching; otherwise we could be group searching 9935 // into other tabs. see LocalActivityManager and TabHost for more info. 9936 return FocusFinder.getInstance().findNextKeyboardNavigationCluster( 9937 this, currentCluster, direction); 9938 } else if (mParent != null) { 9939 return mParent.keyboardNavigationClusterSearch(currentCluster, direction); 9940 } 9941 return null; 9942 } 9943 9944 /** 9945 * This method is the last chance for the focused view and its ancestors to 9946 * respond to an arrow key. This is called when the focused view did not 9947 * consume the key internally, nor could the view system find a new view in 9948 * the requested direction to give focus to. 9949 * 9950 * @param focused The currently focused view. 9951 * @param direction The direction focus wants to move. One of FOCUS_UP, 9952 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 9953 * @return True if the this view consumed this unhandled move. 9954 */ 9955 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 9956 return false; 9957 } 9958 9959 /** 9960 * Sets whether this View should use a default focus highlight when it gets focused but doesn't 9961 * have {@link android.R.attr#state_focused} defined in its background. 9962 * 9963 * @param defaultFocusHighlightEnabled {@code true} to set this view to use a default focus 9964 * highlight, {@code false} otherwise. 9965 * 9966 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled 9967 */ 9968 public void setDefaultFocusHighlightEnabled(boolean defaultFocusHighlightEnabled) { 9969 mDefaultFocusHighlightEnabled = defaultFocusHighlightEnabled; 9970 } 9971 9972 /** 9973 9974 /** 9975 * Returns whether this View should use a default focus highlight when it gets focused but 9976 * doesn't have {@link android.R.attr#state_focused} defined in its background. 9977 * 9978 * @return True if this View should use a default focus highlight. 9979 * @attr ref android.R.styleable#View_defaultFocusHighlightEnabled 9980 */ 9981 @ViewDebug.ExportedProperty(category = "defaultFocusHighlightEnabled") 9982 public final boolean getDefaultFocusHighlightEnabled() { 9983 return mDefaultFocusHighlightEnabled; 9984 } 9985 9986 /** 9987 * If a user manually specified the next view id for a particular direction, 9988 * use the root to look up the view. 9989 * @param root The root view of the hierarchy containing this view. 9990 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 9991 * or FOCUS_BACKWARD. 9992 * @return The user specified next view, or null if there is none. 9993 */ 9994 View findUserSetNextFocus(View root, @FocusDirection int direction) { 9995 switch (direction) { 9996 case FOCUS_LEFT: 9997 if (mNextFocusLeftId == View.NO_ID) return null; 9998 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 9999 case FOCUS_RIGHT: 10000 if (mNextFocusRightId == View.NO_ID) return null; 10001 return findViewInsideOutShouldExist(root, mNextFocusRightId); 10002 case FOCUS_UP: 10003 if (mNextFocusUpId == View.NO_ID) return null; 10004 return findViewInsideOutShouldExist(root, mNextFocusUpId); 10005 case FOCUS_DOWN: 10006 if (mNextFocusDownId == View.NO_ID) return null; 10007 return findViewInsideOutShouldExist(root, mNextFocusDownId); 10008 case FOCUS_FORWARD: 10009 if (mNextFocusForwardId == View.NO_ID) return null; 10010 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 10011 case FOCUS_BACKWARD: { 10012 if (mID == View.NO_ID) return null; 10013 final int id = mID; 10014 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 10015 @Override 10016 public boolean test(View t) { 10017 return t.mNextFocusForwardId == id; 10018 } 10019 }); 10020 } 10021 } 10022 return null; 10023 } 10024 10025 /** 10026 * If a user manually specified the next keyboard-navigation cluster for a particular direction, 10027 * use the root to look up the view. 10028 * 10029 * @param root the root view of the hierarchy containing this view 10030 * @param direction {@link #FOCUS_FORWARD} or {@link #FOCUS_BACKWARD} 10031 * @return the user-specified next cluster, or {@code null} if there is none 10032 */ 10033 View findUserSetNextKeyboardNavigationCluster(View root, @FocusDirection int direction) { 10034 switch (direction) { 10035 case FOCUS_FORWARD: 10036 if (mNextClusterForwardId == View.NO_ID) return null; 10037 return findViewInsideOutShouldExist(root, mNextClusterForwardId); 10038 case FOCUS_BACKWARD: { 10039 if (mID == View.NO_ID) return null; 10040 final int id = mID; 10041 return root.findViewByPredicateInsideOut(this, 10042 (Predicate<View>) t -> t.mNextClusterForwardId == id); 10043 } 10044 } 10045 return null; 10046 } 10047 10048 private View findViewInsideOutShouldExist(View root, int id) { 10049 if (mMatchIdPredicate == null) { 10050 mMatchIdPredicate = new MatchIdPredicate(); 10051 } 10052 mMatchIdPredicate.mId = id; 10053 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 10054 if (result == null) { 10055 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 10056 } 10057 return result; 10058 } 10059 10060 /** 10061 * Find and return all focusable views that are descendants of this view, 10062 * possibly including this view if it is focusable itself. 10063 * 10064 * @param direction The direction of the focus 10065 * @return A list of focusable views 10066 */ 10067 public ArrayList<View> getFocusables(@FocusDirection int direction) { 10068 ArrayList<View> result = new ArrayList<View>(24); 10069 addFocusables(result, direction); 10070 return result; 10071 } 10072 10073 /** 10074 * Add any focusable views that are descendants of this view (possibly 10075 * including this view if it is focusable itself) to views. If we are in touch mode, 10076 * only add views that are also focusable in touch mode. 10077 * 10078 * @param views Focusable views found so far 10079 * @param direction The direction of the focus 10080 */ 10081 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 10082 addFocusables(views, direction, isInTouchMode() ? FOCUSABLES_TOUCH_MODE : FOCUSABLES_ALL); 10083 } 10084 10085 /** 10086 * Adds any focusable views that are descendants of this view (possibly 10087 * including this view if it is focusable itself) to views. This method 10088 * adds all focusable views regardless if we are in touch mode or 10089 * only views focusable in touch mode if we are in touch mode or 10090 * only views that can take accessibility focus if accessibility is enabled 10091 * depending on the focusable mode parameter. 10092 * 10093 * @param views Focusable views found so far or null if all we are interested is 10094 * the number of focusables. 10095 * @param direction The direction of the focus. 10096 * @param focusableMode The type of focusables to be added. 10097 * 10098 * @see #FOCUSABLES_ALL 10099 * @see #FOCUSABLES_TOUCH_MODE 10100 */ 10101 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 10102 @FocusableMode int focusableMode) { 10103 if (views == null) { 10104 return; 10105 } 10106 if (!isFocusable()) { 10107 return; 10108 } 10109 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 10110 && !isFocusableInTouchMode()) { 10111 return; 10112 } 10113 views.add(this); 10114 } 10115 10116 /** 10117 * Adds any keyboard navigation cluster roots that are descendants of this view (possibly 10118 * including this view if it is a cluster root itself) to views. 10119 * 10120 * @param views Keyboard navigation cluster roots found so far 10121 * @param direction Direction to look 10122 */ 10123 public void addKeyboardNavigationClusters( 10124 @NonNull Collection<View> views, 10125 int direction) { 10126 if (!isKeyboardNavigationCluster()) { 10127 return; 10128 } 10129 if (!hasFocusable()) { 10130 return; 10131 } 10132 views.add(this); 10133 } 10134 10135 /** 10136 * Finds the Views that contain given text. The containment is case insensitive. 10137 * The search is performed by either the text that the View renders or the content 10138 * description that describes the view for accessibility purposes and the view does 10139 * not render or both. Clients can specify how the search is to be performed via 10140 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 10141 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 10142 * 10143 * @param outViews The output list of matching Views. 10144 * @param searched The text to match against. 10145 * 10146 * @see #FIND_VIEWS_WITH_TEXT 10147 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 10148 * @see #setContentDescription(CharSequence) 10149 */ 10150 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 10151 @FindViewFlags int flags) { 10152 if (getAccessibilityNodeProvider() != null) { 10153 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 10154 outViews.add(this); 10155 } 10156 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 10157 && (searched != null && searched.length() > 0) 10158 && (mContentDescription != null && mContentDescription.length() > 0)) { 10159 String searchedLowerCase = searched.toString().toLowerCase(); 10160 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 10161 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 10162 outViews.add(this); 10163 } 10164 } 10165 } 10166 10167 /** 10168 * Find and return all touchable views that are descendants of this view, 10169 * possibly including this view if it is touchable itself. 10170 * 10171 * @return A list of touchable views 10172 */ 10173 public ArrayList<View> getTouchables() { 10174 ArrayList<View> result = new ArrayList<View>(); 10175 addTouchables(result); 10176 return result; 10177 } 10178 10179 /** 10180 * Add any touchable views that are descendants of this view (possibly 10181 * including this view if it is touchable itself) to views. 10182 * 10183 * @param views Touchable views found so far 10184 */ 10185 public void addTouchables(ArrayList<View> views) { 10186 final int viewFlags = mViewFlags; 10187 10188 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 10189 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) 10190 && (viewFlags & ENABLED_MASK) == ENABLED) { 10191 views.add(this); 10192 } 10193 } 10194 10195 /** 10196 * Returns whether this View is accessibility focused. 10197 * 10198 * @return True if this View is accessibility focused. 10199 */ 10200 public boolean isAccessibilityFocused() { 10201 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 10202 } 10203 10204 /** 10205 * Call this to try to give accessibility focus to this view. 10206 * 10207 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 10208 * returns false or the view is no visible or the view already has accessibility 10209 * focus. 10210 * 10211 * See also {@link #focusSearch(int)}, which is what you call to say that you 10212 * have focus, and you want your parent to look for the next one. 10213 * 10214 * @return Whether this view actually took accessibility focus. 10215 * 10216 * @hide 10217 */ 10218 public boolean requestAccessibilityFocus() { 10219 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 10220 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 10221 return false; 10222 } 10223 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 10224 return false; 10225 } 10226 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 10227 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 10228 ViewRootImpl viewRootImpl = getViewRootImpl(); 10229 if (viewRootImpl != null) { 10230 viewRootImpl.setAccessibilityFocus(this, null); 10231 } 10232 invalidate(); 10233 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 10234 return true; 10235 } 10236 return false; 10237 } 10238 10239 /** 10240 * Call this to try to clear accessibility focus of this view. 10241 * 10242 * See also {@link #focusSearch(int)}, which is what you call to say that you 10243 * have focus, and you want your parent to look for the next one. 10244 * 10245 * @hide 10246 */ 10247 public void clearAccessibilityFocus() { 10248 clearAccessibilityFocusNoCallbacks(0); 10249 10250 // Clear the global reference of accessibility focus if this view or 10251 // any of its descendants had accessibility focus. This will NOT send 10252 // an event or update internal state if focus is cleared from a 10253 // descendant view, which may leave views in inconsistent states. 10254 final ViewRootImpl viewRootImpl = getViewRootImpl(); 10255 if (viewRootImpl != null) { 10256 final View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 10257 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 10258 viewRootImpl.setAccessibilityFocus(null, null); 10259 } 10260 } 10261 } 10262 10263 private void sendAccessibilityHoverEvent(int eventType) { 10264 // Since we are not delivering to a client accessibility events from not 10265 // important views (unless the clinet request that) we need to fire the 10266 // event from the deepest view exposed to the client. As a consequence if 10267 // the user crosses a not exposed view the client will see enter and exit 10268 // of the exposed predecessor followed by and enter and exit of that same 10269 // predecessor when entering and exiting the not exposed descendant. This 10270 // is fine since the client has a clear idea which view is hovered at the 10271 // price of a couple more events being sent. This is a simple and 10272 // working solution. 10273 View source = this; 10274 while (true) { 10275 if (source.includeForAccessibility()) { 10276 source.sendAccessibilityEvent(eventType); 10277 return; 10278 } 10279 ViewParent parent = source.getParent(); 10280 if (parent instanceof View) { 10281 source = (View) parent; 10282 } else { 10283 return; 10284 } 10285 } 10286 } 10287 10288 /** 10289 * Clears accessibility focus without calling any callback methods 10290 * normally invoked in {@link #clearAccessibilityFocus()}. This method 10291 * is used separately from that one for clearing accessibility focus when 10292 * giving this focus to another view. 10293 * 10294 * @param action The action, if any, that led to focus being cleared. Set to 10295 * AccessibilityNodeInfo#ACTION_ACCESSIBILITY_FOCUS to specify that focus is moving within 10296 * the window. 10297 */ 10298 void clearAccessibilityFocusNoCallbacks(int action) { 10299 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 10300 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 10301 invalidate(); 10302 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 10303 AccessibilityEvent event = AccessibilityEvent.obtain( 10304 AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 10305 event.setAction(action); 10306 if (mAccessibilityDelegate != null) { 10307 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 10308 } else { 10309 sendAccessibilityEventUnchecked(event); 10310 } 10311 } 10312 } 10313 } 10314 10315 /** 10316 * Call this to try to give focus to a specific view or to one of its 10317 * descendants. 10318 * 10319 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 10320 * false), or if it is focusable and it is not focusable in touch mode 10321 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 10322 * 10323 * See also {@link #focusSearch(int)}, which is what you call to say that you 10324 * have focus, and you want your parent to look for the next one. 10325 * 10326 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 10327 * {@link #FOCUS_DOWN} and <code>null</code>. 10328 * 10329 * @return Whether this view or one of its descendants actually took focus. 10330 */ 10331 public final boolean requestFocus() { 10332 return requestFocus(View.FOCUS_DOWN); 10333 } 10334 10335 /** 10336 * This will request focus for whichever View was last focused within this 10337 * cluster before a focus-jump out of it. 10338 * 10339 * @hide 10340 */ 10341 @TestApi 10342 public boolean restoreFocusInCluster(@FocusRealDirection int direction) { 10343 // Prioritize focusableByDefault over algorithmic focus selection. 10344 if (restoreDefaultFocus()) { 10345 return true; 10346 } 10347 return requestFocus(direction); 10348 } 10349 10350 /** 10351 * This will request focus for whichever View not in a cluster was last focused before a 10352 * focus-jump to a cluster. If no non-cluster View has previously had focus, this will focus 10353 * the "first" focusable view it finds. 10354 * 10355 * @hide 10356 */ 10357 @TestApi 10358 public boolean restoreFocusNotInCluster() { 10359 return requestFocus(View.FOCUS_DOWN); 10360 } 10361 10362 /** 10363 * Gives focus to the default-focus view in the view hierarchy that has this view as a root. 10364 * If the default-focus view cannot be found, falls back to calling {@link #requestFocus(int)}. 10365 * 10366 * @return Whether this view or one of its descendants actually took focus 10367 */ 10368 public boolean restoreDefaultFocus() { 10369 return requestFocus(View.FOCUS_DOWN); 10370 } 10371 10372 /** 10373 * Call this to try to give focus to a specific view or to one of its 10374 * descendants and give it a hint about what direction focus is heading. 10375 * 10376 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 10377 * false), or if it is focusable and it is not focusable in touch mode 10378 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 10379 * 10380 * See also {@link #focusSearch(int)}, which is what you call to say that you 10381 * have focus, and you want your parent to look for the next one. 10382 * 10383 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 10384 * <code>null</code> set for the previously focused rectangle. 10385 * 10386 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 10387 * @return Whether this view or one of its descendants actually took focus. 10388 */ 10389 public final boolean requestFocus(int direction) { 10390 return requestFocus(direction, null); 10391 } 10392 10393 /** 10394 * Call this to try to give focus to a specific view or to one of its descendants 10395 * and give it hints about the direction and a specific rectangle that the focus 10396 * is coming from. The rectangle can help give larger views a finer grained hint 10397 * about where focus is coming from, and therefore, where to show selection, or 10398 * forward focus change internally. 10399 * 10400 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 10401 * false), or if it is focusable and it is not focusable in touch mode 10402 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 10403 * 10404 * A View will not take focus if it is not visible. 10405 * 10406 * A View will not take focus if one of its parents has 10407 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 10408 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 10409 * 10410 * See also {@link #focusSearch(int)}, which is what you call to say that you 10411 * have focus, and you want your parent to look for the next one. 10412 * 10413 * You may wish to override this method if your custom {@link View} has an internal 10414 * {@link View} that it wishes to forward the request to. 10415 * 10416 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 10417 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 10418 * to give a finer grained hint about where focus is coming from. May be null 10419 * if there is no hint. 10420 * @return Whether this view or one of its descendants actually took focus. 10421 */ 10422 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 10423 return requestFocusNoSearch(direction, previouslyFocusedRect); 10424 } 10425 10426 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 10427 // need to be focusable 10428 if ((mViewFlags & FOCUSABLE) != FOCUSABLE 10429 || (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 10430 return false; 10431 } 10432 10433 // need to be focusable in touch mode if in touch mode 10434 if (isInTouchMode() && 10435 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 10436 return false; 10437 } 10438 10439 // need to not have any parents blocking us 10440 if (hasAncestorThatBlocksDescendantFocus()) { 10441 return false; 10442 } 10443 10444 handleFocusGainInternal(direction, previouslyFocusedRect); 10445 return true; 10446 } 10447 10448 /** 10449 * Call this to try to give focus to a specific view or to one of its descendants. This is a 10450 * special variant of {@link #requestFocus() } that will allow views that are not focusable in 10451 * touch mode to request focus when they are touched. 10452 * 10453 * @return Whether this view or one of its descendants actually took focus. 10454 * 10455 * @see #isInTouchMode() 10456 * 10457 */ 10458 public final boolean requestFocusFromTouch() { 10459 // Leave touch mode if we need to 10460 if (isInTouchMode()) { 10461 ViewRootImpl viewRoot = getViewRootImpl(); 10462 if (viewRoot != null) { 10463 viewRoot.ensureTouchMode(false); 10464 } 10465 } 10466 return requestFocus(View.FOCUS_DOWN); 10467 } 10468 10469 /** 10470 * @return Whether any ancestor of this view blocks descendant focus. 10471 */ 10472 private boolean hasAncestorThatBlocksDescendantFocus() { 10473 final boolean focusableInTouchMode = isFocusableInTouchMode(); 10474 ViewParent ancestor = mParent; 10475 while (ancestor instanceof ViewGroup) { 10476 final ViewGroup vgAncestor = (ViewGroup) ancestor; 10477 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 10478 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 10479 return true; 10480 } else { 10481 ancestor = vgAncestor.getParent(); 10482 } 10483 } 10484 return false; 10485 } 10486 10487 /** 10488 * Gets the mode for determining whether this View is important for accessibility. 10489 * A view is important for accessibility if it fires accessibility events and if it 10490 * is reported to accessibility services that query the screen. 10491 * 10492 * @return The mode for determining whether a view is important for accessibility, one 10493 * of {@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, {@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, 10494 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO}, or 10495 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}. 10496 * 10497 * @attr ref android.R.styleable#View_importantForAccessibility 10498 * 10499 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 10500 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 10501 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 10502 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 10503 */ 10504 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 10505 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 10506 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 10507 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 10508 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 10509 to = "noHideDescendants") 10510 }) 10511 public int getImportantForAccessibility() { 10512 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 10513 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 10514 } 10515 10516 /** 10517 * Sets the live region mode for this view. This indicates to accessibility 10518 * services whether they should automatically notify the user about changes 10519 * to the view's content description or text, or to the content descriptions 10520 * or text of the view's children (where applicable). 10521 * <p> 10522 * For example, in a login screen with a TextView that displays an "incorrect 10523 * password" notification, that view should be marked as a live region with 10524 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 10525 * <p> 10526 * To disable change notifications for this view, use 10527 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 10528 * mode for most views. 10529 * <p> 10530 * To indicate that the user should be notified of changes, use 10531 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 10532 * <p> 10533 * If the view's changes should interrupt ongoing speech and notify the user 10534 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 10535 * 10536 * @param mode The live region mode for this view, one of: 10537 * <ul> 10538 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 10539 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 10540 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 10541 * </ul> 10542 * @attr ref android.R.styleable#View_accessibilityLiveRegion 10543 */ 10544 public void setAccessibilityLiveRegion(int mode) { 10545 if (mode != getAccessibilityLiveRegion()) { 10546 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 10547 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 10548 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 10549 notifyViewAccessibilityStateChangedIfNeeded( 10550 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10551 } 10552 } 10553 10554 /** 10555 * Gets the live region mode for this View. 10556 * 10557 * @return The live region mode for the view. 10558 * 10559 * @attr ref android.R.styleable#View_accessibilityLiveRegion 10560 * 10561 * @see #setAccessibilityLiveRegion(int) 10562 */ 10563 public int getAccessibilityLiveRegion() { 10564 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 10565 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 10566 } 10567 10568 /** 10569 * Sets how to determine whether this view is important for accessibility 10570 * which is if it fires accessibility events and if it is reported to 10571 * accessibility services that query the screen. 10572 * 10573 * @param mode How to determine whether this view is important for accessibility. 10574 * 10575 * @attr ref android.R.styleable#View_importantForAccessibility 10576 * 10577 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 10578 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 10579 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 10580 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 10581 */ 10582 public void setImportantForAccessibility(int mode) { 10583 final int oldMode = getImportantForAccessibility(); 10584 if (mode != oldMode) { 10585 final boolean hideDescendants = 10586 mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS; 10587 10588 // If this node or its descendants are no longer important, try to 10589 // clear accessibility focus. 10590 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO || hideDescendants) { 10591 final View focusHost = findAccessibilityFocusHost(hideDescendants); 10592 if (focusHost != null) { 10593 focusHost.clearAccessibilityFocus(); 10594 } 10595 } 10596 10597 // If we're moving between AUTO and another state, we might not need 10598 // to send a subtree changed notification. We'll store the computed 10599 // importance, since we'll need to check it later to make sure. 10600 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 10601 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 10602 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 10603 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 10604 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 10605 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 10606 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 10607 notifySubtreeAccessibilityStateChangedIfNeeded(); 10608 } else { 10609 notifyViewAccessibilityStateChangedIfNeeded( 10610 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10611 } 10612 } 10613 } 10614 10615 /** 10616 * Returns the view within this view's hierarchy that is hosting 10617 * accessibility focus. 10618 * 10619 * @param searchDescendants whether to search for focus in descendant views 10620 * @return the view hosting accessibility focus, or {@code null} 10621 */ 10622 private View findAccessibilityFocusHost(boolean searchDescendants) { 10623 if (isAccessibilityFocusedViewOrHost()) { 10624 return this; 10625 } 10626 10627 if (searchDescendants) { 10628 final ViewRootImpl viewRoot = getViewRootImpl(); 10629 if (viewRoot != null) { 10630 final View focusHost = viewRoot.getAccessibilityFocusedHost(); 10631 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 10632 return focusHost; 10633 } 10634 } 10635 } 10636 10637 return null; 10638 } 10639 10640 /** 10641 * Computes whether this view should be exposed for accessibility. In 10642 * general, views that are interactive or provide information are exposed 10643 * while views that serve only as containers are hidden. 10644 * <p> 10645 * If an ancestor of this view has importance 10646 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 10647 * returns <code>false</code>. 10648 * <p> 10649 * Otherwise, the value is computed according to the view's 10650 * {@link #getImportantForAccessibility()} value: 10651 * <ol> 10652 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 10653 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 10654 * </code> 10655 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 10656 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 10657 * view satisfies any of the following: 10658 * <ul> 10659 * <li>Is actionable, e.g. {@link #isClickable()}, 10660 * {@link #isLongClickable()}, or {@link #isFocusable()} 10661 * <li>Has an {@link AccessibilityDelegate} 10662 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 10663 * {@link OnKeyListener}, etc. 10664 * <li>Is an accessibility live region, e.g. 10665 * {@link #getAccessibilityLiveRegion()} is not 10666 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 10667 * </ul> 10668 * </ol> 10669 * 10670 * @return Whether the view is exposed for accessibility. 10671 * @see #setImportantForAccessibility(int) 10672 * @see #getImportantForAccessibility() 10673 */ 10674 public boolean isImportantForAccessibility() { 10675 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 10676 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 10677 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 10678 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 10679 return false; 10680 } 10681 10682 // Check parent mode to ensure we're not hidden. 10683 ViewParent parent = mParent; 10684 while (parent instanceof View) { 10685 if (((View) parent).getImportantForAccessibility() 10686 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 10687 return false; 10688 } 10689 parent = parent.getParent(); 10690 } 10691 10692 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 10693 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 10694 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 10695 } 10696 10697 /** 10698 * Gets the parent for accessibility purposes. Note that the parent for 10699 * accessibility is not necessary the immediate parent. It is the first 10700 * predecessor that is important for accessibility. 10701 * 10702 * @return The parent for accessibility purposes. 10703 */ 10704 public ViewParent getParentForAccessibility() { 10705 if (mParent instanceof View) { 10706 View parentView = (View) mParent; 10707 if (parentView.includeForAccessibility()) { 10708 return mParent; 10709 } else { 10710 return mParent.getParentForAccessibility(); 10711 } 10712 } 10713 return null; 10714 } 10715 10716 /** 10717 * Adds the children of this View relevant for accessibility to the given list 10718 * as output. Since some Views are not important for accessibility the added 10719 * child views are not necessarily direct children of this view, rather they are 10720 * the first level of descendants important for accessibility. 10721 * 10722 * @param outChildren The output list that will receive children for accessibility. 10723 */ 10724 public void addChildrenForAccessibility(ArrayList<View> outChildren) { 10725 10726 } 10727 10728 /** 10729 * Whether to regard this view for accessibility. A view is regarded for 10730 * accessibility if it is important for accessibility or the querying 10731 * accessibility service has explicitly requested that view not 10732 * important for accessibility are regarded. 10733 * 10734 * @return Whether to regard the view for accessibility. 10735 * 10736 * @hide 10737 */ 10738 public boolean includeForAccessibility() { 10739 if (mAttachInfo != null) { 10740 return (mAttachInfo.mAccessibilityFetchFlags 10741 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 10742 || isImportantForAccessibility(); 10743 } 10744 return false; 10745 } 10746 10747 /** 10748 * Returns whether the View is considered actionable from 10749 * accessibility perspective. Such view are important for 10750 * accessibility. 10751 * 10752 * @return True if the view is actionable for accessibility. 10753 * 10754 * @hide 10755 */ 10756 public boolean isActionableForAccessibility() { 10757 return (isClickable() || isLongClickable() || isFocusable()); 10758 } 10759 10760 /** 10761 * Returns whether the View has registered callbacks which makes it 10762 * important for accessibility. 10763 * 10764 * @return True if the view is actionable for accessibility. 10765 */ 10766 private boolean hasListenersForAccessibility() { 10767 ListenerInfo info = getListenerInfo(); 10768 return mTouchDelegate != null || info.mOnKeyListener != null 10769 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 10770 || info.mOnHoverListener != null || info.mOnDragListener != null; 10771 } 10772 10773 /** 10774 * Notifies that the accessibility state of this view changed. The change 10775 * is local to this view and does not represent structural changes such 10776 * as children and parent. For example, the view became focusable. The 10777 * notification is at at most once every 10778 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 10779 * to avoid unnecessary load to the system. Also once a view has a pending 10780 * notification this method is a NOP until the notification has been sent. 10781 * 10782 * @hide 10783 */ 10784 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 10785 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 10786 return; 10787 } 10788 if (mSendViewStateChangedAccessibilityEvent == null) { 10789 mSendViewStateChangedAccessibilityEvent = 10790 new SendViewStateChangedAccessibilityEvent(); 10791 } 10792 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 10793 } 10794 10795 /** 10796 * Notifies that the accessibility state of this view changed. The change 10797 * is *not* local to this view and does represent structural changes such 10798 * as children and parent. For example, the view size changed. The 10799 * notification is at at most once every 10800 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 10801 * to avoid unnecessary load to the system. Also once a view has a pending 10802 * notification this method is a NOP until the notification has been sent. 10803 * 10804 * @hide 10805 */ 10806 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 10807 if (!AccessibilityManager.getInstance(mContext).isEnabled() || mAttachInfo == null) { 10808 return; 10809 } 10810 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 10811 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 10812 if (mParent != null) { 10813 try { 10814 mParent.notifySubtreeAccessibilityStateChanged( 10815 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 10816 } catch (AbstractMethodError e) { 10817 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 10818 " does not fully implement ViewParent", e); 10819 } 10820 } 10821 } 10822 } 10823 10824 /** 10825 * Change the visibility of the View without triggering any other changes. This is 10826 * important for transitions, where visibility changes should not adjust focus or 10827 * trigger a new layout. This is only used when the visibility has already been changed 10828 * and we need a transient value during an animation. When the animation completes, 10829 * the original visibility value is always restored. 10830 * 10831 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 10832 * @hide 10833 */ 10834 public void setTransitionVisibility(@Visibility int visibility) { 10835 mViewFlags = (mViewFlags & ~View.VISIBILITY_MASK) | visibility; 10836 } 10837 10838 /** 10839 * Reset the flag indicating the accessibility state of the subtree rooted 10840 * at this view changed. 10841 */ 10842 void resetSubtreeAccessibilityStateChanged() { 10843 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 10844 } 10845 10846 /** 10847 * Report an accessibility action to this view's parents for delegated processing. 10848 * 10849 * <p>Implementations of {@link #performAccessibilityAction(int, Bundle)} may internally 10850 * call this method to delegate an accessibility action to a supporting parent. If the parent 10851 * returns true from its 10852 * {@link ViewParent#onNestedPrePerformAccessibilityAction(View, int, android.os.Bundle)} 10853 * method this method will return true to signify that the action was consumed.</p> 10854 * 10855 * <p>This method is useful for implementing nested scrolling child views. If 10856 * {@link #isNestedScrollingEnabled()} returns true and the action is a scrolling action 10857 * a custom view implementation may invoke this method to allow a parent to consume the 10858 * scroll first. If this method returns true the custom view should skip its own scrolling 10859 * behavior.</p> 10860 * 10861 * @param action Accessibility action to delegate 10862 * @param arguments Optional action arguments 10863 * @return true if the action was consumed by a parent 10864 */ 10865 public boolean dispatchNestedPrePerformAccessibilityAction(int action, Bundle arguments) { 10866 for (ViewParent p = getParent(); p != null; p = p.getParent()) { 10867 if (p.onNestedPrePerformAccessibilityAction(this, action, arguments)) { 10868 return true; 10869 } 10870 } 10871 return false; 10872 } 10873 10874 /** 10875 * Performs the specified accessibility action on the view. For 10876 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 10877 * <p> 10878 * If an {@link AccessibilityDelegate} has been specified via calling 10879 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 10880 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 10881 * is responsible for handling this call. 10882 * </p> 10883 * 10884 * <p>The default implementation will delegate 10885 * {@link AccessibilityNodeInfo#ACTION_SCROLL_BACKWARD} and 10886 * {@link AccessibilityNodeInfo#ACTION_SCROLL_FORWARD} to nested scrolling parents if 10887 * {@link #isNestedScrollingEnabled() nested scrolling is enabled} on this view.</p> 10888 * 10889 * @param action The action to perform. 10890 * @param arguments Optional action arguments. 10891 * @return Whether the action was performed. 10892 */ 10893 public boolean performAccessibilityAction(int action, Bundle arguments) { 10894 if (mAccessibilityDelegate != null) { 10895 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 10896 } else { 10897 return performAccessibilityActionInternal(action, arguments); 10898 } 10899 } 10900 10901 /** 10902 * @see #performAccessibilityAction(int, Bundle) 10903 * 10904 * Note: Called from the default {@link AccessibilityDelegate}. 10905 * 10906 * @hide 10907 */ 10908 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 10909 if (isNestedScrollingEnabled() 10910 && (action == AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD 10911 || action == AccessibilityNodeInfo.ACTION_SCROLL_FORWARD 10912 || action == R.id.accessibilityActionScrollUp 10913 || action == R.id.accessibilityActionScrollLeft 10914 || action == R.id.accessibilityActionScrollDown 10915 || action == R.id.accessibilityActionScrollRight)) { 10916 if (dispatchNestedPrePerformAccessibilityAction(action, arguments)) { 10917 return true; 10918 } 10919 } 10920 10921 switch (action) { 10922 case AccessibilityNodeInfo.ACTION_CLICK: { 10923 if (isClickable()) { 10924 performClick(); 10925 return true; 10926 } 10927 } break; 10928 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 10929 if (isLongClickable()) { 10930 performLongClick(); 10931 return true; 10932 } 10933 } break; 10934 case AccessibilityNodeInfo.ACTION_FOCUS: { 10935 if (!hasFocus()) { 10936 // Get out of touch mode since accessibility 10937 // wants to move focus around. 10938 getViewRootImpl().ensureTouchMode(false); 10939 return requestFocus(); 10940 } 10941 } break; 10942 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 10943 if (hasFocus()) { 10944 clearFocus(); 10945 return !isFocused(); 10946 } 10947 } break; 10948 case AccessibilityNodeInfo.ACTION_SELECT: { 10949 if (!isSelected()) { 10950 setSelected(true); 10951 return isSelected(); 10952 } 10953 } break; 10954 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 10955 if (isSelected()) { 10956 setSelected(false); 10957 return !isSelected(); 10958 } 10959 } break; 10960 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 10961 if (!isAccessibilityFocused()) { 10962 return requestAccessibilityFocus(); 10963 } 10964 } break; 10965 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 10966 if (isAccessibilityFocused()) { 10967 clearAccessibilityFocus(); 10968 return true; 10969 } 10970 } break; 10971 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 10972 if (arguments != null) { 10973 final int granularity = arguments.getInt( 10974 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 10975 final boolean extendSelection = arguments.getBoolean( 10976 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 10977 return traverseAtGranularity(granularity, true, extendSelection); 10978 } 10979 } break; 10980 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 10981 if (arguments != null) { 10982 final int granularity = arguments.getInt( 10983 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 10984 final boolean extendSelection = arguments.getBoolean( 10985 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 10986 return traverseAtGranularity(granularity, false, extendSelection); 10987 } 10988 } break; 10989 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 10990 CharSequence text = getIterableTextForAccessibility(); 10991 if (text == null) { 10992 return false; 10993 } 10994 final int start = (arguments != null) ? arguments.getInt( 10995 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 10996 final int end = (arguments != null) ? arguments.getInt( 10997 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 10998 // Only cursor position can be specified (selection length == 0) 10999 if ((getAccessibilitySelectionStart() != start 11000 || getAccessibilitySelectionEnd() != end) 11001 && (start == end)) { 11002 setAccessibilitySelection(start, end); 11003 notifyViewAccessibilityStateChangedIfNeeded( 11004 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 11005 return true; 11006 } 11007 } break; 11008 case R.id.accessibilityActionShowOnScreen: { 11009 if (mAttachInfo != null) { 11010 final Rect r = mAttachInfo.mTmpInvalRect; 11011 getDrawingRect(r); 11012 return requestRectangleOnScreen(r, true); 11013 } 11014 } break; 11015 case R.id.accessibilityActionContextClick: { 11016 if (isContextClickable()) { 11017 performContextClick(); 11018 return true; 11019 } 11020 } break; 11021 } 11022 return false; 11023 } 11024 11025 private boolean traverseAtGranularity(int granularity, boolean forward, 11026 boolean extendSelection) { 11027 CharSequence text = getIterableTextForAccessibility(); 11028 if (text == null || text.length() == 0) { 11029 return false; 11030 } 11031 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 11032 if (iterator == null) { 11033 return false; 11034 } 11035 int current = getAccessibilitySelectionEnd(); 11036 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 11037 current = forward ? 0 : text.length(); 11038 } 11039 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 11040 if (range == null) { 11041 return false; 11042 } 11043 final int segmentStart = range[0]; 11044 final int segmentEnd = range[1]; 11045 int selectionStart; 11046 int selectionEnd; 11047 if (extendSelection && isAccessibilitySelectionExtendable()) { 11048 selectionStart = getAccessibilitySelectionStart(); 11049 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 11050 selectionStart = forward ? segmentStart : segmentEnd; 11051 } 11052 selectionEnd = forward ? segmentEnd : segmentStart; 11053 } else { 11054 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 11055 } 11056 setAccessibilitySelection(selectionStart, selectionEnd); 11057 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 11058 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 11059 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 11060 return true; 11061 } 11062 11063 /** 11064 * Gets the text reported for accessibility purposes. 11065 * 11066 * @return The accessibility text. 11067 * 11068 * @hide 11069 */ 11070 public CharSequence getIterableTextForAccessibility() { 11071 return getContentDescription(); 11072 } 11073 11074 /** 11075 * Gets whether accessibility selection can be extended. 11076 * 11077 * @return If selection is extensible. 11078 * 11079 * @hide 11080 */ 11081 public boolean isAccessibilitySelectionExtendable() { 11082 return false; 11083 } 11084 11085 /** 11086 * @hide 11087 */ 11088 public int getAccessibilitySelectionStart() { 11089 return mAccessibilityCursorPosition; 11090 } 11091 11092 /** 11093 * @hide 11094 */ 11095 public int getAccessibilitySelectionEnd() { 11096 return getAccessibilitySelectionStart(); 11097 } 11098 11099 /** 11100 * @hide 11101 */ 11102 public void setAccessibilitySelection(int start, int end) { 11103 if (start == end && end == mAccessibilityCursorPosition) { 11104 return; 11105 } 11106 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 11107 mAccessibilityCursorPosition = start; 11108 } else { 11109 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 11110 } 11111 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 11112 } 11113 11114 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 11115 int fromIndex, int toIndex) { 11116 if (mParent == null) { 11117 return; 11118 } 11119 AccessibilityEvent event = AccessibilityEvent.obtain( 11120 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 11121 onInitializeAccessibilityEvent(event); 11122 onPopulateAccessibilityEvent(event); 11123 event.setFromIndex(fromIndex); 11124 event.setToIndex(toIndex); 11125 event.setAction(action); 11126 event.setMovementGranularity(granularity); 11127 mParent.requestSendAccessibilityEvent(this, event); 11128 } 11129 11130 /** 11131 * @hide 11132 */ 11133 public TextSegmentIterator getIteratorForGranularity(int granularity) { 11134 switch (granularity) { 11135 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 11136 CharSequence text = getIterableTextForAccessibility(); 11137 if (text != null && text.length() > 0) { 11138 CharacterTextSegmentIterator iterator = 11139 CharacterTextSegmentIterator.getInstance( 11140 mContext.getResources().getConfiguration().locale); 11141 iterator.initialize(text.toString()); 11142 return iterator; 11143 } 11144 } break; 11145 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 11146 CharSequence text = getIterableTextForAccessibility(); 11147 if (text != null && text.length() > 0) { 11148 WordTextSegmentIterator iterator = 11149 WordTextSegmentIterator.getInstance( 11150 mContext.getResources().getConfiguration().locale); 11151 iterator.initialize(text.toString()); 11152 return iterator; 11153 } 11154 } break; 11155 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 11156 CharSequence text = getIterableTextForAccessibility(); 11157 if (text != null && text.length() > 0) { 11158 ParagraphTextSegmentIterator iterator = 11159 ParagraphTextSegmentIterator.getInstance(); 11160 iterator.initialize(text.toString()); 11161 return iterator; 11162 } 11163 } break; 11164 } 11165 return null; 11166 } 11167 11168 /** 11169 * Tells whether the {@link View} is in the state between {@link #onStartTemporaryDetach()} 11170 * and {@link #onFinishTemporaryDetach()}. 11171 * 11172 * <p>This method always returns {@code true} when called directly or indirectly from 11173 * {@link #onStartTemporaryDetach()}. The return value when called directly or indirectly from 11174 * {@link #onFinishTemporaryDetach()}, however, depends on the OS version. 11175 * <ul> 11176 * <li>{@code true} on {@link android.os.Build.VERSION_CODES#N API 24}</li> 11177 * <li>{@code false} on {@link android.os.Build.VERSION_CODES#N_MR1 API 25}} and later</li> 11178 * </ul> 11179 * </p> 11180 * 11181 * @return {@code true} when the View is in the state between {@link #onStartTemporaryDetach()} 11182 * and {@link #onFinishTemporaryDetach()}. 11183 */ 11184 public final boolean isTemporarilyDetached() { 11185 return (mPrivateFlags3 & PFLAG3_TEMPORARY_DETACH) != 0; 11186 } 11187 11188 /** 11189 * Dispatch {@link #onStartTemporaryDetach()} to this View and its direct children if this is 11190 * a container View. 11191 */ 11192 @CallSuper 11193 public void dispatchStartTemporaryDetach() { 11194 mPrivateFlags3 |= PFLAG3_TEMPORARY_DETACH; 11195 notifyEnterOrExitForAutoFillIfNeeded(false); 11196 onStartTemporaryDetach(); 11197 } 11198 11199 /** 11200 * This is called when a container is going to temporarily detach a child, with 11201 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 11202 * It will either be followed by {@link #onFinishTemporaryDetach()} or 11203 * {@link #onDetachedFromWindow()} when the container is done. 11204 */ 11205 public void onStartTemporaryDetach() { 11206 removeUnsetPressCallback(); 11207 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 11208 } 11209 11210 /** 11211 * Dispatch {@link #onFinishTemporaryDetach()} to this View and its direct children if this is 11212 * a container View. 11213 */ 11214 @CallSuper 11215 public void dispatchFinishTemporaryDetach() { 11216 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 11217 onFinishTemporaryDetach(); 11218 if (hasWindowFocus() && hasFocus()) { 11219 InputMethodManager.getInstance().focusIn(this); 11220 } 11221 notifyEnterOrExitForAutoFillIfNeeded(true); 11222 } 11223 11224 /** 11225 * Called after {@link #onStartTemporaryDetach} when the container is done 11226 * changing the view. 11227 */ 11228 public void onFinishTemporaryDetach() { 11229 } 11230 11231 /** 11232 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 11233 * for this view's window. Returns null if the view is not currently attached 11234 * to the window. Normally you will not need to use this directly, but 11235 * just use the standard high-level event callbacks like 11236 * {@link #onKeyDown(int, KeyEvent)}. 11237 */ 11238 public KeyEvent.DispatcherState getKeyDispatcherState() { 11239 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 11240 } 11241 11242 /** 11243 * Dispatch a key event before it is processed by any input method 11244 * associated with the view hierarchy. This can be used to intercept 11245 * key events in special situations before the IME consumes them; a 11246 * typical example would be handling the BACK key to update the application's 11247 * UI instead of allowing the IME to see it and close itself. 11248 * 11249 * @param event The key event to be dispatched. 11250 * @return True if the event was handled, false otherwise. 11251 */ 11252 public boolean dispatchKeyEventPreIme(KeyEvent event) { 11253 return onKeyPreIme(event.getKeyCode(), event); 11254 } 11255 11256 /** 11257 * Dispatch a key event to the next view on the focus path. This path runs 11258 * from the top of the view tree down to the currently focused view. If this 11259 * view has focus, it will dispatch to itself. Otherwise it will dispatch 11260 * the next node down the focus path. This method also fires any key 11261 * listeners. 11262 * 11263 * @param event The key event to be dispatched. 11264 * @return True if the event was handled, false otherwise. 11265 */ 11266 public boolean dispatchKeyEvent(KeyEvent event) { 11267 if (mInputEventConsistencyVerifier != null) { 11268 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 11269 } 11270 11271 // Give any attached key listener a first crack at the event. 11272 //noinspection SimplifiableIfStatement 11273 ListenerInfo li = mListenerInfo; 11274 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 11275 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 11276 return true; 11277 } 11278 11279 if (event.dispatch(this, mAttachInfo != null 11280 ? mAttachInfo.mKeyDispatchState : null, this)) { 11281 return true; 11282 } 11283 11284 if (mInputEventConsistencyVerifier != null) { 11285 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11286 } 11287 return false; 11288 } 11289 11290 /** 11291 * Dispatches a key shortcut event. 11292 * 11293 * @param event The key event to be dispatched. 11294 * @return True if the event was handled by the view, false otherwise. 11295 */ 11296 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 11297 return onKeyShortcut(event.getKeyCode(), event); 11298 } 11299 11300 /** 11301 * Pass the touch screen motion event down to the target view, or this 11302 * view if it is the target. 11303 * 11304 * @param event The motion event to be dispatched. 11305 * @return True if the event was handled by the view, false otherwise. 11306 */ 11307 public boolean dispatchTouchEvent(MotionEvent event) { 11308 // If the event should be handled by accessibility focus first. 11309 if (event.isTargetAccessibilityFocus()) { 11310 // We don't have focus or no virtual descendant has it, do not handle the event. 11311 if (!isAccessibilityFocusedViewOrHost()) { 11312 return false; 11313 } 11314 // We have focus and got the event, then use normal event dispatch. 11315 event.setTargetAccessibilityFocus(false); 11316 } 11317 11318 boolean result = false; 11319 11320 if (mInputEventConsistencyVerifier != null) { 11321 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 11322 } 11323 11324 final int actionMasked = event.getActionMasked(); 11325 if (actionMasked == MotionEvent.ACTION_DOWN) { 11326 // Defensive cleanup for new gesture 11327 stopNestedScroll(); 11328 } 11329 11330 if (onFilterTouchEventForSecurity(event)) { 11331 if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) { 11332 result = true; 11333 } 11334 //noinspection SimplifiableIfStatement 11335 ListenerInfo li = mListenerInfo; 11336 if (li != null && li.mOnTouchListener != null 11337 && (mViewFlags & ENABLED_MASK) == ENABLED 11338 && li.mOnTouchListener.onTouch(this, event)) { 11339 result = true; 11340 } 11341 11342 if (!result && onTouchEvent(event)) { 11343 result = true; 11344 } 11345 } 11346 11347 if (!result && mInputEventConsistencyVerifier != null) { 11348 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11349 } 11350 11351 // Clean up after nested scrolls if this is the end of a gesture; 11352 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 11353 // of the gesture. 11354 if (actionMasked == MotionEvent.ACTION_UP || 11355 actionMasked == MotionEvent.ACTION_CANCEL || 11356 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 11357 stopNestedScroll(); 11358 } 11359 11360 return result; 11361 } 11362 11363 boolean isAccessibilityFocusedViewOrHost() { 11364 return isAccessibilityFocused() || (getViewRootImpl() != null && getViewRootImpl() 11365 .getAccessibilityFocusedHost() == this); 11366 } 11367 11368 /** 11369 * Filter the touch event to apply security policies. 11370 * 11371 * @param event The motion event to be filtered. 11372 * @return True if the event should be dispatched, false if the event should be dropped. 11373 * 11374 * @see #getFilterTouchesWhenObscured 11375 */ 11376 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 11377 //noinspection RedundantIfStatement 11378 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 11379 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 11380 // Window is obscured, drop this touch. 11381 return false; 11382 } 11383 return true; 11384 } 11385 11386 /** 11387 * Pass a trackball motion event down to the focused view. 11388 * 11389 * @param event The motion event to be dispatched. 11390 * @return True if the event was handled by the view, false otherwise. 11391 */ 11392 public boolean dispatchTrackballEvent(MotionEvent event) { 11393 if (mInputEventConsistencyVerifier != null) { 11394 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 11395 } 11396 11397 return onTrackballEvent(event); 11398 } 11399 11400 /** 11401 * Pass a captured pointer event down to the focused view. 11402 * 11403 * @param event The motion event to be dispatched. 11404 * @return True if the event was handled by the view, false otherwise. 11405 */ 11406 public boolean dispatchCapturedPointerEvent(MotionEvent event) { 11407 if (!hasPointerCapture()) { 11408 return false; 11409 } 11410 //noinspection SimplifiableIfStatement 11411 ListenerInfo li = mListenerInfo; 11412 if (li != null && li.mOnCapturedPointerListener != null 11413 && li.mOnCapturedPointerListener.onCapturedPointer(this, event)) { 11414 return true; 11415 } 11416 return onCapturedPointerEvent(event); 11417 } 11418 11419 /** 11420 * Dispatch a generic motion event. 11421 * <p> 11422 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 11423 * are delivered to the view under the pointer. All other generic motion events are 11424 * delivered to the focused view. Hover events are handled specially and are delivered 11425 * to {@link #onHoverEvent(MotionEvent)}. 11426 * </p> 11427 * 11428 * @param event The motion event to be dispatched. 11429 * @return True if the event was handled by the view, false otherwise. 11430 */ 11431 public boolean dispatchGenericMotionEvent(MotionEvent event) { 11432 if (mInputEventConsistencyVerifier != null) { 11433 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 11434 } 11435 11436 final int source = event.getSource(); 11437 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 11438 final int action = event.getAction(); 11439 if (action == MotionEvent.ACTION_HOVER_ENTER 11440 || action == MotionEvent.ACTION_HOVER_MOVE 11441 || action == MotionEvent.ACTION_HOVER_EXIT) { 11442 if (dispatchHoverEvent(event)) { 11443 return true; 11444 } 11445 } else if (dispatchGenericPointerEvent(event)) { 11446 return true; 11447 } 11448 } else if (dispatchGenericFocusedEvent(event)) { 11449 return true; 11450 } 11451 11452 if (dispatchGenericMotionEventInternal(event)) { 11453 return true; 11454 } 11455 11456 if (mInputEventConsistencyVerifier != null) { 11457 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11458 } 11459 return false; 11460 } 11461 11462 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 11463 //noinspection SimplifiableIfStatement 11464 ListenerInfo li = mListenerInfo; 11465 if (li != null && li.mOnGenericMotionListener != null 11466 && (mViewFlags & ENABLED_MASK) == ENABLED 11467 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 11468 return true; 11469 } 11470 11471 if (onGenericMotionEvent(event)) { 11472 return true; 11473 } 11474 11475 final int actionButton = event.getActionButton(); 11476 switch (event.getActionMasked()) { 11477 case MotionEvent.ACTION_BUTTON_PRESS: 11478 if (isContextClickable() && !mInContextButtonPress && !mHasPerformedLongPress 11479 && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 11480 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 11481 if (performContextClick(event.getX(), event.getY())) { 11482 mInContextButtonPress = true; 11483 setPressed(true, event.getX(), event.getY()); 11484 removeTapCallback(); 11485 removeLongPressCallback(); 11486 return true; 11487 } 11488 } 11489 break; 11490 11491 case MotionEvent.ACTION_BUTTON_RELEASE: 11492 if (mInContextButtonPress && (actionButton == MotionEvent.BUTTON_STYLUS_PRIMARY 11493 || actionButton == MotionEvent.BUTTON_SECONDARY)) { 11494 mInContextButtonPress = false; 11495 mIgnoreNextUpEvent = true; 11496 } 11497 break; 11498 } 11499 11500 if (mInputEventConsistencyVerifier != null) { 11501 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 11502 } 11503 return false; 11504 } 11505 11506 /** 11507 * Dispatch a hover event. 11508 * <p> 11509 * Do not call this method directly. 11510 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 11511 * </p> 11512 * 11513 * @param event The motion event to be dispatched. 11514 * @return True if the event was handled by the view, false otherwise. 11515 */ 11516 protected boolean dispatchHoverEvent(MotionEvent event) { 11517 ListenerInfo li = mListenerInfo; 11518 //noinspection SimplifiableIfStatement 11519 if (li != null && li.mOnHoverListener != null 11520 && (mViewFlags & ENABLED_MASK) == ENABLED 11521 && li.mOnHoverListener.onHover(this, event)) { 11522 return true; 11523 } 11524 11525 return onHoverEvent(event); 11526 } 11527 11528 /** 11529 * Returns true if the view has a child to which it has recently sent 11530 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 11531 * it does not have a hovered child, then it must be the innermost hovered view. 11532 * @hide 11533 */ 11534 protected boolean hasHoveredChild() { 11535 return false; 11536 } 11537 11538 /** 11539 * Dispatch a generic motion event to the view under the first pointer. 11540 * <p> 11541 * Do not call this method directly. 11542 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 11543 * </p> 11544 * 11545 * @param event The motion event to be dispatched. 11546 * @return True if the event was handled by the view, false otherwise. 11547 */ 11548 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 11549 return false; 11550 } 11551 11552 /** 11553 * Dispatch a generic motion event to the currently focused view. 11554 * <p> 11555 * Do not call this method directly. 11556 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 11557 * </p> 11558 * 11559 * @param event The motion event to be dispatched. 11560 * @return True if the event was handled by the view, false otherwise. 11561 */ 11562 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 11563 return false; 11564 } 11565 11566 /** 11567 * Dispatch a pointer event. 11568 * <p> 11569 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 11570 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 11571 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 11572 * and should not be expected to handle other pointing device features. 11573 * </p> 11574 * 11575 * @param event The motion event to be dispatched. 11576 * @return True if the event was handled by the view, false otherwise. 11577 * @hide 11578 */ 11579 public final boolean dispatchPointerEvent(MotionEvent event) { 11580 if (event.isTouchEvent()) { 11581 return dispatchTouchEvent(event); 11582 } else { 11583 return dispatchGenericMotionEvent(event); 11584 } 11585 } 11586 11587 /** 11588 * Called when the window containing this view gains or loses window focus. 11589 * ViewGroups should override to route to their children. 11590 * 11591 * @param hasFocus True if the window containing this view now has focus, 11592 * false otherwise. 11593 */ 11594 public void dispatchWindowFocusChanged(boolean hasFocus) { 11595 onWindowFocusChanged(hasFocus); 11596 } 11597 11598 /** 11599 * Called when the window containing this view gains or loses focus. Note 11600 * that this is separate from view focus: to receive key events, both 11601 * your view and its window must have focus. If a window is displayed 11602 * on top of yours that takes input focus, then your own window will lose 11603 * focus but the view focus will remain unchanged. 11604 * 11605 * @param hasWindowFocus True if the window containing this view now has 11606 * focus, false otherwise. 11607 */ 11608 public void onWindowFocusChanged(boolean hasWindowFocus) { 11609 InputMethodManager imm = InputMethodManager.peekInstance(); 11610 if (!hasWindowFocus) { 11611 if (isPressed()) { 11612 setPressed(false); 11613 } 11614 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 11615 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 11616 imm.focusOut(this); 11617 } 11618 removeLongPressCallback(); 11619 removeTapCallback(); 11620 onFocusLost(); 11621 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 11622 imm.focusIn(this); 11623 } 11624 11625 notifyEnterOrExitForAutoFillIfNeeded(hasWindowFocus); 11626 11627 refreshDrawableState(); 11628 } 11629 11630 /** 11631 * Returns true if this view is in a window that currently has window focus. 11632 * Note that this is not the same as the view itself having focus. 11633 * 11634 * @return True if this view is in a window that currently has window focus. 11635 */ 11636 public boolean hasWindowFocus() { 11637 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 11638 } 11639 11640 /** 11641 * Dispatch a view visibility change down the view hierarchy. 11642 * ViewGroups should override to route to their children. 11643 * @param changedView The view whose visibility changed. Could be 'this' or 11644 * an ancestor view. 11645 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 11646 * {@link #INVISIBLE} or {@link #GONE}. 11647 */ 11648 protected void dispatchVisibilityChanged(@NonNull View changedView, 11649 @Visibility int visibility) { 11650 onVisibilityChanged(changedView, visibility); 11651 } 11652 11653 /** 11654 * Called when the visibility of the view or an ancestor of the view has 11655 * changed. 11656 * 11657 * @param changedView The view whose visibility changed. May be 11658 * {@code this} or an ancestor view. 11659 * @param visibility The new visibility, one of {@link #VISIBLE}, 11660 * {@link #INVISIBLE} or {@link #GONE}. 11661 */ 11662 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 11663 } 11664 11665 /** 11666 * Dispatch a hint about whether this view is displayed. For instance, when 11667 * a View moves out of the screen, it might receives a display hint indicating 11668 * the view is not displayed. Applications should not <em>rely</em> on this hint 11669 * as there is no guarantee that they will receive one. 11670 * 11671 * @param hint A hint about whether or not this view is displayed: 11672 * {@link #VISIBLE} or {@link #INVISIBLE}. 11673 */ 11674 public void dispatchDisplayHint(@Visibility int hint) { 11675 onDisplayHint(hint); 11676 } 11677 11678 /** 11679 * Gives this view a hint about whether is displayed or not. For instance, when 11680 * a View moves out of the screen, it might receives a display hint indicating 11681 * the view is not displayed. Applications should not <em>rely</em> on this hint 11682 * as there is no guarantee that they will receive one. 11683 * 11684 * @param hint A hint about whether or not this view is displayed: 11685 * {@link #VISIBLE} or {@link #INVISIBLE}. 11686 */ 11687 protected void onDisplayHint(@Visibility int hint) { 11688 } 11689 11690 /** 11691 * Dispatch a window visibility change down the view hierarchy. 11692 * ViewGroups should override to route to their children. 11693 * 11694 * @param visibility The new visibility of the window. 11695 * 11696 * @see #onWindowVisibilityChanged(int) 11697 */ 11698 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 11699 onWindowVisibilityChanged(visibility); 11700 } 11701 11702 /** 11703 * Called when the window containing has change its visibility 11704 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 11705 * that this tells you whether or not your window is being made visible 11706 * to the window manager; this does <em>not</em> tell you whether or not 11707 * your window is obscured by other windows on the screen, even if it 11708 * is itself visible. 11709 * 11710 * @param visibility The new visibility of the window. 11711 */ 11712 protected void onWindowVisibilityChanged(@Visibility int visibility) { 11713 if (visibility == VISIBLE) { 11714 initialAwakenScrollBars(); 11715 } 11716 } 11717 11718 /** 11719 * Internal dispatching method for {@link #onVisibilityAggregated}. Overridden by 11720 * ViewGroup. Intended to only be called when {@link #isAttachedToWindow()}, 11721 * {@link #getWindowVisibility()} is {@link #VISIBLE} and this view's parent {@link #isShown()}. 11722 * 11723 * @param isVisible true if this view's visibility to the user is uninterrupted by its 11724 * ancestors or by window visibility 11725 * @return true if this view is visible to the user, not counting clipping or overlapping 11726 */ 11727 boolean dispatchVisibilityAggregated(boolean isVisible) { 11728 final boolean thisVisible = getVisibility() == VISIBLE; 11729 // If we're not visible but something is telling us we are, ignore it. 11730 if (thisVisible || !isVisible) { 11731 onVisibilityAggregated(isVisible); 11732 } 11733 return thisVisible && isVisible; 11734 } 11735 11736 /** 11737 * Called when the user-visibility of this View is potentially affected by a change 11738 * to this view itself, an ancestor view or the window this view is attached to. 11739 * 11740 * @param isVisible true if this view and all of its ancestors are {@link #VISIBLE} 11741 * and this view's window is also visible 11742 */ 11743 @CallSuper 11744 public void onVisibilityAggregated(boolean isVisible) { 11745 if (isVisible && mAttachInfo != null) { 11746 initialAwakenScrollBars(); 11747 } 11748 11749 final Drawable dr = mBackground; 11750 if (dr != null && isVisible != dr.isVisible()) { 11751 dr.setVisible(isVisible, false); 11752 } 11753 final Drawable hl = mDefaultFocusHighlight; 11754 if (hl != null && isVisible != hl.isVisible()) { 11755 hl.setVisible(isVisible, false); 11756 } 11757 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 11758 if (fg != null && isVisible != fg.isVisible()) { 11759 fg.setVisible(isVisible, false); 11760 } 11761 } 11762 11763 /** 11764 * Returns the current visibility of the window this view is attached to 11765 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 11766 * 11767 * @return Returns the current visibility of the view's window. 11768 */ 11769 @Visibility 11770 public int getWindowVisibility() { 11771 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 11772 } 11773 11774 /** 11775 * Retrieve the overall visible display size in which the window this view is 11776 * attached to has been positioned in. This takes into account screen 11777 * decorations above the window, for both cases where the window itself 11778 * is being position inside of them or the window is being placed under 11779 * then and covered insets are used for the window to position its content 11780 * inside. In effect, this tells you the available area where content can 11781 * be placed and remain visible to users. 11782 * 11783 * <p>This function requires an IPC back to the window manager to retrieve 11784 * the requested information, so should not be used in performance critical 11785 * code like drawing. 11786 * 11787 * @param outRect Filled in with the visible display frame. If the view 11788 * is not attached to a window, this is simply the raw display size. 11789 */ 11790 public void getWindowVisibleDisplayFrame(Rect outRect) { 11791 if (mAttachInfo != null) { 11792 try { 11793 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 11794 } catch (RemoteException e) { 11795 return; 11796 } 11797 // XXX This is really broken, and probably all needs to be done 11798 // in the window manager, and we need to know more about whether 11799 // we want the area behind or in front of the IME. 11800 final Rect insets = mAttachInfo.mVisibleInsets; 11801 outRect.left += insets.left; 11802 outRect.top += insets.top; 11803 outRect.right -= insets.right; 11804 outRect.bottom -= insets.bottom; 11805 return; 11806 } 11807 // The view is not attached to a display so we don't have a context. 11808 // Make a best guess about the display size. 11809 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 11810 d.getRectSize(outRect); 11811 } 11812 11813 /** 11814 * Like {@link #getWindowVisibleDisplayFrame}, but returns the "full" display frame this window 11815 * is currently in without any insets. 11816 * 11817 * @hide 11818 */ 11819 public void getWindowDisplayFrame(Rect outRect) { 11820 if (mAttachInfo != null) { 11821 try { 11822 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 11823 } catch (RemoteException e) { 11824 return; 11825 } 11826 return; 11827 } 11828 // The view is not attached to a display so we don't have a context. 11829 // Make a best guess about the display size. 11830 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 11831 d.getRectSize(outRect); 11832 } 11833 11834 /** 11835 * Dispatch a notification about a resource configuration change down 11836 * the view hierarchy. 11837 * ViewGroups should override to route to their children. 11838 * 11839 * @param newConfig The new resource configuration. 11840 * 11841 * @see #onConfigurationChanged(android.content.res.Configuration) 11842 */ 11843 public void dispatchConfigurationChanged(Configuration newConfig) { 11844 onConfigurationChanged(newConfig); 11845 } 11846 11847 /** 11848 * Called when the current configuration of the resources being used 11849 * by the application have changed. You can use this to decide when 11850 * to reload resources that can changed based on orientation and other 11851 * configuration characteristics. You only need to use this if you are 11852 * not relying on the normal {@link android.app.Activity} mechanism of 11853 * recreating the activity instance upon a configuration change. 11854 * 11855 * @param newConfig The new resource configuration. 11856 */ 11857 protected void onConfigurationChanged(Configuration newConfig) { 11858 } 11859 11860 /** 11861 * Private function to aggregate all per-view attributes in to the view 11862 * root. 11863 */ 11864 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 11865 performCollectViewAttributes(attachInfo, visibility); 11866 } 11867 11868 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 11869 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 11870 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 11871 attachInfo.mKeepScreenOn = true; 11872 } 11873 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 11874 ListenerInfo li = mListenerInfo; 11875 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 11876 attachInfo.mHasSystemUiListeners = true; 11877 } 11878 } 11879 } 11880 11881 void needGlobalAttributesUpdate(boolean force) { 11882 final AttachInfo ai = mAttachInfo; 11883 if (ai != null && !ai.mRecomputeGlobalAttributes) { 11884 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 11885 || ai.mHasSystemUiListeners) { 11886 ai.mRecomputeGlobalAttributes = true; 11887 } 11888 } 11889 } 11890 11891 /** 11892 * Returns whether the device is currently in touch mode. Touch mode is entered 11893 * once the user begins interacting with the device by touch, and affects various 11894 * things like whether focus is always visible to the user. 11895 * 11896 * @return Whether the device is in touch mode. 11897 */ 11898 @ViewDebug.ExportedProperty 11899 public boolean isInTouchMode() { 11900 if (mAttachInfo != null) { 11901 return mAttachInfo.mInTouchMode; 11902 } else { 11903 return ViewRootImpl.isInTouchMode(); 11904 } 11905 } 11906 11907 /** 11908 * Returns the context the view is running in, through which it can 11909 * access the current theme, resources, etc. 11910 * 11911 * @return The view's Context. 11912 */ 11913 @ViewDebug.CapturedViewProperty 11914 public final Context getContext() { 11915 return mContext; 11916 } 11917 11918 /** 11919 * Handle a key event before it is processed by any input method 11920 * associated with the view hierarchy. This can be used to intercept 11921 * key events in special situations before the IME consumes them; a 11922 * typical example would be handling the BACK key to update the application's 11923 * UI instead of allowing the IME to see it and close itself. 11924 * 11925 * @param keyCode The value in event.getKeyCode(). 11926 * @param event Description of the key event. 11927 * @return If you handled the event, return true. If you want to allow the 11928 * event to be handled by the next receiver, return false. 11929 */ 11930 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 11931 return false; 11932 } 11933 11934 /** 11935 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 11936 * KeyEvent.Callback.onKeyDown()}: perform press of the view 11937 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 11938 * is released, if the view is enabled and clickable. 11939 * <p> 11940 * Key presses in software keyboards will generally NOT trigger this 11941 * listener, although some may elect to do so in some situations. Do not 11942 * rely on this to catch software key presses. 11943 * 11944 * @param keyCode a key code that represents the button pressed, from 11945 * {@link android.view.KeyEvent} 11946 * @param event the KeyEvent object that defines the button action 11947 */ 11948 public boolean onKeyDown(int keyCode, KeyEvent event) { 11949 if (KeyEvent.isConfirmKey(keyCode)) { 11950 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 11951 return true; 11952 } 11953 11954 if (event.getRepeatCount() == 0) { 11955 // Long clickable items don't necessarily have to be clickable. 11956 final boolean clickable = (mViewFlags & CLICKABLE) == CLICKABLE 11957 || (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 11958 if (clickable || (mViewFlags & TOOLTIP) == TOOLTIP) { 11959 // For the purposes of menu anchoring and drawable hotspots, 11960 // key events are considered to be at the center of the view. 11961 final float x = getWidth() / 2f; 11962 final float y = getHeight() / 2f; 11963 if (clickable) { 11964 setPressed(true, x, y); 11965 } 11966 checkForLongClick(0, x, y); 11967 return true; 11968 } 11969 } 11970 } 11971 11972 return false; 11973 } 11974 11975 /** 11976 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 11977 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 11978 * the event). 11979 * <p>Key presses in software keyboards will generally NOT trigger this listener, 11980 * although some may elect to do so in some situations. Do not rely on this to 11981 * catch software key presses. 11982 */ 11983 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 11984 return false; 11985 } 11986 11987 /** 11988 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 11989 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 11990 * when {@link KeyEvent#KEYCODE_DPAD_CENTER}, {@link KeyEvent#KEYCODE_ENTER} 11991 * or {@link KeyEvent#KEYCODE_SPACE} is released. 11992 * <p>Key presses in software keyboards will generally NOT trigger this listener, 11993 * although some may elect to do so in some situations. Do not rely on this to 11994 * catch software key presses. 11995 * 11996 * @param keyCode A key code that represents the button pressed, from 11997 * {@link android.view.KeyEvent}. 11998 * @param event The KeyEvent object that defines the button action. 11999 */ 12000 public boolean onKeyUp(int keyCode, KeyEvent event) { 12001 if (KeyEvent.isConfirmKey(keyCode)) { 12002 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 12003 return true; 12004 } 12005 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 12006 setPressed(false); 12007 12008 if (!mHasPerformedLongPress) { 12009 // This is a tap, so remove the longpress check 12010 removeLongPressCallback(); 12011 if (!event.isCanceled()) { 12012 return performClick(); 12013 } 12014 } 12015 } 12016 } 12017 return false; 12018 } 12019 12020 /** 12021 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 12022 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 12023 * the event). 12024 * <p>Key presses in software keyboards will generally NOT trigger this listener, 12025 * although some may elect to do so in some situations. Do not rely on this to 12026 * catch software key presses. 12027 * 12028 * @param keyCode A key code that represents the button pressed, from 12029 * {@link android.view.KeyEvent}. 12030 * @param repeatCount The number of times the action was made. 12031 * @param event The KeyEvent object that defines the button action. 12032 */ 12033 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 12034 return false; 12035 } 12036 12037 /** 12038 * Called on the focused view when a key shortcut event is not handled. 12039 * Override this method to implement local key shortcuts for the View. 12040 * Key shortcuts can also be implemented by setting the 12041 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 12042 * 12043 * @param keyCode The value in event.getKeyCode(). 12044 * @param event Description of the key event. 12045 * @return If you handled the event, return true. If you want to allow the 12046 * event to be handled by the next receiver, return false. 12047 */ 12048 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 12049 return false; 12050 } 12051 12052 /** 12053 * Check whether the called view is a text editor, in which case it 12054 * would make sense to automatically display a soft input window for 12055 * it. Subclasses should override this if they implement 12056 * {@link #onCreateInputConnection(EditorInfo)} to return true if 12057 * a call on that method would return a non-null InputConnection, and 12058 * they are really a first-class editor that the user would normally 12059 * start typing on when the go into a window containing your view. 12060 * 12061 * <p>The default implementation always returns false. This does 12062 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 12063 * will not be called or the user can not otherwise perform edits on your 12064 * view; it is just a hint to the system that this is not the primary 12065 * purpose of this view. 12066 * 12067 * @return Returns true if this view is a text editor, else false. 12068 */ 12069 public boolean onCheckIsTextEditor() { 12070 return false; 12071 } 12072 12073 /** 12074 * Create a new InputConnection for an InputMethod to interact 12075 * with the view. The default implementation returns null, since it doesn't 12076 * support input methods. You can override this to implement such support. 12077 * This is only needed for views that take focus and text input. 12078 * 12079 * <p>When implementing this, you probably also want to implement 12080 * {@link #onCheckIsTextEditor()} to indicate you will return a 12081 * non-null InputConnection.</p> 12082 * 12083 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 12084 * object correctly and in its entirety, so that the connected IME can rely 12085 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 12086 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 12087 * must be filled in with the correct cursor position for IMEs to work correctly 12088 * with your application.</p> 12089 * 12090 * @param outAttrs Fill in with attribute information about the connection. 12091 */ 12092 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 12093 return null; 12094 } 12095 12096 /** 12097 * Called by the {@link android.view.inputmethod.InputMethodManager} 12098 * when a view who is not the current 12099 * input connection target is trying to make a call on the manager. The 12100 * default implementation returns false; you can override this to return 12101 * true for certain views if you are performing InputConnection proxying 12102 * to them. 12103 * @param view The View that is making the InputMethodManager call. 12104 * @return Return true to allow the call, false to reject. 12105 */ 12106 public boolean checkInputConnectionProxy(View view) { 12107 return false; 12108 } 12109 12110 /** 12111 * Show the context menu for this view. It is not safe to hold on to the 12112 * menu after returning from this method. 12113 * 12114 * You should normally not overload this method. Overload 12115 * {@link #onCreateContextMenu(ContextMenu)} or define an 12116 * {@link OnCreateContextMenuListener} to add items to the context menu. 12117 * 12118 * @param menu The context menu to populate 12119 */ 12120 public void createContextMenu(ContextMenu menu) { 12121 ContextMenuInfo menuInfo = getContextMenuInfo(); 12122 12123 // Sets the current menu info so all items added to menu will have 12124 // my extra info set. 12125 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 12126 12127 onCreateContextMenu(menu); 12128 ListenerInfo li = mListenerInfo; 12129 if (li != null && li.mOnCreateContextMenuListener != null) { 12130 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 12131 } 12132 12133 // Clear the extra information so subsequent items that aren't mine don't 12134 // have my extra info. 12135 ((MenuBuilder)menu).setCurrentMenuInfo(null); 12136 12137 if (mParent != null) { 12138 mParent.createContextMenu(menu); 12139 } 12140 } 12141 12142 /** 12143 * Views should implement this if they have extra information to associate 12144 * with the context menu. The return result is supplied as a parameter to 12145 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 12146 * callback. 12147 * 12148 * @return Extra information about the item for which the context menu 12149 * should be shown. This information will vary across different 12150 * subclasses of View. 12151 */ 12152 protected ContextMenuInfo getContextMenuInfo() { 12153 return null; 12154 } 12155 12156 /** 12157 * Views should implement this if the view itself is going to add items to 12158 * the context menu. 12159 * 12160 * @param menu the context menu to populate 12161 */ 12162 protected void onCreateContextMenu(ContextMenu menu) { 12163 } 12164 12165 /** 12166 * Implement this method to handle trackball motion events. The 12167 * <em>relative</em> movement of the trackball since the last event 12168 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 12169 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 12170 * that a movement of 1 corresponds to the user pressing one DPAD key (so 12171 * they will often be fractional values, representing the more fine-grained 12172 * movement information available from a trackball). 12173 * 12174 * @param event The motion event. 12175 * @return True if the event was handled, false otherwise. 12176 */ 12177 public boolean onTrackballEvent(MotionEvent event) { 12178 return false; 12179 } 12180 12181 /** 12182 * Implement this method to handle generic motion events. 12183 * <p> 12184 * Generic motion events describe joystick movements, mouse hovers, track pad 12185 * touches, scroll wheel movements and other input events. The 12186 * {@link MotionEvent#getSource() source} of the motion event specifies 12187 * the class of input that was received. Implementations of this method 12188 * must examine the bits in the source before processing the event. 12189 * The following code example shows how this is done. 12190 * </p><p> 12191 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 12192 * are delivered to the view under the pointer. All other generic motion events are 12193 * delivered to the focused view. 12194 * </p> 12195 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 12196 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 12197 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 12198 * // process the joystick movement... 12199 * return true; 12200 * } 12201 * } 12202 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 12203 * switch (event.getAction()) { 12204 * case MotionEvent.ACTION_HOVER_MOVE: 12205 * // process the mouse hover movement... 12206 * return true; 12207 * case MotionEvent.ACTION_SCROLL: 12208 * // process the scroll wheel movement... 12209 * return true; 12210 * } 12211 * } 12212 * return super.onGenericMotionEvent(event); 12213 * }</pre> 12214 * 12215 * @param event The generic motion event being processed. 12216 * @return True if the event was handled, false otherwise. 12217 */ 12218 public boolean onGenericMotionEvent(MotionEvent event) { 12219 return false; 12220 } 12221 12222 /** 12223 * Implement this method to handle hover events. 12224 * <p> 12225 * This method is called whenever a pointer is hovering into, over, or out of the 12226 * bounds of a view and the view is not currently being touched. 12227 * Hover events are represented as pointer events with action 12228 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 12229 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 12230 * </p> 12231 * <ul> 12232 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 12233 * when the pointer enters the bounds of the view.</li> 12234 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 12235 * when the pointer has already entered the bounds of the view and has moved.</li> 12236 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 12237 * when the pointer has exited the bounds of the view or when the pointer is 12238 * about to go down due to a button click, tap, or similar user action that 12239 * causes the view to be touched.</li> 12240 * </ul> 12241 * <p> 12242 * The view should implement this method to return true to indicate that it is 12243 * handling the hover event, such as by changing its drawable state. 12244 * </p><p> 12245 * The default implementation calls {@link #setHovered} to update the hovered state 12246 * of the view when a hover enter or hover exit event is received, if the view 12247 * is enabled and is clickable. The default implementation also sends hover 12248 * accessibility events. 12249 * </p> 12250 * 12251 * @param event The motion event that describes the hover. 12252 * @return True if the view handled the hover event. 12253 * 12254 * @see #isHovered 12255 * @see #setHovered 12256 * @see #onHoverChanged 12257 */ 12258 public boolean onHoverEvent(MotionEvent event) { 12259 // The root view may receive hover (or touch) events that are outside the bounds of 12260 // the window. This code ensures that we only send accessibility events for 12261 // hovers that are actually within the bounds of the root view. 12262 final int action = event.getActionMasked(); 12263 if (!mSendingHoverAccessibilityEvents) { 12264 if ((action == MotionEvent.ACTION_HOVER_ENTER 12265 || action == MotionEvent.ACTION_HOVER_MOVE) 12266 && !hasHoveredChild() 12267 && pointInView(event.getX(), event.getY())) { 12268 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 12269 mSendingHoverAccessibilityEvents = true; 12270 } 12271 } else { 12272 if (action == MotionEvent.ACTION_HOVER_EXIT 12273 || (action == MotionEvent.ACTION_MOVE 12274 && !pointInView(event.getX(), event.getY()))) { 12275 mSendingHoverAccessibilityEvents = false; 12276 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 12277 } 12278 } 12279 12280 if ((action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE) 12281 && event.isFromSource(InputDevice.SOURCE_MOUSE) 12282 && isOnScrollbar(event.getX(), event.getY())) { 12283 awakenScrollBars(); 12284 } 12285 12286 // If we consider ourself hoverable, or if we we're already hovered, 12287 // handle changing state in response to ENTER and EXIT events. 12288 if (isHoverable() || isHovered()) { 12289 switch (action) { 12290 case MotionEvent.ACTION_HOVER_ENTER: 12291 setHovered(true); 12292 break; 12293 case MotionEvent.ACTION_HOVER_EXIT: 12294 setHovered(false); 12295 break; 12296 } 12297 12298 // Dispatch the event to onGenericMotionEvent before returning true. 12299 // This is to provide compatibility with existing applications that 12300 // handled HOVER_MOVE events in onGenericMotionEvent and that would 12301 // break because of the new default handling for hoverable views 12302 // in onHoverEvent. 12303 // Note that onGenericMotionEvent will be called by default when 12304 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 12305 dispatchGenericMotionEventInternal(event); 12306 // The event was already handled by calling setHovered(), so always 12307 // return true. 12308 return true; 12309 } 12310 12311 return false; 12312 } 12313 12314 /** 12315 * Returns true if the view should handle {@link #onHoverEvent} 12316 * by calling {@link #setHovered} to change its hovered state. 12317 * 12318 * @return True if the view is hoverable. 12319 */ 12320 private boolean isHoverable() { 12321 final int viewFlags = mViewFlags; 12322 if ((viewFlags & ENABLED_MASK) == DISABLED) { 12323 return false; 12324 } 12325 12326 return (viewFlags & CLICKABLE) == CLICKABLE 12327 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE 12328 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 12329 } 12330 12331 /** 12332 * Returns true if the view is currently hovered. 12333 * 12334 * @return True if the view is currently hovered. 12335 * 12336 * @see #setHovered 12337 * @see #onHoverChanged 12338 */ 12339 @ViewDebug.ExportedProperty 12340 public boolean isHovered() { 12341 return (mPrivateFlags & PFLAG_HOVERED) != 0; 12342 } 12343 12344 /** 12345 * Sets whether the view is currently hovered. 12346 * <p> 12347 * Calling this method also changes the drawable state of the view. This 12348 * enables the view to react to hover by using different drawable resources 12349 * to change its appearance. 12350 * </p><p> 12351 * The {@link #onHoverChanged} method is called when the hovered state changes. 12352 * </p> 12353 * 12354 * @param hovered True if the view is hovered. 12355 * 12356 * @see #isHovered 12357 * @see #onHoverChanged 12358 */ 12359 public void setHovered(boolean hovered) { 12360 if (hovered) { 12361 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 12362 mPrivateFlags |= PFLAG_HOVERED; 12363 refreshDrawableState(); 12364 onHoverChanged(true); 12365 } 12366 } else { 12367 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 12368 mPrivateFlags &= ~PFLAG_HOVERED; 12369 refreshDrawableState(); 12370 onHoverChanged(false); 12371 } 12372 } 12373 } 12374 12375 /** 12376 * Implement this method to handle hover state changes. 12377 * <p> 12378 * This method is called whenever the hover state changes as a result of a 12379 * call to {@link #setHovered}. 12380 * </p> 12381 * 12382 * @param hovered The current hover state, as returned by {@link #isHovered}. 12383 * 12384 * @see #isHovered 12385 * @see #setHovered 12386 */ 12387 public void onHoverChanged(boolean hovered) { 12388 } 12389 12390 /** 12391 * Handles scroll bar dragging by mouse input. 12392 * 12393 * @hide 12394 * @param event The motion event. 12395 * 12396 * @return true if the event was handled as a scroll bar dragging, false otherwise. 12397 */ 12398 protected boolean handleScrollBarDragging(MotionEvent event) { 12399 if (mScrollCache == null) { 12400 return false; 12401 } 12402 final float x = event.getX(); 12403 final float y = event.getY(); 12404 final int action = event.getAction(); 12405 if ((mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING 12406 && action != MotionEvent.ACTION_DOWN) 12407 || !event.isFromSource(InputDevice.SOURCE_MOUSE) 12408 || !event.isButtonPressed(MotionEvent.BUTTON_PRIMARY)) { 12409 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 12410 return false; 12411 } 12412 12413 switch (action) { 12414 case MotionEvent.ACTION_MOVE: 12415 if (mScrollCache.mScrollBarDraggingState == ScrollabilityCache.NOT_DRAGGING) { 12416 return false; 12417 } 12418 if (mScrollCache.mScrollBarDraggingState 12419 == ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR) { 12420 final Rect bounds = mScrollCache.mScrollBarBounds; 12421 getVerticalScrollBarBounds(bounds, null); 12422 final int range = computeVerticalScrollRange(); 12423 final int offset = computeVerticalScrollOffset(); 12424 final int extent = computeVerticalScrollExtent(); 12425 12426 final int thumbLength = ScrollBarUtils.getThumbLength( 12427 bounds.height(), bounds.width(), extent, range); 12428 final int thumbOffset = ScrollBarUtils.getThumbOffset( 12429 bounds.height(), thumbLength, extent, range, offset); 12430 12431 final float diff = y - mScrollCache.mScrollBarDraggingPos; 12432 final float maxThumbOffset = bounds.height() - thumbLength; 12433 final float newThumbOffset = 12434 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 12435 final int height = getHeight(); 12436 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 12437 && height > 0 && extent > 0) { 12438 final int newY = Math.round((range - extent) 12439 / ((float)extent / height) * (newThumbOffset / maxThumbOffset)); 12440 if (newY != getScrollY()) { 12441 mScrollCache.mScrollBarDraggingPos = y; 12442 setScrollY(newY); 12443 } 12444 } 12445 return true; 12446 } 12447 if (mScrollCache.mScrollBarDraggingState 12448 == ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR) { 12449 final Rect bounds = mScrollCache.mScrollBarBounds; 12450 getHorizontalScrollBarBounds(bounds, null); 12451 final int range = computeHorizontalScrollRange(); 12452 final int offset = computeHorizontalScrollOffset(); 12453 final int extent = computeHorizontalScrollExtent(); 12454 12455 final int thumbLength = ScrollBarUtils.getThumbLength( 12456 bounds.width(), bounds.height(), extent, range); 12457 final int thumbOffset = ScrollBarUtils.getThumbOffset( 12458 bounds.width(), thumbLength, extent, range, offset); 12459 12460 final float diff = x - mScrollCache.mScrollBarDraggingPos; 12461 final float maxThumbOffset = bounds.width() - thumbLength; 12462 final float newThumbOffset = 12463 Math.min(Math.max(thumbOffset + diff, 0.0f), maxThumbOffset); 12464 final int width = getWidth(); 12465 if (Math.round(newThumbOffset) != thumbOffset && maxThumbOffset > 0 12466 && width > 0 && extent > 0) { 12467 final int newX = Math.round((range - extent) 12468 / ((float)extent / width) * (newThumbOffset / maxThumbOffset)); 12469 if (newX != getScrollX()) { 12470 mScrollCache.mScrollBarDraggingPos = x; 12471 setScrollX(newX); 12472 } 12473 } 12474 return true; 12475 } 12476 case MotionEvent.ACTION_DOWN: 12477 if (mScrollCache.state == ScrollabilityCache.OFF) { 12478 return false; 12479 } 12480 if (isOnVerticalScrollbarThumb(x, y)) { 12481 mScrollCache.mScrollBarDraggingState = 12482 ScrollabilityCache.DRAGGING_VERTICAL_SCROLL_BAR; 12483 mScrollCache.mScrollBarDraggingPos = y; 12484 return true; 12485 } 12486 if (isOnHorizontalScrollbarThumb(x, y)) { 12487 mScrollCache.mScrollBarDraggingState = 12488 ScrollabilityCache.DRAGGING_HORIZONTAL_SCROLL_BAR; 12489 mScrollCache.mScrollBarDraggingPos = x; 12490 return true; 12491 } 12492 } 12493 mScrollCache.mScrollBarDraggingState = ScrollabilityCache.NOT_DRAGGING; 12494 return false; 12495 } 12496 12497 /** 12498 * Implement this method to handle touch screen motion events. 12499 * <p> 12500 * If this method is used to detect click actions, it is recommended that 12501 * the actions be performed by implementing and calling 12502 * {@link #performClick()}. This will ensure consistent system behavior, 12503 * including: 12504 * <ul> 12505 * <li>obeying click sound preferences 12506 * <li>dispatching OnClickListener calls 12507 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 12508 * accessibility features are enabled 12509 * </ul> 12510 * 12511 * @param event The motion event. 12512 * @return True if the event was handled, false otherwise. 12513 */ 12514 public boolean onTouchEvent(MotionEvent event) { 12515 final float x = event.getX(); 12516 final float y = event.getY(); 12517 final int viewFlags = mViewFlags; 12518 final int action = event.getAction(); 12519 12520 final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE 12521 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 12522 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE; 12523 12524 if ((viewFlags & ENABLED_MASK) == DISABLED) { 12525 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 12526 setPressed(false); 12527 } 12528 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12529 // A disabled view that is clickable still consumes the touch 12530 // events, it just doesn't respond to them. 12531 return clickable; 12532 } 12533 if (mTouchDelegate != null) { 12534 if (mTouchDelegate.onTouchEvent(event)) { 12535 return true; 12536 } 12537 } 12538 12539 if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) { 12540 switch (action) { 12541 case MotionEvent.ACTION_UP: 12542 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12543 if ((viewFlags & TOOLTIP) == TOOLTIP) { 12544 handleTooltipUp(); 12545 } 12546 if (!clickable) { 12547 removeTapCallback(); 12548 removeLongPressCallback(); 12549 mInContextButtonPress = false; 12550 mHasPerformedLongPress = false; 12551 mIgnoreNextUpEvent = false; 12552 break; 12553 } 12554 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 12555 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 12556 // take focus if we don't have it already and we should in 12557 // touch mode. 12558 boolean focusTaken = false; 12559 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 12560 focusTaken = requestFocus(); 12561 } 12562 12563 if (prepressed) { 12564 // The button is being released before we actually 12565 // showed it as pressed. Make it show the pressed 12566 // state now (before scheduling the click) to ensure 12567 // the user sees it. 12568 setPressed(true, x, y); 12569 } 12570 12571 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 12572 // This is a tap, so remove the longpress check 12573 removeLongPressCallback(); 12574 12575 // Only perform take click actions if we were in the pressed state 12576 if (!focusTaken) { 12577 // Use a Runnable and post this rather than calling 12578 // performClick directly. This lets other visual state 12579 // of the view update before click actions start. 12580 if (mPerformClick == null) { 12581 mPerformClick = new PerformClick(); 12582 } 12583 if (!post(mPerformClick)) { 12584 performClick(); 12585 } 12586 } 12587 } 12588 12589 if (mUnsetPressedState == null) { 12590 mUnsetPressedState = new UnsetPressedState(); 12591 } 12592 12593 if (prepressed) { 12594 postDelayed(mUnsetPressedState, 12595 ViewConfiguration.getPressedStateDuration()); 12596 } else if (!post(mUnsetPressedState)) { 12597 // If the post failed, unpress right now 12598 mUnsetPressedState.run(); 12599 } 12600 12601 removeTapCallback(); 12602 } 12603 mIgnoreNextUpEvent = false; 12604 break; 12605 12606 case MotionEvent.ACTION_DOWN: 12607 if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) { 12608 mPrivateFlags3 |= PFLAG3_FINGER_DOWN; 12609 } 12610 mHasPerformedLongPress = false; 12611 12612 if (!clickable) { 12613 checkForLongClick(0, x, y); 12614 break; 12615 } 12616 12617 if (performButtonActionOnTouchDown(event)) { 12618 break; 12619 } 12620 12621 // Walk up the hierarchy to determine if we're inside a scrolling container. 12622 boolean isInScrollingContainer = isInScrollingContainer(); 12623 12624 // For views inside a scrolling container, delay the pressed feedback for 12625 // a short period in case this is a scroll. 12626 if (isInScrollingContainer) { 12627 mPrivateFlags |= PFLAG_PREPRESSED; 12628 if (mPendingCheckForTap == null) { 12629 mPendingCheckForTap = new CheckForTap(); 12630 } 12631 mPendingCheckForTap.x = event.getX(); 12632 mPendingCheckForTap.y = event.getY(); 12633 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 12634 } else { 12635 // Not inside a scrolling container, so show the feedback right away 12636 setPressed(true, x, y); 12637 checkForLongClick(0, x, y); 12638 } 12639 break; 12640 12641 case MotionEvent.ACTION_CANCEL: 12642 if (clickable) { 12643 setPressed(false); 12644 } 12645 removeTapCallback(); 12646 removeLongPressCallback(); 12647 mInContextButtonPress = false; 12648 mHasPerformedLongPress = false; 12649 mIgnoreNextUpEvent = false; 12650 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12651 break; 12652 12653 case MotionEvent.ACTION_MOVE: 12654 if (clickable) { 12655 drawableHotspotChanged(x, y); 12656 } 12657 12658 // Be lenient about moving outside of buttons 12659 if (!pointInView(x, y, mTouchSlop)) { 12660 // Outside button 12661 // Remove any future long press/tap checks 12662 removeTapCallback(); 12663 removeLongPressCallback(); 12664 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 12665 setPressed(false); 12666 } 12667 mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN; 12668 } 12669 break; 12670 } 12671 12672 return true; 12673 } 12674 12675 return false; 12676 } 12677 12678 /** 12679 * @hide 12680 */ 12681 public boolean isInScrollingContainer() { 12682 ViewParent p = getParent(); 12683 while (p != null && p instanceof ViewGroup) { 12684 if (((ViewGroup) p).shouldDelayChildPressedState()) { 12685 return true; 12686 } 12687 p = p.getParent(); 12688 } 12689 return false; 12690 } 12691 12692 /** 12693 * Remove the longpress detection timer. 12694 */ 12695 private void removeLongPressCallback() { 12696 if (mPendingCheckForLongPress != null) { 12697 removeCallbacks(mPendingCheckForLongPress); 12698 } 12699 } 12700 12701 /** 12702 * Remove the pending click action 12703 */ 12704 private void removePerformClickCallback() { 12705 if (mPerformClick != null) { 12706 removeCallbacks(mPerformClick); 12707 } 12708 } 12709 12710 /** 12711 * Remove the prepress detection timer. 12712 */ 12713 private void removeUnsetPressCallback() { 12714 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 12715 setPressed(false); 12716 removeCallbacks(mUnsetPressedState); 12717 } 12718 } 12719 12720 /** 12721 * Remove the tap detection timer. 12722 */ 12723 private void removeTapCallback() { 12724 if (mPendingCheckForTap != null) { 12725 mPrivateFlags &= ~PFLAG_PREPRESSED; 12726 removeCallbacks(mPendingCheckForTap); 12727 } 12728 } 12729 12730 /** 12731 * Cancels a pending long press. Your subclass can use this if you 12732 * want the context menu to come up if the user presses and holds 12733 * at the same place, but you don't want it to come up if they press 12734 * and then move around enough to cause scrolling. 12735 */ 12736 public void cancelLongPress() { 12737 removeLongPressCallback(); 12738 12739 /* 12740 * The prepressed state handled by the tap callback is a display 12741 * construct, but the tap callback will post a long press callback 12742 * less its own timeout. Remove it here. 12743 */ 12744 removeTapCallback(); 12745 } 12746 12747 /** 12748 * Remove the pending callback for sending a 12749 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 12750 */ 12751 private void removeSendViewScrolledAccessibilityEventCallback() { 12752 if (mSendViewScrolledAccessibilityEvent != null) { 12753 removeCallbacks(mSendViewScrolledAccessibilityEvent); 12754 mSendViewScrolledAccessibilityEvent.mIsPending = false; 12755 } 12756 } 12757 12758 /** 12759 * Sets the TouchDelegate for this View. 12760 */ 12761 public void setTouchDelegate(TouchDelegate delegate) { 12762 mTouchDelegate = delegate; 12763 } 12764 12765 /** 12766 * Gets the TouchDelegate for this View. 12767 */ 12768 public TouchDelegate getTouchDelegate() { 12769 return mTouchDelegate; 12770 } 12771 12772 /** 12773 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 12774 * 12775 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 12776 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 12777 * available. This method should only be called for touch events. 12778 * 12779 * <p class="note">This api is not intended for most applications. Buffered dispatch 12780 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 12781 * streams will not improve your input latency. Side effects include: increased latency, 12782 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 12783 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 12784 * you.</p> 12785 */ 12786 public final void requestUnbufferedDispatch(MotionEvent event) { 12787 final int action = event.getAction(); 12788 if (mAttachInfo == null 12789 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 12790 || !event.isTouchEvent()) { 12791 return; 12792 } 12793 mAttachInfo.mUnbufferedDispatchRequested = true; 12794 } 12795 12796 /** 12797 * Set flags controlling behavior of this view. 12798 * 12799 * @param flags Constant indicating the value which should be set 12800 * @param mask Constant indicating the bit range that should be changed 12801 */ 12802 void setFlags(int flags, int mask) { 12803 final boolean accessibilityEnabled = 12804 AccessibilityManager.getInstance(mContext).isEnabled(); 12805 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 12806 12807 int old = mViewFlags; 12808 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 12809 12810 int changed = mViewFlags ^ old; 12811 if (changed == 0) { 12812 return; 12813 } 12814 int privateFlags = mPrivateFlags; 12815 12816 // If focusable is auto, update the FOCUSABLE bit. 12817 int focusableChangedByAuto = 0; 12818 if (((mViewFlags & FOCUSABLE_AUTO) != 0) 12819 && (changed & (FOCUSABLE_MASK | CLICKABLE)) != 0) { 12820 // Heuristic only takes into account whether view is clickable. 12821 final int newFocus; 12822 if ((mViewFlags & CLICKABLE) != 0) { 12823 newFocus = FOCUSABLE; 12824 } else { 12825 newFocus = NOT_FOCUSABLE; 12826 } 12827 mViewFlags = (mViewFlags & ~FOCUSABLE) | newFocus; 12828 focusableChangedByAuto = (old & FOCUSABLE) ^ (newFocus & FOCUSABLE); 12829 changed = (changed & ~FOCUSABLE) | focusableChangedByAuto; 12830 } 12831 12832 /* Check if the FOCUSABLE bit has changed */ 12833 if (((changed & FOCUSABLE) != 0) && ((privateFlags & PFLAG_HAS_BOUNDS) != 0)) { 12834 if (((old & FOCUSABLE) == FOCUSABLE) 12835 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 12836 /* Give up focus if we are no longer focusable */ 12837 clearFocus(); 12838 } else if (((old & FOCUSABLE) == NOT_FOCUSABLE) 12839 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 12840 /* 12841 * Tell the view system that we are now available to take focus 12842 * if no one else already has it. 12843 */ 12844 if (mParent != null) { 12845 ViewRootImpl viewRootImpl = getViewRootImpl(); 12846 if (!sAutoFocusableOffUIThreadWontNotifyParents 12847 || focusableChangedByAuto == 0 12848 || viewRootImpl == null 12849 || viewRootImpl.mThread == Thread.currentThread()) { 12850 mParent.focusableViewAvailable(this); 12851 } 12852 } 12853 } 12854 } 12855 12856 final int newVisibility = flags & VISIBILITY_MASK; 12857 if (newVisibility == VISIBLE) { 12858 if ((changed & VISIBILITY_MASK) != 0) { 12859 /* 12860 * If this view is becoming visible, invalidate it in case it changed while 12861 * it was not visible. Marking it drawn ensures that the invalidation will 12862 * go through. 12863 */ 12864 mPrivateFlags |= PFLAG_DRAWN; 12865 invalidate(true); 12866 12867 needGlobalAttributesUpdate(true); 12868 12869 // a view becoming visible is worth notifying the parent 12870 // about in case nothing has focus. even if this specific view 12871 // isn't focusable, it may contain something that is, so let 12872 // the root view try to give this focus if nothing else does. 12873 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 12874 mParent.focusableViewAvailable(this); 12875 } 12876 } 12877 } 12878 12879 /* Check if the GONE bit has changed */ 12880 if ((changed & GONE) != 0) { 12881 needGlobalAttributesUpdate(false); 12882 requestLayout(); 12883 12884 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 12885 if (hasFocus()) clearFocus(); 12886 clearAccessibilityFocus(); 12887 destroyDrawingCache(); 12888 if (mParent instanceof View) { 12889 // GONE views noop invalidation, so invalidate the parent 12890 ((View) mParent).invalidate(true); 12891 } 12892 // Mark the view drawn to ensure that it gets invalidated properly the next 12893 // time it is visible and gets invalidated 12894 mPrivateFlags |= PFLAG_DRAWN; 12895 } 12896 if (mAttachInfo != null) { 12897 mAttachInfo.mViewVisibilityChanged = true; 12898 } 12899 } 12900 12901 /* Check if the VISIBLE bit has changed */ 12902 if ((changed & INVISIBLE) != 0) { 12903 needGlobalAttributesUpdate(false); 12904 /* 12905 * If this view is becoming invisible, set the DRAWN flag so that 12906 * the next invalidate() will not be skipped. 12907 */ 12908 mPrivateFlags |= PFLAG_DRAWN; 12909 12910 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 12911 // root view becoming invisible shouldn't clear focus and accessibility focus 12912 if (getRootView() != this) { 12913 if (hasFocus()) clearFocus(); 12914 clearAccessibilityFocus(); 12915 } 12916 } 12917 if (mAttachInfo != null) { 12918 mAttachInfo.mViewVisibilityChanged = true; 12919 } 12920 } 12921 12922 if ((changed & VISIBILITY_MASK) != 0) { 12923 // If the view is invisible, cleanup its display list to free up resources 12924 if (newVisibility != VISIBLE && mAttachInfo != null) { 12925 cleanupDraw(); 12926 } 12927 12928 if (mParent instanceof ViewGroup) { 12929 ((ViewGroup) mParent).onChildVisibilityChanged(this, 12930 (changed & VISIBILITY_MASK), newVisibility); 12931 ((View) mParent).invalidate(true); 12932 } else if (mParent != null) { 12933 mParent.invalidateChild(this, null); 12934 } 12935 12936 if (mAttachInfo != null) { 12937 dispatchVisibilityChanged(this, newVisibility); 12938 12939 // Aggregated visibility changes are dispatched to attached views 12940 // in visible windows where the parent is currently shown/drawn 12941 // or the parent is not a ViewGroup (and therefore assumed to be a ViewRoot), 12942 // discounting clipping or overlapping. This makes it a good place 12943 // to change animation states. 12944 if (mParent != null && getWindowVisibility() == VISIBLE && 12945 ((!(mParent instanceof ViewGroup)) || ((ViewGroup) mParent).isShown())) { 12946 dispatchVisibilityAggregated(newVisibility == VISIBLE); 12947 } 12948 notifySubtreeAccessibilityStateChangedIfNeeded(); 12949 } 12950 } 12951 12952 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 12953 destroyDrawingCache(); 12954 } 12955 12956 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 12957 destroyDrawingCache(); 12958 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12959 invalidateParentCaches(); 12960 } 12961 12962 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 12963 destroyDrawingCache(); 12964 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 12965 } 12966 12967 if ((changed & DRAW_MASK) != 0) { 12968 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 12969 if (mBackground != null 12970 || mDefaultFocusHighlight != null 12971 || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { 12972 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 12973 } else { 12974 mPrivateFlags |= PFLAG_SKIP_DRAW; 12975 } 12976 } else { 12977 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 12978 } 12979 requestLayout(); 12980 invalidate(true); 12981 } 12982 12983 if ((changed & KEEP_SCREEN_ON) != 0) { 12984 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 12985 mParent.recomputeViewAttributes(this); 12986 } 12987 } 12988 12989 if (accessibilityEnabled) { 12990 if ((changed & FOCUSABLE) != 0 || (changed & VISIBILITY_MASK) != 0 12991 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0 12992 || (changed & CONTEXT_CLICKABLE) != 0) { 12993 if (oldIncludeForAccessibility != includeForAccessibility()) { 12994 notifySubtreeAccessibilityStateChangedIfNeeded(); 12995 } else { 12996 notifyViewAccessibilityStateChangedIfNeeded( 12997 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 12998 } 12999 } else if ((changed & ENABLED_MASK) != 0) { 13000 notifyViewAccessibilityStateChangedIfNeeded( 13001 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 13002 } 13003 } 13004 } 13005 13006 /** 13007 * Change the view's z order in the tree, so it's on top of other sibling 13008 * views. This ordering change may affect layout, if the parent container 13009 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 13010 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 13011 * method should be followed by calls to {@link #requestLayout()} and 13012 * {@link View#invalidate()} on the view's parent to force the parent to redraw 13013 * with the new child ordering. 13014 * 13015 * @see ViewGroup#bringChildToFront(View) 13016 */ 13017 public void bringToFront() { 13018 if (mParent != null) { 13019 mParent.bringChildToFront(this); 13020 } 13021 } 13022 13023 /** 13024 * This is called in response to an internal scroll in this view (i.e., the 13025 * view scrolled its own contents). This is typically as a result of 13026 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 13027 * called. 13028 * 13029 * @param l Current horizontal scroll origin. 13030 * @param t Current vertical scroll origin. 13031 * @param oldl Previous horizontal scroll origin. 13032 * @param oldt Previous vertical scroll origin. 13033 */ 13034 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 13035 notifySubtreeAccessibilityStateChangedIfNeeded(); 13036 13037 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 13038 postSendViewScrolledAccessibilityEventCallback(); 13039 } 13040 13041 mBackgroundSizeChanged = true; 13042 mDefaultFocusHighlightSizeChanged = true; 13043 if (mForegroundInfo != null) { 13044 mForegroundInfo.mBoundsChanged = true; 13045 } 13046 13047 final AttachInfo ai = mAttachInfo; 13048 if (ai != null) { 13049 ai.mViewScrollChanged = true; 13050 } 13051 13052 if (mListenerInfo != null && mListenerInfo.mOnScrollChangeListener != null) { 13053 mListenerInfo.mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt); 13054 } 13055 } 13056 13057 /** 13058 * Interface definition for a callback to be invoked when the scroll 13059 * X or Y positions of a view change. 13060 * <p> 13061 * <b>Note:</b> Some views handle scrolling independently from View and may 13062 * have their own separate listeners for scroll-type events. For example, 13063 * {@link android.widget.ListView ListView} allows clients to register an 13064 * {@link android.widget.ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener) AbsListView.OnScrollListener} 13065 * to listen for changes in list scroll position. 13066 * 13067 * @see #setOnScrollChangeListener(View.OnScrollChangeListener) 13068 */ 13069 public interface OnScrollChangeListener { 13070 /** 13071 * Called when the scroll position of a view changes. 13072 * 13073 * @param v The view whose scroll position has changed. 13074 * @param scrollX Current horizontal scroll origin. 13075 * @param scrollY Current vertical scroll origin. 13076 * @param oldScrollX Previous horizontal scroll origin. 13077 * @param oldScrollY Previous vertical scroll origin. 13078 */ 13079 void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY); 13080 } 13081 13082 /** 13083 * Interface definition for a callback to be invoked when the layout bounds of a view 13084 * changes due to layout processing. 13085 */ 13086 public interface OnLayoutChangeListener { 13087 /** 13088 * Called when the layout bounds of a view changes due to layout processing. 13089 * 13090 * @param v The view whose bounds have changed. 13091 * @param left The new value of the view's left property. 13092 * @param top The new value of the view's top property. 13093 * @param right The new value of the view's right property. 13094 * @param bottom The new value of the view's bottom property. 13095 * @param oldLeft The previous value of the view's left property. 13096 * @param oldTop The previous value of the view's top property. 13097 * @param oldRight The previous value of the view's right property. 13098 * @param oldBottom The previous value of the view's bottom property. 13099 */ 13100 void onLayoutChange(View v, int left, int top, int right, int bottom, 13101 int oldLeft, int oldTop, int oldRight, int oldBottom); 13102 } 13103 13104 /** 13105 * This is called during layout when the size of this view has changed. If 13106 * you were just added to the view hierarchy, you're called with the old 13107 * values of 0. 13108 * 13109 * @param w Current width of this view. 13110 * @param h Current height of this view. 13111 * @param oldw Old width of this view. 13112 * @param oldh Old height of this view. 13113 */ 13114 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 13115 } 13116 13117 /** 13118 * Called by draw to draw the child views. This may be overridden 13119 * by derived classes to gain control just before its children are drawn 13120 * (but after its own view has been drawn). 13121 * @param canvas the canvas on which to draw the view 13122 */ 13123 protected void dispatchDraw(Canvas canvas) { 13124 13125 } 13126 13127 /** 13128 * Gets the parent of this view. Note that the parent is a 13129 * ViewParent and not necessarily a View. 13130 * 13131 * @return Parent of this view. 13132 */ 13133 public final ViewParent getParent() { 13134 return mParent; 13135 } 13136 13137 /** 13138 * Set the horizontal scrolled position of your view. This will cause a call to 13139 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13140 * invalidated. 13141 * @param value the x position to scroll to 13142 */ 13143 public void setScrollX(int value) { 13144 scrollTo(value, mScrollY); 13145 } 13146 13147 /** 13148 * Set the vertical scrolled position of your view. This will cause a call to 13149 * {@link #onScrollChanged(int, int, int, int)} and the view will be 13150 * invalidated. 13151 * @param value the y position to scroll to 13152 */ 13153 public void setScrollY(int value) { 13154 scrollTo(mScrollX, value); 13155 } 13156 13157 /** 13158 * Return the scrolled left position of this view. This is the left edge of 13159 * the displayed part of your view. You do not need to draw any pixels 13160 * farther left, since those are outside of the frame of your view on 13161 * screen. 13162 * 13163 * @return The left edge of the displayed part of your view, in pixels. 13164 */ 13165 public final int getScrollX() { 13166 return mScrollX; 13167 } 13168 13169 /** 13170 * Return the scrolled top position of this view. This is the top edge of 13171 * the displayed part of your view. You do not need to draw any pixels above 13172 * it, since those are outside of the frame of your view on screen. 13173 * 13174 * @return The top edge of the displayed part of your view, in pixels. 13175 */ 13176 public final int getScrollY() { 13177 return mScrollY; 13178 } 13179 13180 /** 13181 * Return the width of the your view. 13182 * 13183 * @return The width of your view, in pixels. 13184 */ 13185 @ViewDebug.ExportedProperty(category = "layout") 13186 public final int getWidth() { 13187 return mRight - mLeft; 13188 } 13189 13190 /** 13191 * Return the height of your view. 13192 * 13193 * @return The height of your view, in pixels. 13194 */ 13195 @ViewDebug.ExportedProperty(category = "layout") 13196 public final int getHeight() { 13197 return mBottom - mTop; 13198 } 13199 13200 /** 13201 * Return the visible drawing bounds of your view. Fills in the output 13202 * rectangle with the values from getScrollX(), getScrollY(), 13203 * getWidth(), and getHeight(). These bounds do not account for any 13204 * transformation properties currently set on the view, such as 13205 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 13206 * 13207 * @param outRect The (scrolled) drawing bounds of the view. 13208 */ 13209 public void getDrawingRect(Rect outRect) { 13210 outRect.left = mScrollX; 13211 outRect.top = mScrollY; 13212 outRect.right = mScrollX + (mRight - mLeft); 13213 outRect.bottom = mScrollY + (mBottom - mTop); 13214 } 13215 13216 /** 13217 * Like {@link #getMeasuredWidthAndState()}, but only returns the 13218 * raw width component (that is the result is masked by 13219 * {@link #MEASURED_SIZE_MASK}). 13220 * 13221 * @return The raw measured width of this view. 13222 */ 13223 public final int getMeasuredWidth() { 13224 return mMeasuredWidth & MEASURED_SIZE_MASK; 13225 } 13226 13227 /** 13228 * Return the full width measurement information for this view as computed 13229 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 13230 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13231 * This should be used during measurement and layout calculations only. Use 13232 * {@link #getWidth()} to see how wide a view is after layout. 13233 * 13234 * @return The measured width of this view as a bit mask. 13235 */ 13236 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 13237 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 13238 name = "MEASURED_STATE_TOO_SMALL"), 13239 }) 13240 public final int getMeasuredWidthAndState() { 13241 return mMeasuredWidth; 13242 } 13243 13244 /** 13245 * Like {@link #getMeasuredHeightAndState()}, but only returns the 13246 * raw height component (that is the result is masked by 13247 * {@link #MEASURED_SIZE_MASK}). 13248 * 13249 * @return The raw measured height of this view. 13250 */ 13251 public final int getMeasuredHeight() { 13252 return mMeasuredHeight & MEASURED_SIZE_MASK; 13253 } 13254 13255 /** 13256 * Return the full height measurement information for this view as computed 13257 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 13258 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 13259 * This should be used during measurement and layout calculations only. Use 13260 * {@link #getHeight()} to see how wide a view is after layout. 13261 * 13262 * @return The measured height of this view as a bit mask. 13263 */ 13264 @ViewDebug.ExportedProperty(category = "measurement", flagMapping = { 13265 @ViewDebug.FlagToString(mask = MEASURED_STATE_MASK, equals = MEASURED_STATE_TOO_SMALL, 13266 name = "MEASURED_STATE_TOO_SMALL"), 13267 }) 13268 public final int getMeasuredHeightAndState() { 13269 return mMeasuredHeight; 13270 } 13271 13272 /** 13273 * Return only the state bits of {@link #getMeasuredWidthAndState()} 13274 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 13275 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 13276 * and the height component is at the shifted bits 13277 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 13278 */ 13279 public final int getMeasuredState() { 13280 return (mMeasuredWidth&MEASURED_STATE_MASK) 13281 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 13282 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 13283 } 13284 13285 /** 13286 * The transform matrix of this view, which is calculated based on the current 13287 * rotation, scale, and pivot properties. 13288 * 13289 * @see #getRotation() 13290 * @see #getScaleX() 13291 * @see #getScaleY() 13292 * @see #getPivotX() 13293 * @see #getPivotY() 13294 * @return The current transform matrix for the view 13295 */ 13296 public Matrix getMatrix() { 13297 ensureTransformationInfo(); 13298 final Matrix matrix = mTransformationInfo.mMatrix; 13299 mRenderNode.getMatrix(matrix); 13300 return matrix; 13301 } 13302 13303 /** 13304 * Returns true if the transform matrix is the identity matrix. 13305 * Recomputes the matrix if necessary. 13306 * 13307 * @return True if the transform matrix is the identity matrix, false otherwise. 13308 */ 13309 final boolean hasIdentityMatrix() { 13310 return mRenderNode.hasIdentityMatrix(); 13311 } 13312 13313 void ensureTransformationInfo() { 13314 if (mTransformationInfo == null) { 13315 mTransformationInfo = new TransformationInfo(); 13316 } 13317 } 13318 13319 /** 13320 * Utility method to retrieve the inverse of the current mMatrix property. 13321 * We cache the matrix to avoid recalculating it when transform properties 13322 * have not changed. 13323 * 13324 * @return The inverse of the current matrix of this view. 13325 * @hide 13326 */ 13327 public final Matrix getInverseMatrix() { 13328 ensureTransformationInfo(); 13329 if (mTransformationInfo.mInverseMatrix == null) { 13330 mTransformationInfo.mInverseMatrix = new Matrix(); 13331 } 13332 final Matrix matrix = mTransformationInfo.mInverseMatrix; 13333 mRenderNode.getInverseMatrix(matrix); 13334 return matrix; 13335 } 13336 13337 /** 13338 * Gets the distance along the Z axis from the camera to this view. 13339 * 13340 * @see #setCameraDistance(float) 13341 * 13342 * @return The distance along the Z axis. 13343 */ 13344 public float getCameraDistance() { 13345 final float dpi = mResources.getDisplayMetrics().densityDpi; 13346 return -(mRenderNode.getCameraDistance() * dpi); 13347 } 13348 13349 /** 13350 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 13351 * views are drawn) from the camera to this view. The camera's distance 13352 * affects 3D transformations, for instance rotations around the X and Y 13353 * axis. If the rotationX or rotationY properties are changed and this view is 13354 * large (more than half the size of the screen), it is recommended to always 13355 * use a camera distance that's greater than the height (X axis rotation) or 13356 * the width (Y axis rotation) of this view.</p> 13357 * 13358 * <p>The distance of the camera from the view plane can have an affect on the 13359 * perspective distortion of the view when it is rotated around the x or y axis. 13360 * For example, a large distance will result in a large viewing angle, and there 13361 * will not be much perspective distortion of the view as it rotates. A short 13362 * distance may cause much more perspective distortion upon rotation, and can 13363 * also result in some drawing artifacts if the rotated view ends up partially 13364 * behind the camera (which is why the recommendation is to use a distance at 13365 * least as far as the size of the view, if the view is to be rotated.)</p> 13366 * 13367 * <p>The distance is expressed in "depth pixels." The default distance depends 13368 * on the screen density. For instance, on a medium density display, the 13369 * default distance is 1280. On a high density display, the default distance 13370 * is 1920.</p> 13371 * 13372 * <p>If you want to specify a distance that leads to visually consistent 13373 * results across various densities, use the following formula:</p> 13374 * <pre> 13375 * float scale = context.getResources().getDisplayMetrics().density; 13376 * view.setCameraDistance(distance * scale); 13377 * </pre> 13378 * 13379 * <p>The density scale factor of a high density display is 1.5, 13380 * and 1920 = 1280 * 1.5.</p> 13381 * 13382 * @param distance The distance in "depth pixels", if negative the opposite 13383 * value is used 13384 * 13385 * @see #setRotationX(float) 13386 * @see #setRotationY(float) 13387 */ 13388 public void setCameraDistance(float distance) { 13389 final float dpi = mResources.getDisplayMetrics().densityDpi; 13390 13391 invalidateViewProperty(true, false); 13392 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 13393 invalidateViewProperty(false, false); 13394 13395 invalidateParentIfNeededAndWasQuickRejected(); 13396 } 13397 13398 /** 13399 * The degrees that the view is rotated around the pivot point. 13400 * 13401 * @see #setRotation(float) 13402 * @see #getPivotX() 13403 * @see #getPivotY() 13404 * 13405 * @return The degrees of rotation. 13406 */ 13407 @ViewDebug.ExportedProperty(category = "drawing") 13408 public float getRotation() { 13409 return mRenderNode.getRotation(); 13410 } 13411 13412 /** 13413 * Sets the degrees that the view is rotated around the pivot point. Increasing values 13414 * result in clockwise rotation. 13415 * 13416 * @param rotation The degrees of rotation. 13417 * 13418 * @see #getRotation() 13419 * @see #getPivotX() 13420 * @see #getPivotY() 13421 * @see #setRotationX(float) 13422 * @see #setRotationY(float) 13423 * 13424 * @attr ref android.R.styleable#View_rotation 13425 */ 13426 public void setRotation(float rotation) { 13427 if (rotation != getRotation()) { 13428 // Double-invalidation is necessary to capture view's old and new areas 13429 invalidateViewProperty(true, false); 13430 mRenderNode.setRotation(rotation); 13431 invalidateViewProperty(false, true); 13432 13433 invalidateParentIfNeededAndWasQuickRejected(); 13434 notifySubtreeAccessibilityStateChangedIfNeeded(); 13435 } 13436 } 13437 13438 /** 13439 * The degrees that the view is rotated around the vertical axis through the pivot point. 13440 * 13441 * @see #getPivotX() 13442 * @see #getPivotY() 13443 * @see #setRotationY(float) 13444 * 13445 * @return The degrees of Y rotation. 13446 */ 13447 @ViewDebug.ExportedProperty(category = "drawing") 13448 public float getRotationY() { 13449 return mRenderNode.getRotationY(); 13450 } 13451 13452 /** 13453 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 13454 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 13455 * down the y axis. 13456 * 13457 * When rotating large views, it is recommended to adjust the camera distance 13458 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 13459 * 13460 * @param rotationY The degrees of Y rotation. 13461 * 13462 * @see #getRotationY() 13463 * @see #getPivotX() 13464 * @see #getPivotY() 13465 * @see #setRotation(float) 13466 * @see #setRotationX(float) 13467 * @see #setCameraDistance(float) 13468 * 13469 * @attr ref android.R.styleable#View_rotationY 13470 */ 13471 public void setRotationY(float rotationY) { 13472 if (rotationY != getRotationY()) { 13473 invalidateViewProperty(true, false); 13474 mRenderNode.setRotationY(rotationY); 13475 invalidateViewProperty(false, true); 13476 13477 invalidateParentIfNeededAndWasQuickRejected(); 13478 notifySubtreeAccessibilityStateChangedIfNeeded(); 13479 } 13480 } 13481 13482 /** 13483 * The degrees that the view is rotated around the horizontal axis through the pivot point. 13484 * 13485 * @see #getPivotX() 13486 * @see #getPivotY() 13487 * @see #setRotationX(float) 13488 * 13489 * @return The degrees of X rotation. 13490 */ 13491 @ViewDebug.ExportedProperty(category = "drawing") 13492 public float getRotationX() { 13493 return mRenderNode.getRotationX(); 13494 } 13495 13496 /** 13497 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 13498 * Increasing values result in clockwise rotation from the viewpoint of looking down the 13499 * x axis. 13500 * 13501 * When rotating large views, it is recommended to adjust the camera distance 13502 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 13503 * 13504 * @param rotationX The degrees of X rotation. 13505 * 13506 * @see #getRotationX() 13507 * @see #getPivotX() 13508 * @see #getPivotY() 13509 * @see #setRotation(float) 13510 * @see #setRotationY(float) 13511 * @see #setCameraDistance(float) 13512 * 13513 * @attr ref android.R.styleable#View_rotationX 13514 */ 13515 public void setRotationX(float rotationX) { 13516 if (rotationX != getRotationX()) { 13517 invalidateViewProperty(true, false); 13518 mRenderNode.setRotationX(rotationX); 13519 invalidateViewProperty(false, true); 13520 13521 invalidateParentIfNeededAndWasQuickRejected(); 13522 notifySubtreeAccessibilityStateChangedIfNeeded(); 13523 } 13524 } 13525 13526 /** 13527 * The amount that the view is scaled in x around the pivot point, as a proportion of 13528 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 13529 * 13530 * <p>By default, this is 1.0f. 13531 * 13532 * @see #getPivotX() 13533 * @see #getPivotY() 13534 * @return The scaling factor. 13535 */ 13536 @ViewDebug.ExportedProperty(category = "drawing") 13537 public float getScaleX() { 13538 return mRenderNode.getScaleX(); 13539 } 13540 13541 /** 13542 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 13543 * the view's unscaled width. A value of 1 means that no scaling is applied. 13544 * 13545 * @param scaleX The scaling factor. 13546 * @see #getPivotX() 13547 * @see #getPivotY() 13548 * 13549 * @attr ref android.R.styleable#View_scaleX 13550 */ 13551 public void setScaleX(float scaleX) { 13552 if (scaleX != getScaleX()) { 13553 invalidateViewProperty(true, false); 13554 mRenderNode.setScaleX(scaleX); 13555 invalidateViewProperty(false, true); 13556 13557 invalidateParentIfNeededAndWasQuickRejected(); 13558 notifySubtreeAccessibilityStateChangedIfNeeded(); 13559 } 13560 } 13561 13562 /** 13563 * The amount that the view is scaled in y around the pivot point, as a proportion of 13564 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 13565 * 13566 * <p>By default, this is 1.0f. 13567 * 13568 * @see #getPivotX() 13569 * @see #getPivotY() 13570 * @return The scaling factor. 13571 */ 13572 @ViewDebug.ExportedProperty(category = "drawing") 13573 public float getScaleY() { 13574 return mRenderNode.getScaleY(); 13575 } 13576 13577 /** 13578 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 13579 * the view's unscaled width. A value of 1 means that no scaling is applied. 13580 * 13581 * @param scaleY The scaling factor. 13582 * @see #getPivotX() 13583 * @see #getPivotY() 13584 * 13585 * @attr ref android.R.styleable#View_scaleY 13586 */ 13587 public void setScaleY(float scaleY) { 13588 if (scaleY != getScaleY()) { 13589 invalidateViewProperty(true, false); 13590 mRenderNode.setScaleY(scaleY); 13591 invalidateViewProperty(false, true); 13592 13593 invalidateParentIfNeededAndWasQuickRejected(); 13594 notifySubtreeAccessibilityStateChangedIfNeeded(); 13595 } 13596 } 13597 13598 /** 13599 * The x location of the point around which the view is {@link #setRotation(float) rotated} 13600 * and {@link #setScaleX(float) scaled}. 13601 * 13602 * @see #getRotation() 13603 * @see #getScaleX() 13604 * @see #getScaleY() 13605 * @see #getPivotY() 13606 * @return The x location of the pivot point. 13607 * 13608 * @attr ref android.R.styleable#View_transformPivotX 13609 */ 13610 @ViewDebug.ExportedProperty(category = "drawing") 13611 public float getPivotX() { 13612 return mRenderNode.getPivotX(); 13613 } 13614 13615 /** 13616 * Sets the x location of the point around which the view is 13617 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 13618 * By default, the pivot point is centered on the object. 13619 * Setting this property disables this behavior and causes the view to use only the 13620 * explicitly set pivotX and pivotY values. 13621 * 13622 * @param pivotX The x location of the pivot point. 13623 * @see #getRotation() 13624 * @see #getScaleX() 13625 * @see #getScaleY() 13626 * @see #getPivotY() 13627 * 13628 * @attr ref android.R.styleable#View_transformPivotX 13629 */ 13630 public void setPivotX(float pivotX) { 13631 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 13632 invalidateViewProperty(true, false); 13633 mRenderNode.setPivotX(pivotX); 13634 invalidateViewProperty(false, true); 13635 13636 invalidateParentIfNeededAndWasQuickRejected(); 13637 } 13638 } 13639 13640 /** 13641 * The y location of the point around which the view is {@link #setRotation(float) rotated} 13642 * and {@link #setScaleY(float) scaled}. 13643 * 13644 * @see #getRotation() 13645 * @see #getScaleX() 13646 * @see #getScaleY() 13647 * @see #getPivotY() 13648 * @return The y location of the pivot point. 13649 * 13650 * @attr ref android.R.styleable#View_transformPivotY 13651 */ 13652 @ViewDebug.ExportedProperty(category = "drawing") 13653 public float getPivotY() { 13654 return mRenderNode.getPivotY(); 13655 } 13656 13657 /** 13658 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 13659 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 13660 * Setting this property disables this behavior and causes the view to use only the 13661 * explicitly set pivotX and pivotY values. 13662 * 13663 * @param pivotY The y location of the pivot point. 13664 * @see #getRotation() 13665 * @see #getScaleX() 13666 * @see #getScaleY() 13667 * @see #getPivotY() 13668 * 13669 * @attr ref android.R.styleable#View_transformPivotY 13670 */ 13671 public void setPivotY(float pivotY) { 13672 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 13673 invalidateViewProperty(true, false); 13674 mRenderNode.setPivotY(pivotY); 13675 invalidateViewProperty(false, true); 13676 13677 invalidateParentIfNeededAndWasQuickRejected(); 13678 } 13679 } 13680 13681 /** 13682 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 13683 * completely transparent and 1 means the view is completely opaque. 13684 * 13685 * <p>By default this is 1.0f. 13686 * @return The opacity of the view. 13687 */ 13688 @ViewDebug.ExportedProperty(category = "drawing") 13689 public float getAlpha() { 13690 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 13691 } 13692 13693 /** 13694 * Sets the behavior for overlapping rendering for this view (see {@link 13695 * #hasOverlappingRendering()} for more details on this behavior). Calling this method 13696 * is an alternative to overriding {@link #hasOverlappingRendering()} in a subclass, 13697 * providing the value which is then used internally. That is, when {@link 13698 * #forceHasOverlappingRendering(boolean)} is called, the value of {@link 13699 * #hasOverlappingRendering()} is ignored and the value passed into this method is used 13700 * instead. 13701 * 13702 * @param hasOverlappingRendering The value for overlapping rendering to be used internally 13703 * instead of that returned by {@link #hasOverlappingRendering()}. 13704 * 13705 * @attr ref android.R.styleable#View_forceHasOverlappingRendering 13706 */ 13707 public void forceHasOverlappingRendering(boolean hasOverlappingRendering) { 13708 mPrivateFlags3 |= PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED; 13709 if (hasOverlappingRendering) { 13710 mPrivateFlags3 |= PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 13711 } else { 13712 mPrivateFlags3 &= ~PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE; 13713 } 13714 } 13715 13716 /** 13717 * Returns the value for overlapping rendering that is used internally. This is either 13718 * the value passed into {@link #forceHasOverlappingRendering(boolean)}, if called, or 13719 * the return value of {@link #hasOverlappingRendering()}, otherwise. 13720 * 13721 * @return The value for overlapping rendering being used internally. 13722 */ 13723 public final boolean getHasOverlappingRendering() { 13724 return (mPrivateFlags3 & PFLAG3_HAS_OVERLAPPING_RENDERING_FORCED) != 0 ? 13725 (mPrivateFlags3 & PFLAG3_OVERLAPPING_RENDERING_FORCED_VALUE) != 0 : 13726 hasOverlappingRendering(); 13727 } 13728 13729 /** 13730 * Returns whether this View has content which overlaps. 13731 * 13732 * <p>This function, intended to be overridden by specific View types, is an optimization when 13733 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 13734 * an offscreen buffer and then composited into place, which can be expensive. If the view has 13735 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 13736 * directly. An example of overlapping rendering is a TextView with a background image, such as 13737 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 13738 * ImageView with only the foreground image. The default implementation returns true; subclasses 13739 * should override if they have cases which can be optimized.</p> 13740 * 13741 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 13742 * necessitates that a View return true if it uses the methods internally without passing the 13743 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 13744 * 13745 * <p><strong>Note:</strong> The return value of this method is ignored if {@link 13746 * #forceHasOverlappingRendering(boolean)} has been called on this view.</p> 13747 * 13748 * @return true if the content in this view might overlap, false otherwise. 13749 */ 13750 @ViewDebug.ExportedProperty(category = "drawing") 13751 public boolean hasOverlappingRendering() { 13752 return true; 13753 } 13754 13755 /** 13756 * Sets the opacity of the view to a value from 0 to 1, where 0 means the view is 13757 * completely transparent and 1 means the view is completely opaque. 13758 * 13759 * <p class="note"><strong>Note:</strong> setting alpha to a translucent value (0 < alpha < 1) 13760 * can have significant performance implications, especially for large views. It is best to use 13761 * the alpha property sparingly and transiently, as in the case of fading animations.</p> 13762 * 13763 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 13764 * strongly recommended for performance reasons to either override 13765 * {@link #hasOverlappingRendering()} to return <code>false</code> if appropriate, or setting a 13766 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view for the duration 13767 * of the animation. On versions {@link android.os.Build.VERSION_CODES#M} and below, 13768 * the default path for rendering an unlayered View with alpha could add multiple milliseconds 13769 * of rendering cost, even for simple or small views. Starting with 13770 * {@link android.os.Build.VERSION_CODES#M}, {@link #LAYER_TYPE_HARDWARE} is automatically 13771 * applied to the view at the rendering level.</p> 13772 * 13773 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 13774 * responsible for applying the opacity itself.</p> 13775 * 13776 * <p>On versions {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and below, note that if 13777 * the view is backed by a {@link #setLayerType(int, android.graphics.Paint) layer} and is 13778 * associated with a {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an 13779 * alpha value less than 1.0 will supersede the alpha of the layer paint.</p> 13780 * 13781 * <p>Starting with {@link android.os.Build.VERSION_CODES#M}, setting a translucent alpha 13782 * value will clip a View to its bounds, unless the View returns <code>false</code> from 13783 * {@link #hasOverlappingRendering}.</p> 13784 * 13785 * @param alpha The opacity of the view. 13786 * 13787 * @see #hasOverlappingRendering() 13788 * @see #setLayerType(int, android.graphics.Paint) 13789 * 13790 * @attr ref android.R.styleable#View_alpha 13791 */ 13792 public void setAlpha(@FloatRange(from=0.0, to=1.0) float alpha) { 13793 ensureTransformationInfo(); 13794 if (mTransformationInfo.mAlpha != alpha) { 13795 // Report visibility changes, which can affect children, to accessibility 13796 if ((alpha == 0) ^ (mTransformationInfo.mAlpha == 0)) { 13797 notifySubtreeAccessibilityStateChangedIfNeeded(); 13798 } 13799 mTransformationInfo.mAlpha = alpha; 13800 if (onSetAlpha((int) (alpha * 255))) { 13801 mPrivateFlags |= PFLAG_ALPHA_SET; 13802 // subclass is handling alpha - don't optimize rendering cache invalidation 13803 invalidateParentCaches(); 13804 invalidate(true); 13805 } else { 13806 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13807 invalidateViewProperty(true, false); 13808 mRenderNode.setAlpha(getFinalAlpha()); 13809 } 13810 } 13811 } 13812 13813 /** 13814 * Faster version of setAlpha() which performs the same steps except there are 13815 * no calls to invalidate(). The caller of this function should perform proper invalidation 13816 * on the parent and this object. The return value indicates whether the subclass handles 13817 * alpha (the return value for onSetAlpha()). 13818 * 13819 * @param alpha The new value for the alpha property 13820 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 13821 * the new value for the alpha property is different from the old value 13822 */ 13823 boolean setAlphaNoInvalidation(float alpha) { 13824 ensureTransformationInfo(); 13825 if (mTransformationInfo.mAlpha != alpha) { 13826 mTransformationInfo.mAlpha = alpha; 13827 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 13828 if (subclassHandlesAlpha) { 13829 mPrivateFlags |= PFLAG_ALPHA_SET; 13830 return true; 13831 } else { 13832 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13833 mRenderNode.setAlpha(getFinalAlpha()); 13834 } 13835 } 13836 return false; 13837 } 13838 13839 /** 13840 * This property is hidden and intended only for use by the Fade transition, which 13841 * animates it to produce a visual translucency that does not side-effect (or get 13842 * affected by) the real alpha property. This value is composited with the other 13843 * alpha value (and the AlphaAnimation value, when that is present) to produce 13844 * a final visual translucency result, which is what is passed into the DisplayList. 13845 * 13846 * @hide 13847 */ 13848 public void setTransitionAlpha(float alpha) { 13849 ensureTransformationInfo(); 13850 if (mTransformationInfo.mTransitionAlpha != alpha) { 13851 mTransformationInfo.mTransitionAlpha = alpha; 13852 mPrivateFlags &= ~PFLAG_ALPHA_SET; 13853 invalidateViewProperty(true, false); 13854 mRenderNode.setAlpha(getFinalAlpha()); 13855 } 13856 } 13857 13858 /** 13859 * Calculates the visual alpha of this view, which is a combination of the actual 13860 * alpha value and the transitionAlpha value (if set). 13861 */ 13862 private float getFinalAlpha() { 13863 if (mTransformationInfo != null) { 13864 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 13865 } 13866 return 1; 13867 } 13868 13869 /** 13870 * This property is hidden and intended only for use by the Fade transition, which 13871 * animates it to produce a visual translucency that does not side-effect (or get 13872 * affected by) the real alpha property. This value is composited with the other 13873 * alpha value (and the AlphaAnimation value, when that is present) to produce 13874 * a final visual translucency result, which is what is passed into the DisplayList. 13875 * 13876 * @hide 13877 */ 13878 @ViewDebug.ExportedProperty(category = "drawing") 13879 public float getTransitionAlpha() { 13880 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 13881 } 13882 13883 /** 13884 * Top position of this view relative to its parent. 13885 * 13886 * @return The top of this view, in pixels. 13887 */ 13888 @ViewDebug.CapturedViewProperty 13889 public final int getTop() { 13890 return mTop; 13891 } 13892 13893 /** 13894 * Sets the top position of this view relative to its parent. This method is meant to be called 13895 * by the layout system and should not generally be called otherwise, because the property 13896 * may be changed at any time by the layout. 13897 * 13898 * @param top The top of this view, in pixels. 13899 */ 13900 public final void setTop(int top) { 13901 if (top != mTop) { 13902 final boolean matrixIsIdentity = hasIdentityMatrix(); 13903 if (matrixIsIdentity) { 13904 if (mAttachInfo != null) { 13905 int minTop; 13906 int yLoc; 13907 if (top < mTop) { 13908 minTop = top; 13909 yLoc = top - mTop; 13910 } else { 13911 minTop = mTop; 13912 yLoc = 0; 13913 } 13914 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 13915 } 13916 } else { 13917 // Double-invalidation is necessary to capture view's old and new areas 13918 invalidate(true); 13919 } 13920 13921 int width = mRight - mLeft; 13922 int oldHeight = mBottom - mTop; 13923 13924 mTop = top; 13925 mRenderNode.setTop(mTop); 13926 13927 sizeChange(width, mBottom - mTop, width, oldHeight); 13928 13929 if (!matrixIsIdentity) { 13930 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 13931 invalidate(true); 13932 } 13933 mBackgroundSizeChanged = true; 13934 mDefaultFocusHighlightSizeChanged = true; 13935 if (mForegroundInfo != null) { 13936 mForegroundInfo.mBoundsChanged = true; 13937 } 13938 invalidateParentIfNeeded(); 13939 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 13940 // View was rejected last time it was drawn by its parent; this may have changed 13941 invalidateParentIfNeeded(); 13942 } 13943 } 13944 } 13945 13946 /** 13947 * Bottom position of this view relative to its parent. 13948 * 13949 * @return The bottom of this view, in pixels. 13950 */ 13951 @ViewDebug.CapturedViewProperty 13952 public final int getBottom() { 13953 return mBottom; 13954 } 13955 13956 /** 13957 * True if this view has changed since the last time being drawn. 13958 * 13959 * @return The dirty state of this view. 13960 */ 13961 public boolean isDirty() { 13962 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 13963 } 13964 13965 /** 13966 * Sets the bottom position of this view relative to its parent. This method is meant to be 13967 * called by the layout system and should not generally be called otherwise, because the 13968 * property may be changed at any time by the layout. 13969 * 13970 * @param bottom The bottom of this view, in pixels. 13971 */ 13972 public final void setBottom(int bottom) { 13973 if (bottom != mBottom) { 13974 final boolean matrixIsIdentity = hasIdentityMatrix(); 13975 if (matrixIsIdentity) { 13976 if (mAttachInfo != null) { 13977 int maxBottom; 13978 if (bottom < mBottom) { 13979 maxBottom = mBottom; 13980 } else { 13981 maxBottom = bottom; 13982 } 13983 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 13984 } 13985 } else { 13986 // Double-invalidation is necessary to capture view's old and new areas 13987 invalidate(true); 13988 } 13989 13990 int width = mRight - mLeft; 13991 int oldHeight = mBottom - mTop; 13992 13993 mBottom = bottom; 13994 mRenderNode.setBottom(mBottom); 13995 13996 sizeChange(width, mBottom - mTop, width, oldHeight); 13997 13998 if (!matrixIsIdentity) { 13999 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14000 invalidate(true); 14001 } 14002 mBackgroundSizeChanged = true; 14003 mDefaultFocusHighlightSizeChanged = true; 14004 if (mForegroundInfo != null) { 14005 mForegroundInfo.mBoundsChanged = true; 14006 } 14007 invalidateParentIfNeeded(); 14008 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 14009 // View was rejected last time it was drawn by its parent; this may have changed 14010 invalidateParentIfNeeded(); 14011 } 14012 } 14013 } 14014 14015 /** 14016 * Left position of this view relative to its parent. 14017 * 14018 * @return The left edge of this view, in pixels. 14019 */ 14020 @ViewDebug.CapturedViewProperty 14021 public final int getLeft() { 14022 return mLeft; 14023 } 14024 14025 /** 14026 * Sets the left position of this view relative to its parent. This method is meant to be called 14027 * by the layout system and should not generally be called otherwise, because the property 14028 * may be changed at any time by the layout. 14029 * 14030 * @param left The left of this view, in pixels. 14031 */ 14032 public final void setLeft(int left) { 14033 if (left != mLeft) { 14034 final boolean matrixIsIdentity = hasIdentityMatrix(); 14035 if (matrixIsIdentity) { 14036 if (mAttachInfo != null) { 14037 int minLeft; 14038 int xLoc; 14039 if (left < mLeft) { 14040 minLeft = left; 14041 xLoc = left - mLeft; 14042 } else { 14043 minLeft = mLeft; 14044 xLoc = 0; 14045 } 14046 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 14047 } 14048 } else { 14049 // Double-invalidation is necessary to capture view's old and new areas 14050 invalidate(true); 14051 } 14052 14053 int oldWidth = mRight - mLeft; 14054 int height = mBottom - mTop; 14055 14056 mLeft = left; 14057 mRenderNode.setLeft(left); 14058 14059 sizeChange(mRight - mLeft, height, oldWidth, height); 14060 14061 if (!matrixIsIdentity) { 14062 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14063 invalidate(true); 14064 } 14065 mBackgroundSizeChanged = true; 14066 mDefaultFocusHighlightSizeChanged = true; 14067 if (mForegroundInfo != null) { 14068 mForegroundInfo.mBoundsChanged = true; 14069 } 14070 invalidateParentIfNeeded(); 14071 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 14072 // View was rejected last time it was drawn by its parent; this may have changed 14073 invalidateParentIfNeeded(); 14074 } 14075 } 14076 } 14077 14078 /** 14079 * Right position of this view relative to its parent. 14080 * 14081 * @return The right edge of this view, in pixels. 14082 */ 14083 @ViewDebug.CapturedViewProperty 14084 public final int getRight() { 14085 return mRight; 14086 } 14087 14088 /** 14089 * Sets the right position of this view relative to its parent. This method is meant to be called 14090 * by the layout system and should not generally be called otherwise, because the property 14091 * may be changed at any time by the layout. 14092 * 14093 * @param right The right of this view, in pixels. 14094 */ 14095 public final void setRight(int right) { 14096 if (right != mRight) { 14097 final boolean matrixIsIdentity = hasIdentityMatrix(); 14098 if (matrixIsIdentity) { 14099 if (mAttachInfo != null) { 14100 int maxRight; 14101 if (right < mRight) { 14102 maxRight = mRight; 14103 } else { 14104 maxRight = right; 14105 } 14106 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 14107 } 14108 } else { 14109 // Double-invalidation is necessary to capture view's old and new areas 14110 invalidate(true); 14111 } 14112 14113 int oldWidth = mRight - mLeft; 14114 int height = mBottom - mTop; 14115 14116 mRight = right; 14117 mRenderNode.setRight(mRight); 14118 14119 sizeChange(mRight - mLeft, height, oldWidth, height); 14120 14121 if (!matrixIsIdentity) { 14122 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 14123 invalidate(true); 14124 } 14125 mBackgroundSizeChanged = true; 14126 mDefaultFocusHighlightSizeChanged = true; 14127 if (mForegroundInfo != null) { 14128 mForegroundInfo.mBoundsChanged = true; 14129 } 14130 invalidateParentIfNeeded(); 14131 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 14132 // View was rejected last time it was drawn by its parent; this may have changed 14133 invalidateParentIfNeeded(); 14134 } 14135 } 14136 } 14137 14138 /** 14139 * The visual x position of this view, in pixels. This is equivalent to the 14140 * {@link #setTranslationX(float) translationX} property plus the current 14141 * {@link #getLeft() left} property. 14142 * 14143 * @return The visual x position of this view, in pixels. 14144 */ 14145 @ViewDebug.ExportedProperty(category = "drawing") 14146 public float getX() { 14147 return mLeft + getTranslationX(); 14148 } 14149 14150 /** 14151 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 14152 * {@link #setTranslationX(float) translationX} property to be the difference between 14153 * the x value passed in and the current {@link #getLeft() left} property. 14154 * 14155 * @param x The visual x position of this view, in pixels. 14156 */ 14157 public void setX(float x) { 14158 setTranslationX(x - mLeft); 14159 } 14160 14161 /** 14162 * The visual y position of this view, in pixels. This is equivalent to the 14163 * {@link #setTranslationY(float) translationY} property plus the current 14164 * {@link #getTop() top} property. 14165 * 14166 * @return The visual y position of this view, in pixels. 14167 */ 14168 @ViewDebug.ExportedProperty(category = "drawing") 14169 public float getY() { 14170 return mTop + getTranslationY(); 14171 } 14172 14173 /** 14174 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 14175 * {@link #setTranslationY(float) translationY} property to be the difference between 14176 * the y value passed in and the current {@link #getTop() top} property. 14177 * 14178 * @param y The visual y position of this view, in pixels. 14179 */ 14180 public void setY(float y) { 14181 setTranslationY(y - mTop); 14182 } 14183 14184 /** 14185 * The visual z position of this view, in pixels. This is equivalent to the 14186 * {@link #setTranslationZ(float) translationZ} property plus the current 14187 * {@link #getElevation() elevation} property. 14188 * 14189 * @return The visual z position of this view, in pixels. 14190 */ 14191 @ViewDebug.ExportedProperty(category = "drawing") 14192 public float getZ() { 14193 return getElevation() + getTranslationZ(); 14194 } 14195 14196 /** 14197 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 14198 * {@link #setTranslationZ(float) translationZ} property to be the difference between 14199 * the x value passed in and the current {@link #getElevation() elevation} property. 14200 * 14201 * @param z The visual z position of this view, in pixels. 14202 */ 14203 public void setZ(float z) { 14204 setTranslationZ(z - getElevation()); 14205 } 14206 14207 /** 14208 * The base elevation of this view relative to its parent, in pixels. 14209 * 14210 * @return The base depth position of the view, in pixels. 14211 */ 14212 @ViewDebug.ExportedProperty(category = "drawing") 14213 public float getElevation() { 14214 return mRenderNode.getElevation(); 14215 } 14216 14217 /** 14218 * Sets the base elevation of this view, in pixels. 14219 * 14220 * @attr ref android.R.styleable#View_elevation 14221 */ 14222 public void setElevation(float elevation) { 14223 if (elevation != getElevation()) { 14224 invalidateViewProperty(true, false); 14225 mRenderNode.setElevation(elevation); 14226 invalidateViewProperty(false, true); 14227 14228 invalidateParentIfNeededAndWasQuickRejected(); 14229 } 14230 } 14231 14232 /** 14233 * The horizontal location of this view relative to its {@link #getLeft() left} position. 14234 * This position is post-layout, in addition to wherever the object's 14235 * layout placed it. 14236 * 14237 * @return The horizontal position of this view relative to its left position, in pixels. 14238 */ 14239 @ViewDebug.ExportedProperty(category = "drawing") 14240 public float getTranslationX() { 14241 return mRenderNode.getTranslationX(); 14242 } 14243 14244 /** 14245 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 14246 * This effectively positions the object post-layout, in addition to wherever the object's 14247 * layout placed it. 14248 * 14249 * @param translationX The horizontal position of this view relative to its left position, 14250 * in pixels. 14251 * 14252 * @attr ref android.R.styleable#View_translationX 14253 */ 14254 public void setTranslationX(float translationX) { 14255 if (translationX != getTranslationX()) { 14256 invalidateViewProperty(true, false); 14257 mRenderNode.setTranslationX(translationX); 14258 invalidateViewProperty(false, true); 14259 14260 invalidateParentIfNeededAndWasQuickRejected(); 14261 notifySubtreeAccessibilityStateChangedIfNeeded(); 14262 } 14263 } 14264 14265 /** 14266 * The vertical location of this view relative to its {@link #getTop() top} position. 14267 * This position is post-layout, in addition to wherever the object's 14268 * layout placed it. 14269 * 14270 * @return The vertical position of this view relative to its top position, 14271 * in pixels. 14272 */ 14273 @ViewDebug.ExportedProperty(category = "drawing") 14274 public float getTranslationY() { 14275 return mRenderNode.getTranslationY(); 14276 } 14277 14278 /** 14279 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 14280 * This effectively positions the object post-layout, in addition to wherever the object's 14281 * layout placed it. 14282 * 14283 * @param translationY The vertical position of this view relative to its top position, 14284 * in pixels. 14285 * 14286 * @attr ref android.R.styleable#View_translationY 14287 */ 14288 public void setTranslationY(float translationY) { 14289 if (translationY != getTranslationY()) { 14290 invalidateViewProperty(true, false); 14291 mRenderNode.setTranslationY(translationY); 14292 invalidateViewProperty(false, true); 14293 14294 invalidateParentIfNeededAndWasQuickRejected(); 14295 notifySubtreeAccessibilityStateChangedIfNeeded(); 14296 } 14297 } 14298 14299 /** 14300 * The depth location of this view relative to its {@link #getElevation() elevation}. 14301 * 14302 * @return The depth of this view relative to its elevation. 14303 */ 14304 @ViewDebug.ExportedProperty(category = "drawing") 14305 public float getTranslationZ() { 14306 return mRenderNode.getTranslationZ(); 14307 } 14308 14309 /** 14310 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 14311 * 14312 * @attr ref android.R.styleable#View_translationZ 14313 */ 14314 public void setTranslationZ(float translationZ) { 14315 if (translationZ != getTranslationZ()) { 14316 invalidateViewProperty(true, false); 14317 mRenderNode.setTranslationZ(translationZ); 14318 invalidateViewProperty(false, true); 14319 14320 invalidateParentIfNeededAndWasQuickRejected(); 14321 } 14322 } 14323 14324 /** @hide */ 14325 public void setAnimationMatrix(Matrix matrix) { 14326 invalidateViewProperty(true, false); 14327 mRenderNode.setAnimationMatrix(matrix); 14328 invalidateViewProperty(false, true); 14329 14330 invalidateParentIfNeededAndWasQuickRejected(); 14331 } 14332 14333 /** 14334 * Returns the current StateListAnimator if exists. 14335 * 14336 * @return StateListAnimator or null if it does not exists 14337 * @see #setStateListAnimator(android.animation.StateListAnimator) 14338 */ 14339 public StateListAnimator getStateListAnimator() { 14340 return mStateListAnimator; 14341 } 14342 14343 /** 14344 * Attaches the provided StateListAnimator to this View. 14345 * <p> 14346 * Any previously attached StateListAnimator will be detached. 14347 * 14348 * @param stateListAnimator The StateListAnimator to update the view 14349 * @see android.animation.StateListAnimator 14350 */ 14351 public void setStateListAnimator(StateListAnimator stateListAnimator) { 14352 if (mStateListAnimator == stateListAnimator) { 14353 return; 14354 } 14355 if (mStateListAnimator != null) { 14356 mStateListAnimator.setTarget(null); 14357 } 14358 mStateListAnimator = stateListAnimator; 14359 if (stateListAnimator != null) { 14360 stateListAnimator.setTarget(this); 14361 if (isAttachedToWindow()) { 14362 stateListAnimator.setState(getDrawableState()); 14363 } 14364 } 14365 } 14366 14367 /** 14368 * Returns whether the Outline should be used to clip the contents of the View. 14369 * <p> 14370 * Note that this flag will only be respected if the View's Outline returns true from 14371 * {@link Outline#canClip()}. 14372 * 14373 * @see #setOutlineProvider(ViewOutlineProvider) 14374 * @see #setClipToOutline(boolean) 14375 */ 14376 public final boolean getClipToOutline() { 14377 return mRenderNode.getClipToOutline(); 14378 } 14379 14380 /** 14381 * Sets whether the View's Outline should be used to clip the contents of the View. 14382 * <p> 14383 * Only a single non-rectangular clip can be applied on a View at any time. 14384 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 14385 * circular reveal} animation take priority over Outline clipping, and 14386 * child Outline clipping takes priority over Outline clipping done by a 14387 * parent. 14388 * <p> 14389 * Note that this flag will only be respected if the View's Outline returns true from 14390 * {@link Outline#canClip()}. 14391 * 14392 * @see #setOutlineProvider(ViewOutlineProvider) 14393 * @see #getClipToOutline() 14394 */ 14395 public void setClipToOutline(boolean clipToOutline) { 14396 damageInParent(); 14397 if (getClipToOutline() != clipToOutline) { 14398 mRenderNode.setClipToOutline(clipToOutline); 14399 } 14400 } 14401 14402 // correspond to the enum values of View_outlineProvider 14403 private static final int PROVIDER_BACKGROUND = 0; 14404 private static final int PROVIDER_NONE = 1; 14405 private static final int PROVIDER_BOUNDS = 2; 14406 private static final int PROVIDER_PADDED_BOUNDS = 3; 14407 private void setOutlineProviderFromAttribute(int providerInt) { 14408 switch (providerInt) { 14409 case PROVIDER_BACKGROUND: 14410 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 14411 break; 14412 case PROVIDER_NONE: 14413 setOutlineProvider(null); 14414 break; 14415 case PROVIDER_BOUNDS: 14416 setOutlineProvider(ViewOutlineProvider.BOUNDS); 14417 break; 14418 case PROVIDER_PADDED_BOUNDS: 14419 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 14420 break; 14421 } 14422 } 14423 14424 /** 14425 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 14426 * the shape of the shadow it casts, and enables outline clipping. 14427 * <p> 14428 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 14429 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 14430 * outline provider with this method allows this behavior to be overridden. 14431 * <p> 14432 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 14433 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 14434 * <p> 14435 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 14436 * 14437 * @see #setClipToOutline(boolean) 14438 * @see #getClipToOutline() 14439 * @see #getOutlineProvider() 14440 */ 14441 public void setOutlineProvider(ViewOutlineProvider provider) { 14442 mOutlineProvider = provider; 14443 invalidateOutline(); 14444 } 14445 14446 /** 14447 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 14448 * that defines the shape of the shadow it casts, and enables outline clipping. 14449 * 14450 * @see #setOutlineProvider(ViewOutlineProvider) 14451 */ 14452 public ViewOutlineProvider getOutlineProvider() { 14453 return mOutlineProvider; 14454 } 14455 14456 /** 14457 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 14458 * 14459 * @see #setOutlineProvider(ViewOutlineProvider) 14460 */ 14461 public void invalidateOutline() { 14462 rebuildOutline(); 14463 14464 notifySubtreeAccessibilityStateChangedIfNeeded(); 14465 invalidateViewProperty(false, false); 14466 } 14467 14468 /** 14469 * Internal version of {@link #invalidateOutline()} which invalidates the 14470 * outline without invalidating the view itself. This is intended to be called from 14471 * within methods in the View class itself which are the result of the view being 14472 * invalidated already. For example, when we are drawing the background of a View, 14473 * we invalidate the outline in case it changed in the meantime, but we do not 14474 * need to invalidate the view because we're already drawing the background as part 14475 * of drawing the view in response to an earlier invalidation of the view. 14476 */ 14477 private void rebuildOutline() { 14478 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 14479 if (mAttachInfo == null) return; 14480 14481 if (mOutlineProvider == null) { 14482 // no provider, remove outline 14483 mRenderNode.setOutline(null); 14484 } else { 14485 final Outline outline = mAttachInfo.mTmpOutline; 14486 outline.setEmpty(); 14487 outline.setAlpha(1.0f); 14488 14489 mOutlineProvider.getOutline(this, outline); 14490 mRenderNode.setOutline(outline); 14491 } 14492 } 14493 14494 /** 14495 * HierarchyViewer only 14496 * 14497 * @hide 14498 */ 14499 @ViewDebug.ExportedProperty(category = "drawing") 14500 public boolean hasShadow() { 14501 return mRenderNode.hasShadow(); 14502 } 14503 14504 14505 /** @hide */ 14506 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 14507 mRenderNode.setRevealClip(shouldClip, x, y, radius); 14508 invalidateViewProperty(false, false); 14509 } 14510 14511 /** 14512 * Hit rectangle in parent's coordinates 14513 * 14514 * @param outRect The hit rectangle of the view. 14515 */ 14516 public void getHitRect(Rect outRect) { 14517 if (hasIdentityMatrix() || mAttachInfo == null) { 14518 outRect.set(mLeft, mTop, mRight, mBottom); 14519 } else { 14520 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 14521 tmpRect.set(0, 0, getWidth(), getHeight()); 14522 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 14523 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 14524 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 14525 } 14526 } 14527 14528 /** 14529 * Determines whether the given point, in local coordinates is inside the view. 14530 */ 14531 /*package*/ final boolean pointInView(float localX, float localY) { 14532 return pointInView(localX, localY, 0); 14533 } 14534 14535 /** 14536 * Utility method to determine whether the given point, in local coordinates, 14537 * is inside the view, where the area of the view is expanded by the slop factor. 14538 * This method is called while processing touch-move events to determine if the event 14539 * is still within the view. 14540 * 14541 * @hide 14542 */ 14543 public boolean pointInView(float localX, float localY, float slop) { 14544 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 14545 localY < ((mBottom - mTop) + slop); 14546 } 14547 14548 /** 14549 * When a view has focus and the user navigates away from it, the next view is searched for 14550 * starting from the rectangle filled in by this method. 14551 * 14552 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 14553 * of the view. However, if your view maintains some idea of internal selection, 14554 * such as a cursor, or a selected row or column, you should override this method and 14555 * fill in a more specific rectangle. 14556 * 14557 * @param r The rectangle to fill in, in this view's coordinates. 14558 */ 14559 public void getFocusedRect(Rect r) { 14560 getDrawingRect(r); 14561 } 14562 14563 /** 14564 * If some part of this view is not clipped by any of its parents, then 14565 * return that area in r in global (root) coordinates. To convert r to local 14566 * coordinates (without taking possible View rotations into account), offset 14567 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 14568 * If the view is completely clipped or translated out, return false. 14569 * 14570 * @param r If true is returned, r holds the global coordinates of the 14571 * visible portion of this view. 14572 * @param globalOffset If true is returned, globalOffset holds the dx,dy 14573 * between this view and its root. globalOffet may be null. 14574 * @return true if r is non-empty (i.e. part of the view is visible at the 14575 * root level. 14576 */ 14577 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 14578 int width = mRight - mLeft; 14579 int height = mBottom - mTop; 14580 if (width > 0 && height > 0) { 14581 r.set(0, 0, width, height); 14582 if (globalOffset != null) { 14583 globalOffset.set(-mScrollX, -mScrollY); 14584 } 14585 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 14586 } 14587 return false; 14588 } 14589 14590 public final boolean getGlobalVisibleRect(Rect r) { 14591 return getGlobalVisibleRect(r, null); 14592 } 14593 14594 public final boolean getLocalVisibleRect(Rect r) { 14595 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 14596 if (getGlobalVisibleRect(r, offset)) { 14597 r.offset(-offset.x, -offset.y); // make r local 14598 return true; 14599 } 14600 return false; 14601 } 14602 14603 /** 14604 * Offset this view's vertical location by the specified number of pixels. 14605 * 14606 * @param offset the number of pixels to offset the view by 14607 */ 14608 public void offsetTopAndBottom(int offset) { 14609 if (offset != 0) { 14610 final boolean matrixIsIdentity = hasIdentityMatrix(); 14611 if (matrixIsIdentity) { 14612 if (isHardwareAccelerated()) { 14613 invalidateViewProperty(false, false); 14614 } else { 14615 final ViewParent p = mParent; 14616 if (p != null && mAttachInfo != null) { 14617 final Rect r = mAttachInfo.mTmpInvalRect; 14618 int minTop; 14619 int maxBottom; 14620 int yLoc; 14621 if (offset < 0) { 14622 minTop = mTop + offset; 14623 maxBottom = mBottom; 14624 yLoc = offset; 14625 } else { 14626 minTop = mTop; 14627 maxBottom = mBottom + offset; 14628 yLoc = 0; 14629 } 14630 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 14631 p.invalidateChild(this, r); 14632 } 14633 } 14634 } else { 14635 invalidateViewProperty(false, false); 14636 } 14637 14638 mTop += offset; 14639 mBottom += offset; 14640 mRenderNode.offsetTopAndBottom(offset); 14641 if (isHardwareAccelerated()) { 14642 invalidateViewProperty(false, false); 14643 invalidateParentIfNeededAndWasQuickRejected(); 14644 } else { 14645 if (!matrixIsIdentity) { 14646 invalidateViewProperty(false, true); 14647 } 14648 invalidateParentIfNeeded(); 14649 } 14650 notifySubtreeAccessibilityStateChangedIfNeeded(); 14651 } 14652 } 14653 14654 /** 14655 * Offset this view's horizontal location by the specified amount of pixels. 14656 * 14657 * @param offset the number of pixels to offset the view by 14658 */ 14659 public void offsetLeftAndRight(int offset) { 14660 if (offset != 0) { 14661 final boolean matrixIsIdentity = hasIdentityMatrix(); 14662 if (matrixIsIdentity) { 14663 if (isHardwareAccelerated()) { 14664 invalidateViewProperty(false, false); 14665 } else { 14666 final ViewParent p = mParent; 14667 if (p != null && mAttachInfo != null) { 14668 final Rect r = mAttachInfo.mTmpInvalRect; 14669 int minLeft; 14670 int maxRight; 14671 if (offset < 0) { 14672 minLeft = mLeft + offset; 14673 maxRight = mRight; 14674 } else { 14675 minLeft = mLeft; 14676 maxRight = mRight + offset; 14677 } 14678 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 14679 p.invalidateChild(this, r); 14680 } 14681 } 14682 } else { 14683 invalidateViewProperty(false, false); 14684 } 14685 14686 mLeft += offset; 14687 mRight += offset; 14688 mRenderNode.offsetLeftAndRight(offset); 14689 if (isHardwareAccelerated()) { 14690 invalidateViewProperty(false, false); 14691 invalidateParentIfNeededAndWasQuickRejected(); 14692 } else { 14693 if (!matrixIsIdentity) { 14694 invalidateViewProperty(false, true); 14695 } 14696 invalidateParentIfNeeded(); 14697 } 14698 notifySubtreeAccessibilityStateChangedIfNeeded(); 14699 } 14700 } 14701 14702 /** 14703 * Get the LayoutParams associated with this view. All views should have 14704 * layout parameters. These supply parameters to the <i>parent</i> of this 14705 * view specifying how it should be arranged. There are many subclasses of 14706 * ViewGroup.LayoutParams, and these correspond to the different subclasses 14707 * of ViewGroup that are responsible for arranging their children. 14708 * 14709 * This method may return null if this View is not attached to a parent 14710 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 14711 * was not invoked successfully. When a View is attached to a parent 14712 * ViewGroup, this method must not return null. 14713 * 14714 * @return The LayoutParams associated with this view, or null if no 14715 * parameters have been set yet 14716 */ 14717 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 14718 public ViewGroup.LayoutParams getLayoutParams() { 14719 return mLayoutParams; 14720 } 14721 14722 /** 14723 * Set the layout parameters associated with this view. These supply 14724 * parameters to the <i>parent</i> of this view specifying how it should be 14725 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 14726 * correspond to the different subclasses of ViewGroup that are responsible 14727 * for arranging their children. 14728 * 14729 * @param params The layout parameters for this view, cannot be null 14730 */ 14731 public void setLayoutParams(ViewGroup.LayoutParams params) { 14732 if (params == null) { 14733 throw new NullPointerException("Layout parameters cannot be null"); 14734 } 14735 mLayoutParams = params; 14736 resolveLayoutParams(); 14737 if (mParent instanceof ViewGroup) { 14738 ((ViewGroup) mParent).onSetLayoutParams(this, params); 14739 } 14740 requestLayout(); 14741 } 14742 14743 /** 14744 * Resolve the layout parameters depending on the resolved layout direction 14745 * 14746 * @hide 14747 */ 14748 public void resolveLayoutParams() { 14749 if (mLayoutParams != null) { 14750 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 14751 } 14752 } 14753 14754 /** 14755 * Set the scrolled position of your view. This will cause a call to 14756 * {@link #onScrollChanged(int, int, int, int)} and the view will be 14757 * invalidated. 14758 * @param x the x position to scroll to 14759 * @param y the y position to scroll to 14760 */ 14761 public void scrollTo(int x, int y) { 14762 if (mScrollX != x || mScrollY != y) { 14763 int oldX = mScrollX; 14764 int oldY = mScrollY; 14765 mScrollX = x; 14766 mScrollY = y; 14767 invalidateParentCaches(); 14768 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 14769 if (!awakenScrollBars()) { 14770 postInvalidateOnAnimation(); 14771 } 14772 } 14773 } 14774 14775 /** 14776 * Move the scrolled position of your view. This will cause a call to 14777 * {@link #onScrollChanged(int, int, int, int)} and the view will be 14778 * invalidated. 14779 * @param x the amount of pixels to scroll by horizontally 14780 * @param y the amount of pixels to scroll by vertically 14781 */ 14782 public void scrollBy(int x, int y) { 14783 scrollTo(mScrollX + x, mScrollY + y); 14784 } 14785 14786 /** 14787 * <p>Trigger the scrollbars to draw. When invoked this method starts an 14788 * animation to fade the scrollbars out after a default delay. If a subclass 14789 * provides animated scrolling, the start delay should equal the duration 14790 * of the scrolling animation.</p> 14791 * 14792 * <p>The animation starts only if at least one of the scrollbars is 14793 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 14794 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 14795 * this method returns true, and false otherwise. If the animation is 14796 * started, this method calls {@link #invalidate()}; in that case the 14797 * caller should not call {@link #invalidate()}.</p> 14798 * 14799 * <p>This method should be invoked every time a subclass directly updates 14800 * the scroll parameters.</p> 14801 * 14802 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 14803 * and {@link #scrollTo(int, int)}.</p> 14804 * 14805 * @return true if the animation is played, false otherwise 14806 * 14807 * @see #awakenScrollBars(int) 14808 * @see #scrollBy(int, int) 14809 * @see #scrollTo(int, int) 14810 * @see #isHorizontalScrollBarEnabled() 14811 * @see #isVerticalScrollBarEnabled() 14812 * @see #setHorizontalScrollBarEnabled(boolean) 14813 * @see #setVerticalScrollBarEnabled(boolean) 14814 */ 14815 protected boolean awakenScrollBars() { 14816 return mScrollCache != null && 14817 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 14818 } 14819 14820 /** 14821 * Trigger the scrollbars to draw. 14822 * This method differs from awakenScrollBars() only in its default duration. 14823 * initialAwakenScrollBars() will show the scroll bars for longer than 14824 * usual to give the user more of a chance to notice them. 14825 * 14826 * @return true if the animation is played, false otherwise. 14827 */ 14828 private boolean initialAwakenScrollBars() { 14829 return mScrollCache != null && 14830 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 14831 } 14832 14833 /** 14834 * <p> 14835 * Trigger the scrollbars to draw. When invoked this method starts an 14836 * animation to fade the scrollbars out after a fixed delay. If a subclass 14837 * provides animated scrolling, the start delay should equal the duration of 14838 * the scrolling animation. 14839 * </p> 14840 * 14841 * <p> 14842 * The animation starts only if at least one of the scrollbars is enabled, 14843 * as specified by {@link #isHorizontalScrollBarEnabled()} and 14844 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 14845 * this method returns true, and false otherwise. If the animation is 14846 * started, this method calls {@link #invalidate()}; in that case the caller 14847 * should not call {@link #invalidate()}. 14848 * </p> 14849 * 14850 * <p> 14851 * This method should be invoked every time a subclass directly updates the 14852 * scroll parameters. 14853 * </p> 14854 * 14855 * @param startDelay the delay, in milliseconds, after which the animation 14856 * should start; when the delay is 0, the animation starts 14857 * immediately 14858 * @return true if the animation is played, false otherwise 14859 * 14860 * @see #scrollBy(int, int) 14861 * @see #scrollTo(int, int) 14862 * @see #isHorizontalScrollBarEnabled() 14863 * @see #isVerticalScrollBarEnabled() 14864 * @see #setHorizontalScrollBarEnabled(boolean) 14865 * @see #setVerticalScrollBarEnabled(boolean) 14866 */ 14867 protected boolean awakenScrollBars(int startDelay) { 14868 return awakenScrollBars(startDelay, true); 14869 } 14870 14871 /** 14872 * <p> 14873 * Trigger the scrollbars to draw. When invoked this method starts an 14874 * animation to fade the scrollbars out after a fixed delay. If a subclass 14875 * provides animated scrolling, the start delay should equal the duration of 14876 * the scrolling animation. 14877 * </p> 14878 * 14879 * <p> 14880 * The animation starts only if at least one of the scrollbars is enabled, 14881 * as specified by {@link #isHorizontalScrollBarEnabled()} and 14882 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 14883 * this method returns true, and false otherwise. If the animation is 14884 * started, this method calls {@link #invalidate()} if the invalidate parameter 14885 * is set to true; in that case the caller 14886 * should not call {@link #invalidate()}. 14887 * </p> 14888 * 14889 * <p> 14890 * This method should be invoked every time a subclass directly updates the 14891 * scroll parameters. 14892 * </p> 14893 * 14894 * @param startDelay the delay, in milliseconds, after which the animation 14895 * should start; when the delay is 0, the animation starts 14896 * immediately 14897 * 14898 * @param invalidate Whether this method should call invalidate 14899 * 14900 * @return true if the animation is played, false otherwise 14901 * 14902 * @see #scrollBy(int, int) 14903 * @see #scrollTo(int, int) 14904 * @see #isHorizontalScrollBarEnabled() 14905 * @see #isVerticalScrollBarEnabled() 14906 * @see #setHorizontalScrollBarEnabled(boolean) 14907 * @see #setVerticalScrollBarEnabled(boolean) 14908 */ 14909 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 14910 final ScrollabilityCache scrollCache = mScrollCache; 14911 14912 if (scrollCache == null || !scrollCache.fadeScrollBars) { 14913 return false; 14914 } 14915 14916 if (scrollCache.scrollBar == null) { 14917 scrollCache.scrollBar = new ScrollBarDrawable(); 14918 scrollCache.scrollBar.setState(getDrawableState()); 14919 scrollCache.scrollBar.setCallback(this); 14920 } 14921 14922 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 14923 14924 if (invalidate) { 14925 // Invalidate to show the scrollbars 14926 postInvalidateOnAnimation(); 14927 } 14928 14929 if (scrollCache.state == ScrollabilityCache.OFF) { 14930 // FIXME: this is copied from WindowManagerService. 14931 // We should get this value from the system when it 14932 // is possible to do so. 14933 final int KEY_REPEAT_FIRST_DELAY = 750; 14934 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 14935 } 14936 14937 // Tell mScrollCache when we should start fading. This may 14938 // extend the fade start time if one was already scheduled 14939 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 14940 scrollCache.fadeStartTime = fadeStartTime; 14941 scrollCache.state = ScrollabilityCache.ON; 14942 14943 // Schedule our fader to run, unscheduling any old ones first 14944 if (mAttachInfo != null) { 14945 mAttachInfo.mHandler.removeCallbacks(scrollCache); 14946 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 14947 } 14948 14949 return true; 14950 } 14951 14952 return false; 14953 } 14954 14955 /** 14956 * Do not invalidate views which are not visible and which are not running an animation. They 14957 * will not get drawn and they should not set dirty flags as if they will be drawn 14958 */ 14959 private boolean skipInvalidate() { 14960 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 14961 (!(mParent instanceof ViewGroup) || 14962 !((ViewGroup) mParent).isViewTransitioning(this)); 14963 } 14964 14965 /** 14966 * Mark the area defined by dirty as needing to be drawn. If the view is 14967 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 14968 * point in the future. 14969 * <p> 14970 * This must be called from a UI thread. To call from a non-UI thread, call 14971 * {@link #postInvalidate()}. 14972 * <p> 14973 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 14974 * {@code dirty}. 14975 * 14976 * @param dirty the rectangle representing the bounds of the dirty region 14977 */ 14978 public void invalidate(Rect dirty) { 14979 final int scrollX = mScrollX; 14980 final int scrollY = mScrollY; 14981 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 14982 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 14983 } 14984 14985 /** 14986 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 14987 * coordinates of the dirty rect are relative to the view. If the view is 14988 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 14989 * point in the future. 14990 * <p> 14991 * This must be called from a UI thread. To call from a non-UI thread, call 14992 * {@link #postInvalidate()}. 14993 * 14994 * @param l the left position of the dirty region 14995 * @param t the top position of the dirty region 14996 * @param r the right position of the dirty region 14997 * @param b the bottom position of the dirty region 14998 */ 14999 public void invalidate(int l, int t, int r, int b) { 15000 final int scrollX = mScrollX; 15001 final int scrollY = mScrollY; 15002 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 15003 } 15004 15005 /** 15006 * Invalidate the whole view. If the view is visible, 15007 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 15008 * the future. 15009 * <p> 15010 * This must be called from a UI thread. To call from a non-UI thread, call 15011 * {@link #postInvalidate()}. 15012 */ 15013 public void invalidate() { 15014 invalidate(true); 15015 } 15016 15017 /** 15018 * This is where the invalidate() work actually happens. A full invalidate() 15019 * causes the drawing cache to be invalidated, but this function can be 15020 * called with invalidateCache set to false to skip that invalidation step 15021 * for cases that do not need it (for example, a component that remains at 15022 * the same dimensions with the same content). 15023 * 15024 * @param invalidateCache Whether the drawing cache for this view should be 15025 * invalidated as well. This is usually true for a full 15026 * invalidate, but may be set to false if the View's contents or 15027 * dimensions have not changed. 15028 * @hide 15029 */ 15030 public void invalidate(boolean invalidateCache) { 15031 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 15032 } 15033 15034 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 15035 boolean fullInvalidate) { 15036 if (mGhostView != null) { 15037 mGhostView.invalidate(true); 15038 return; 15039 } 15040 15041 if (skipInvalidate()) { 15042 return; 15043 } 15044 15045 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 15046 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 15047 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 15048 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 15049 if (fullInvalidate) { 15050 mLastIsOpaque = isOpaque(); 15051 mPrivateFlags &= ~PFLAG_DRAWN; 15052 } 15053 15054 mPrivateFlags |= PFLAG_DIRTY; 15055 15056 if (invalidateCache) { 15057 mPrivateFlags |= PFLAG_INVALIDATED; 15058 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 15059 } 15060 15061 // Propagate the damage rectangle to the parent view. 15062 final AttachInfo ai = mAttachInfo; 15063 final ViewParent p = mParent; 15064 if (p != null && ai != null && l < r && t < b) { 15065 final Rect damage = ai.mTmpInvalRect; 15066 damage.set(l, t, r, b); 15067 p.invalidateChild(this, damage); 15068 } 15069 15070 // Damage the entire projection receiver, if necessary. 15071 if (mBackground != null && mBackground.isProjected()) { 15072 final View receiver = getProjectionReceiver(); 15073 if (receiver != null) { 15074 receiver.damageInParent(); 15075 } 15076 } 15077 } 15078 } 15079 15080 /** 15081 * @return this view's projection receiver, or {@code null} if none exists 15082 */ 15083 private View getProjectionReceiver() { 15084 ViewParent p = getParent(); 15085 while (p != null && p instanceof View) { 15086 final View v = (View) p; 15087 if (v.isProjectionReceiver()) { 15088 return v; 15089 } 15090 p = p.getParent(); 15091 } 15092 15093 return null; 15094 } 15095 15096 /** 15097 * @return whether the view is a projection receiver 15098 */ 15099 private boolean isProjectionReceiver() { 15100 return mBackground != null; 15101 } 15102 15103 /** 15104 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 15105 * set any flags or handle all of the cases handled by the default invalidation methods. 15106 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 15107 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 15108 * walk up the hierarchy, transforming the dirty rect as necessary. 15109 * 15110 * The method also handles normal invalidation logic if display list properties are not 15111 * being used in this view. The invalidateParent and forceRedraw flags are used by that 15112 * backup approach, to handle these cases used in the various property-setting methods. 15113 * 15114 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 15115 * are not being used in this view 15116 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 15117 * list properties are not being used in this view 15118 */ 15119 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 15120 if (!isHardwareAccelerated() 15121 || !mRenderNode.isValid() 15122 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 15123 if (invalidateParent) { 15124 invalidateParentCaches(); 15125 } 15126 if (forceRedraw) { 15127 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 15128 } 15129 invalidate(false); 15130 } else { 15131 damageInParent(); 15132 } 15133 } 15134 15135 /** 15136 * Tells the parent view to damage this view's bounds. 15137 * 15138 * @hide 15139 */ 15140 protected void damageInParent() { 15141 if (mParent != null && mAttachInfo != null) { 15142 mParent.onDescendantInvalidated(this, this); 15143 } 15144 } 15145 15146 /** 15147 * Utility method to transform a given Rect by the current matrix of this view. 15148 */ 15149 void transformRect(final Rect rect) { 15150 if (!getMatrix().isIdentity()) { 15151 RectF boundingRect = mAttachInfo.mTmpTransformRect; 15152 boundingRect.set(rect); 15153 getMatrix().mapRect(boundingRect); 15154 rect.set((int) Math.floor(boundingRect.left), 15155 (int) Math.floor(boundingRect.top), 15156 (int) Math.ceil(boundingRect.right), 15157 (int) Math.ceil(boundingRect.bottom)); 15158 } 15159 } 15160 15161 /** 15162 * Used to indicate that the parent of this view should clear its caches. This functionality 15163 * is used to force the parent to rebuild its display list (when hardware-accelerated), 15164 * which is necessary when various parent-managed properties of the view change, such as 15165 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 15166 * clears the parent caches and does not causes an invalidate event. 15167 * 15168 * @hide 15169 */ 15170 protected void invalidateParentCaches() { 15171 if (mParent instanceof View) { 15172 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 15173 } 15174 } 15175 15176 /** 15177 * Used to indicate that the parent of this view should be invalidated. This functionality 15178 * is used to force the parent to rebuild its display list (when hardware-accelerated), 15179 * which is necessary when various parent-managed properties of the view change, such as 15180 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 15181 * an invalidation event to the parent. 15182 * 15183 * @hide 15184 */ 15185 protected void invalidateParentIfNeeded() { 15186 if (isHardwareAccelerated() && mParent instanceof View) { 15187 ((View) mParent).invalidate(true); 15188 } 15189 } 15190 15191 /** 15192 * @hide 15193 */ 15194 protected void invalidateParentIfNeededAndWasQuickRejected() { 15195 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 15196 // View was rejected last time it was drawn by its parent; this may have changed 15197 invalidateParentIfNeeded(); 15198 } 15199 } 15200 15201 /** 15202 * Indicates whether this View is opaque. An opaque View guarantees that it will 15203 * draw all the pixels overlapping its bounds using a fully opaque color. 15204 * 15205 * Subclasses of View should override this method whenever possible to indicate 15206 * whether an instance is opaque. Opaque Views are treated in a special way by 15207 * the View hierarchy, possibly allowing it to perform optimizations during 15208 * invalidate/draw passes. 15209 * 15210 * @return True if this View is guaranteed to be fully opaque, false otherwise. 15211 */ 15212 @ViewDebug.ExportedProperty(category = "drawing") 15213 public boolean isOpaque() { 15214 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 15215 getFinalAlpha() >= 1.0f; 15216 } 15217 15218 /** 15219 * @hide 15220 */ 15221 protected void computeOpaqueFlags() { 15222 // Opaque if: 15223 // - Has a background 15224 // - Background is opaque 15225 // - Doesn't have scrollbars or scrollbars overlay 15226 15227 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 15228 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 15229 } else { 15230 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 15231 } 15232 15233 final int flags = mViewFlags; 15234 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 15235 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 15236 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 15237 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 15238 } else { 15239 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 15240 } 15241 } 15242 15243 /** 15244 * @hide 15245 */ 15246 protected boolean hasOpaqueScrollbars() { 15247 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 15248 } 15249 15250 /** 15251 * @return A handler associated with the thread running the View. This 15252 * handler can be used to pump events in the UI events queue. 15253 */ 15254 public Handler getHandler() { 15255 final AttachInfo attachInfo = mAttachInfo; 15256 if (attachInfo != null) { 15257 return attachInfo.mHandler; 15258 } 15259 return null; 15260 } 15261 15262 /** 15263 * Returns the queue of runnable for this view. 15264 * 15265 * @return the queue of runnables for this view 15266 */ 15267 private HandlerActionQueue getRunQueue() { 15268 if (mRunQueue == null) { 15269 mRunQueue = new HandlerActionQueue(); 15270 } 15271 return mRunQueue; 15272 } 15273 15274 /** 15275 * Gets the view root associated with the View. 15276 * @return The view root, or null if none. 15277 * @hide 15278 */ 15279 public ViewRootImpl getViewRootImpl() { 15280 if (mAttachInfo != null) { 15281 return mAttachInfo.mViewRootImpl; 15282 } 15283 return null; 15284 } 15285 15286 /** 15287 * @hide 15288 */ 15289 public ThreadedRenderer getThreadedRenderer() { 15290 return mAttachInfo != null ? mAttachInfo.mThreadedRenderer : null; 15291 } 15292 15293 /** 15294 * <p>Causes the Runnable to be added to the message queue. 15295 * The runnable will be run on the user interface thread.</p> 15296 * 15297 * @param action The Runnable that will be executed. 15298 * 15299 * @return Returns true if the Runnable was successfully placed in to the 15300 * message queue. Returns false on failure, usually because the 15301 * looper processing the message queue is exiting. 15302 * 15303 * @see #postDelayed 15304 * @see #removeCallbacks 15305 */ 15306 public boolean post(Runnable action) { 15307 final AttachInfo attachInfo = mAttachInfo; 15308 if (attachInfo != null) { 15309 return attachInfo.mHandler.post(action); 15310 } 15311 15312 // Postpone the runnable until we know on which thread it needs to run. 15313 // Assume that the runnable will be successfully placed after attach. 15314 getRunQueue().post(action); 15315 return true; 15316 } 15317 15318 /** 15319 * <p>Causes the Runnable to be added to the message queue, to be run 15320 * after the specified amount of time elapses. 15321 * The runnable will be run on the user interface thread.</p> 15322 * 15323 * @param action The Runnable that will be executed. 15324 * @param delayMillis The delay (in milliseconds) until the Runnable 15325 * will be executed. 15326 * 15327 * @return true if the Runnable was successfully placed in to the 15328 * message queue. Returns false on failure, usually because the 15329 * looper processing the message queue is exiting. Note that a 15330 * result of true does not mean the Runnable will be processed -- 15331 * if the looper is quit before the delivery time of the message 15332 * occurs then the message will be dropped. 15333 * 15334 * @see #post 15335 * @see #removeCallbacks 15336 */ 15337 public boolean postDelayed(Runnable action, long delayMillis) { 15338 final AttachInfo attachInfo = mAttachInfo; 15339 if (attachInfo != null) { 15340 return attachInfo.mHandler.postDelayed(action, delayMillis); 15341 } 15342 15343 // Postpone the runnable until we know on which thread it needs to run. 15344 // Assume that the runnable will be successfully placed after attach. 15345 getRunQueue().postDelayed(action, delayMillis); 15346 return true; 15347 } 15348 15349 /** 15350 * <p>Causes the Runnable to execute on the next animation time step. 15351 * The runnable will be run on the user interface thread.</p> 15352 * 15353 * @param action The Runnable that will be executed. 15354 * 15355 * @see #postOnAnimationDelayed 15356 * @see #removeCallbacks 15357 */ 15358 public void postOnAnimation(Runnable action) { 15359 final AttachInfo attachInfo = mAttachInfo; 15360 if (attachInfo != null) { 15361 attachInfo.mViewRootImpl.mChoreographer.postCallback( 15362 Choreographer.CALLBACK_ANIMATION, action, null); 15363 } else { 15364 // Postpone the runnable until we know 15365 // on which thread it needs to run. 15366 getRunQueue().post(action); 15367 } 15368 } 15369 15370 /** 15371 * <p>Causes the Runnable to execute on the next animation time step, 15372 * after the specified amount of time elapses. 15373 * The runnable will be run on the user interface thread.</p> 15374 * 15375 * @param action The Runnable that will be executed. 15376 * @param delayMillis The delay (in milliseconds) until the Runnable 15377 * will be executed. 15378 * 15379 * @see #postOnAnimation 15380 * @see #removeCallbacks 15381 */ 15382 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 15383 final AttachInfo attachInfo = mAttachInfo; 15384 if (attachInfo != null) { 15385 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15386 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 15387 } else { 15388 // Postpone the runnable until we know 15389 // on which thread it needs to run. 15390 getRunQueue().postDelayed(action, delayMillis); 15391 } 15392 } 15393 15394 /** 15395 * <p>Removes the specified Runnable from the message queue.</p> 15396 * 15397 * @param action The Runnable to remove from the message handling queue 15398 * 15399 * @return true if this view could ask the Handler to remove the Runnable, 15400 * false otherwise. When the returned value is true, the Runnable 15401 * may or may not have been actually removed from the message queue 15402 * (for instance, if the Runnable was not in the queue already.) 15403 * 15404 * @see #post 15405 * @see #postDelayed 15406 * @see #postOnAnimation 15407 * @see #postOnAnimationDelayed 15408 */ 15409 public boolean removeCallbacks(Runnable action) { 15410 if (action != null) { 15411 final AttachInfo attachInfo = mAttachInfo; 15412 if (attachInfo != null) { 15413 attachInfo.mHandler.removeCallbacks(action); 15414 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15415 Choreographer.CALLBACK_ANIMATION, action, null); 15416 } 15417 getRunQueue().removeCallbacks(action); 15418 } 15419 return true; 15420 } 15421 15422 /** 15423 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 15424 * Use this to invalidate the View from a non-UI thread.</p> 15425 * 15426 * <p>This method can be invoked from outside of the UI thread 15427 * only when this View is attached to a window.</p> 15428 * 15429 * @see #invalidate() 15430 * @see #postInvalidateDelayed(long) 15431 */ 15432 public void postInvalidate() { 15433 postInvalidateDelayed(0); 15434 } 15435 15436 /** 15437 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 15438 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 15439 * 15440 * <p>This method can be invoked from outside of the UI thread 15441 * only when this View is attached to a window.</p> 15442 * 15443 * @param left The left coordinate of the rectangle to invalidate. 15444 * @param top The top coordinate of the rectangle to invalidate. 15445 * @param right The right coordinate of the rectangle to invalidate. 15446 * @param bottom The bottom coordinate of the rectangle to invalidate. 15447 * 15448 * @see #invalidate(int, int, int, int) 15449 * @see #invalidate(Rect) 15450 * @see #postInvalidateDelayed(long, int, int, int, int) 15451 */ 15452 public void postInvalidate(int left, int top, int right, int bottom) { 15453 postInvalidateDelayed(0, left, top, right, bottom); 15454 } 15455 15456 /** 15457 * <p>Cause an invalidate to happen on a subsequent cycle through the event 15458 * loop. Waits for the specified amount of time.</p> 15459 * 15460 * <p>This method can be invoked from outside of the UI thread 15461 * only when this View is attached to a window.</p> 15462 * 15463 * @param delayMilliseconds the duration in milliseconds to delay the 15464 * invalidation by 15465 * 15466 * @see #invalidate() 15467 * @see #postInvalidate() 15468 */ 15469 public void postInvalidateDelayed(long delayMilliseconds) { 15470 // We try only with the AttachInfo because there's no point in invalidating 15471 // if we are not attached to our window 15472 final AttachInfo attachInfo = mAttachInfo; 15473 if (attachInfo != null) { 15474 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 15475 } 15476 } 15477 15478 /** 15479 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 15480 * through the event loop. Waits for the specified amount of time.</p> 15481 * 15482 * <p>This method can be invoked from outside of the UI thread 15483 * only when this View is attached to a window.</p> 15484 * 15485 * @param delayMilliseconds the duration in milliseconds to delay the 15486 * invalidation by 15487 * @param left The left coordinate of the rectangle to invalidate. 15488 * @param top The top coordinate of the rectangle to invalidate. 15489 * @param right The right coordinate of the rectangle to invalidate. 15490 * @param bottom The bottom coordinate of the rectangle to invalidate. 15491 * 15492 * @see #invalidate(int, int, int, int) 15493 * @see #invalidate(Rect) 15494 * @see #postInvalidate(int, int, int, int) 15495 */ 15496 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 15497 int right, int bottom) { 15498 15499 // We try only with the AttachInfo because there's no point in invalidating 15500 // if we are not attached to our window 15501 final AttachInfo attachInfo = mAttachInfo; 15502 if (attachInfo != null) { 15503 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 15504 info.target = this; 15505 info.left = left; 15506 info.top = top; 15507 info.right = right; 15508 info.bottom = bottom; 15509 15510 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 15511 } 15512 } 15513 15514 /** 15515 * <p>Cause an invalidate to happen on the next animation time step, typically the 15516 * next display frame.</p> 15517 * 15518 * <p>This method can be invoked from outside of the UI thread 15519 * only when this View is attached to a window.</p> 15520 * 15521 * @see #invalidate() 15522 */ 15523 public void postInvalidateOnAnimation() { 15524 // We try only with the AttachInfo because there's no point in invalidating 15525 // if we are not attached to our window 15526 final AttachInfo attachInfo = mAttachInfo; 15527 if (attachInfo != null) { 15528 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 15529 } 15530 } 15531 15532 /** 15533 * <p>Cause an invalidate of the specified area to happen on the next animation 15534 * time step, typically the next display frame.</p> 15535 * 15536 * <p>This method can be invoked from outside of the UI thread 15537 * only when this View is attached to a window.</p> 15538 * 15539 * @param left The left coordinate of the rectangle to invalidate. 15540 * @param top The top coordinate of the rectangle to invalidate. 15541 * @param right The right coordinate of the rectangle to invalidate. 15542 * @param bottom The bottom coordinate of the rectangle to invalidate. 15543 * 15544 * @see #invalidate(int, int, int, int) 15545 * @see #invalidate(Rect) 15546 */ 15547 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 15548 // We try only with the AttachInfo because there's no point in invalidating 15549 // if we are not attached to our window 15550 final AttachInfo attachInfo = mAttachInfo; 15551 if (attachInfo != null) { 15552 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 15553 info.target = this; 15554 info.left = left; 15555 info.top = top; 15556 info.right = right; 15557 info.bottom = bottom; 15558 15559 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 15560 } 15561 } 15562 15563 /** 15564 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 15565 * This event is sent at most once every 15566 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 15567 */ 15568 private void postSendViewScrolledAccessibilityEventCallback() { 15569 if (mSendViewScrolledAccessibilityEvent == null) { 15570 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 15571 } 15572 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 15573 mSendViewScrolledAccessibilityEvent.mIsPending = true; 15574 postDelayed(mSendViewScrolledAccessibilityEvent, 15575 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 15576 } 15577 } 15578 15579 /** 15580 * Called by a parent to request that a child update its values for mScrollX 15581 * and mScrollY if necessary. This will typically be done if the child is 15582 * animating a scroll using a {@link android.widget.Scroller Scroller} 15583 * object. 15584 */ 15585 public void computeScroll() { 15586 } 15587 15588 /** 15589 * <p>Indicate whether the horizontal edges are faded when the view is 15590 * scrolled horizontally.</p> 15591 * 15592 * @return true if the horizontal edges should are faded on scroll, false 15593 * otherwise 15594 * 15595 * @see #setHorizontalFadingEdgeEnabled(boolean) 15596 * 15597 * @attr ref android.R.styleable#View_requiresFadingEdge 15598 */ 15599 public boolean isHorizontalFadingEdgeEnabled() { 15600 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 15601 } 15602 15603 /** 15604 * <p>Define whether the horizontal edges should be faded when this view 15605 * is scrolled horizontally.</p> 15606 * 15607 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 15608 * be faded when the view is scrolled 15609 * horizontally 15610 * 15611 * @see #isHorizontalFadingEdgeEnabled() 15612 * 15613 * @attr ref android.R.styleable#View_requiresFadingEdge 15614 */ 15615 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 15616 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 15617 if (horizontalFadingEdgeEnabled) { 15618 initScrollCache(); 15619 } 15620 15621 mViewFlags ^= FADING_EDGE_HORIZONTAL; 15622 } 15623 } 15624 15625 /** 15626 * <p>Indicate whether the vertical edges are faded when the view is 15627 * scrolled horizontally.</p> 15628 * 15629 * @return true if the vertical edges should are faded on scroll, false 15630 * otherwise 15631 * 15632 * @see #setVerticalFadingEdgeEnabled(boolean) 15633 * 15634 * @attr ref android.R.styleable#View_requiresFadingEdge 15635 */ 15636 public boolean isVerticalFadingEdgeEnabled() { 15637 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 15638 } 15639 15640 /** 15641 * <p>Define whether the vertical edges should be faded when this view 15642 * is scrolled vertically.</p> 15643 * 15644 * @param verticalFadingEdgeEnabled true if the vertical edges should 15645 * be faded when the view is scrolled 15646 * vertically 15647 * 15648 * @see #isVerticalFadingEdgeEnabled() 15649 * 15650 * @attr ref android.R.styleable#View_requiresFadingEdge 15651 */ 15652 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 15653 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 15654 if (verticalFadingEdgeEnabled) { 15655 initScrollCache(); 15656 } 15657 15658 mViewFlags ^= FADING_EDGE_VERTICAL; 15659 } 15660 } 15661 15662 /** 15663 * Returns the strength, or intensity, of the top faded edge. The strength is 15664 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15665 * returns 0.0 or 1.0 but no value in between. 15666 * 15667 * Subclasses should override this method to provide a smoother fade transition 15668 * when scrolling occurs. 15669 * 15670 * @return the intensity of the top fade as a float between 0.0f and 1.0f 15671 */ 15672 protected float getTopFadingEdgeStrength() { 15673 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 15674 } 15675 15676 /** 15677 * Returns the strength, or intensity, of the bottom faded edge. The strength is 15678 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15679 * returns 0.0 or 1.0 but no value in between. 15680 * 15681 * Subclasses should override this method to provide a smoother fade transition 15682 * when scrolling occurs. 15683 * 15684 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 15685 */ 15686 protected float getBottomFadingEdgeStrength() { 15687 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 15688 computeVerticalScrollRange() ? 1.0f : 0.0f; 15689 } 15690 15691 /** 15692 * Returns the strength, or intensity, of the left faded edge. The strength is 15693 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15694 * returns 0.0 or 1.0 but no value in between. 15695 * 15696 * Subclasses should override this method to provide a smoother fade transition 15697 * when scrolling occurs. 15698 * 15699 * @return the intensity of the left fade as a float between 0.0f and 1.0f 15700 */ 15701 protected float getLeftFadingEdgeStrength() { 15702 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 15703 } 15704 15705 /** 15706 * Returns the strength, or intensity, of the right faded edge. The strength is 15707 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 15708 * returns 0.0 or 1.0 but no value in between. 15709 * 15710 * Subclasses should override this method to provide a smoother fade transition 15711 * when scrolling occurs. 15712 * 15713 * @return the intensity of the right fade as a float between 0.0f and 1.0f 15714 */ 15715 protected float getRightFadingEdgeStrength() { 15716 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 15717 computeHorizontalScrollRange() ? 1.0f : 0.0f; 15718 } 15719 15720 /** 15721 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 15722 * scrollbar is not drawn by default.</p> 15723 * 15724 * @return true if the horizontal scrollbar should be painted, false 15725 * otherwise 15726 * 15727 * @see #setHorizontalScrollBarEnabled(boolean) 15728 */ 15729 public boolean isHorizontalScrollBarEnabled() { 15730 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 15731 } 15732 15733 /** 15734 * <p>Define whether the horizontal scrollbar should be drawn or not. The 15735 * scrollbar is not drawn by default.</p> 15736 * 15737 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 15738 * be painted 15739 * 15740 * @see #isHorizontalScrollBarEnabled() 15741 */ 15742 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 15743 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 15744 mViewFlags ^= SCROLLBARS_HORIZONTAL; 15745 computeOpaqueFlags(); 15746 resolvePadding(); 15747 } 15748 } 15749 15750 /** 15751 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 15752 * scrollbar is not drawn by default.</p> 15753 * 15754 * @return true if the vertical scrollbar should be painted, false 15755 * otherwise 15756 * 15757 * @see #setVerticalScrollBarEnabled(boolean) 15758 */ 15759 public boolean isVerticalScrollBarEnabled() { 15760 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 15761 } 15762 15763 /** 15764 * <p>Define whether the vertical scrollbar should be drawn or not. The 15765 * scrollbar is not drawn by default.</p> 15766 * 15767 * @param verticalScrollBarEnabled true if the vertical scrollbar should 15768 * be painted 15769 * 15770 * @see #isVerticalScrollBarEnabled() 15771 */ 15772 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 15773 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 15774 mViewFlags ^= SCROLLBARS_VERTICAL; 15775 computeOpaqueFlags(); 15776 resolvePadding(); 15777 } 15778 } 15779 15780 /** 15781 * @hide 15782 */ 15783 protected void recomputePadding() { 15784 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 15785 } 15786 15787 /** 15788 * Define whether scrollbars will fade when the view is not scrolling. 15789 * 15790 * @param fadeScrollbars whether to enable fading 15791 * 15792 * @attr ref android.R.styleable#View_fadeScrollbars 15793 */ 15794 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 15795 initScrollCache(); 15796 final ScrollabilityCache scrollabilityCache = mScrollCache; 15797 scrollabilityCache.fadeScrollBars = fadeScrollbars; 15798 if (fadeScrollbars) { 15799 scrollabilityCache.state = ScrollabilityCache.OFF; 15800 } else { 15801 scrollabilityCache.state = ScrollabilityCache.ON; 15802 } 15803 } 15804 15805 /** 15806 * 15807 * Returns true if scrollbars will fade when this view is not scrolling 15808 * 15809 * @return true if scrollbar fading is enabled 15810 * 15811 * @attr ref android.R.styleable#View_fadeScrollbars 15812 */ 15813 public boolean isScrollbarFadingEnabled() { 15814 return mScrollCache != null && mScrollCache.fadeScrollBars; 15815 } 15816 15817 /** 15818 * 15819 * Returns the delay before scrollbars fade. 15820 * 15821 * @return the delay before scrollbars fade 15822 * 15823 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 15824 */ 15825 public int getScrollBarDefaultDelayBeforeFade() { 15826 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 15827 mScrollCache.scrollBarDefaultDelayBeforeFade; 15828 } 15829 15830 /** 15831 * Define the delay before scrollbars fade. 15832 * 15833 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 15834 * 15835 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 15836 */ 15837 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 15838 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 15839 } 15840 15841 /** 15842 * 15843 * Returns the scrollbar fade duration. 15844 * 15845 * @return the scrollbar fade duration, in milliseconds 15846 * 15847 * @attr ref android.R.styleable#View_scrollbarFadeDuration 15848 */ 15849 public int getScrollBarFadeDuration() { 15850 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 15851 mScrollCache.scrollBarFadeDuration; 15852 } 15853 15854 /** 15855 * Define the scrollbar fade duration. 15856 * 15857 * @param scrollBarFadeDuration - the scrollbar fade duration, in milliseconds 15858 * 15859 * @attr ref android.R.styleable#View_scrollbarFadeDuration 15860 */ 15861 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 15862 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 15863 } 15864 15865 /** 15866 * 15867 * Returns the scrollbar size. 15868 * 15869 * @return the scrollbar size 15870 * 15871 * @attr ref android.R.styleable#View_scrollbarSize 15872 */ 15873 public int getScrollBarSize() { 15874 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 15875 mScrollCache.scrollBarSize; 15876 } 15877 15878 /** 15879 * Define the scrollbar size. 15880 * 15881 * @param scrollBarSize - the scrollbar size 15882 * 15883 * @attr ref android.R.styleable#View_scrollbarSize 15884 */ 15885 public void setScrollBarSize(int scrollBarSize) { 15886 getScrollCache().scrollBarSize = scrollBarSize; 15887 } 15888 15889 /** 15890 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 15891 * inset. When inset, they add to the padding of the view. And the scrollbars 15892 * can be drawn inside the padding area or on the edge of the view. For example, 15893 * if a view has a background drawable and you want to draw the scrollbars 15894 * inside the padding specified by the drawable, you can use 15895 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 15896 * appear at the edge of the view, ignoring the padding, then you can use 15897 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 15898 * @param style the style of the scrollbars. Should be one of 15899 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 15900 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 15901 * @see #SCROLLBARS_INSIDE_OVERLAY 15902 * @see #SCROLLBARS_INSIDE_INSET 15903 * @see #SCROLLBARS_OUTSIDE_OVERLAY 15904 * @see #SCROLLBARS_OUTSIDE_INSET 15905 * 15906 * @attr ref android.R.styleable#View_scrollbarStyle 15907 */ 15908 public void setScrollBarStyle(@ScrollBarStyle int style) { 15909 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 15910 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 15911 computeOpaqueFlags(); 15912 resolvePadding(); 15913 } 15914 } 15915 15916 /** 15917 * <p>Returns the current scrollbar style.</p> 15918 * @return the current scrollbar style 15919 * @see #SCROLLBARS_INSIDE_OVERLAY 15920 * @see #SCROLLBARS_INSIDE_INSET 15921 * @see #SCROLLBARS_OUTSIDE_OVERLAY 15922 * @see #SCROLLBARS_OUTSIDE_INSET 15923 * 15924 * @attr ref android.R.styleable#View_scrollbarStyle 15925 */ 15926 @ViewDebug.ExportedProperty(mapping = { 15927 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 15928 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 15929 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 15930 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 15931 }) 15932 @ScrollBarStyle 15933 public int getScrollBarStyle() { 15934 return mViewFlags & SCROLLBARS_STYLE_MASK; 15935 } 15936 15937 /** 15938 * <p>Compute the horizontal range that the horizontal scrollbar 15939 * represents.</p> 15940 * 15941 * <p>The range is expressed in arbitrary units that must be the same as the 15942 * units used by {@link #computeHorizontalScrollExtent()} and 15943 * {@link #computeHorizontalScrollOffset()}.</p> 15944 * 15945 * <p>The default range is the drawing width of this view.</p> 15946 * 15947 * @return the total horizontal range represented by the horizontal 15948 * scrollbar 15949 * 15950 * @see #computeHorizontalScrollExtent() 15951 * @see #computeHorizontalScrollOffset() 15952 * @see android.widget.ScrollBarDrawable 15953 */ 15954 protected int computeHorizontalScrollRange() { 15955 return getWidth(); 15956 } 15957 15958 /** 15959 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 15960 * within the horizontal range. This value is used to compute the position 15961 * of the thumb within the scrollbar's track.</p> 15962 * 15963 * <p>The range is expressed in arbitrary units that must be the same as the 15964 * units used by {@link #computeHorizontalScrollRange()} and 15965 * {@link #computeHorizontalScrollExtent()}.</p> 15966 * 15967 * <p>The default offset is the scroll offset of this view.</p> 15968 * 15969 * @return the horizontal offset of the scrollbar's thumb 15970 * 15971 * @see #computeHorizontalScrollRange() 15972 * @see #computeHorizontalScrollExtent() 15973 * @see android.widget.ScrollBarDrawable 15974 */ 15975 protected int computeHorizontalScrollOffset() { 15976 return mScrollX; 15977 } 15978 15979 /** 15980 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 15981 * within the horizontal range. This value is used to compute the length 15982 * of the thumb within the scrollbar's track.</p> 15983 * 15984 * <p>The range is expressed in arbitrary units that must be the same as the 15985 * units used by {@link #computeHorizontalScrollRange()} and 15986 * {@link #computeHorizontalScrollOffset()}.</p> 15987 * 15988 * <p>The default extent is the drawing width of this view.</p> 15989 * 15990 * @return the horizontal extent of the scrollbar's thumb 15991 * 15992 * @see #computeHorizontalScrollRange() 15993 * @see #computeHorizontalScrollOffset() 15994 * @see android.widget.ScrollBarDrawable 15995 */ 15996 protected int computeHorizontalScrollExtent() { 15997 return getWidth(); 15998 } 15999 16000 /** 16001 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 16002 * 16003 * <p>The range is expressed in arbitrary units that must be the same as the 16004 * units used by {@link #computeVerticalScrollExtent()} and 16005 * {@link #computeVerticalScrollOffset()}.</p> 16006 * 16007 * @return the total vertical range represented by the vertical scrollbar 16008 * 16009 * <p>The default range is the drawing height of this view.</p> 16010 * 16011 * @see #computeVerticalScrollExtent() 16012 * @see #computeVerticalScrollOffset() 16013 * @see android.widget.ScrollBarDrawable 16014 */ 16015 protected int computeVerticalScrollRange() { 16016 return getHeight(); 16017 } 16018 16019 /** 16020 * <p>Compute the vertical offset of the vertical scrollbar's thumb 16021 * within the horizontal range. This value is used to compute the position 16022 * of the thumb within the scrollbar's track.</p> 16023 * 16024 * <p>The range is expressed in arbitrary units that must be the same as the 16025 * units used by {@link #computeVerticalScrollRange()} and 16026 * {@link #computeVerticalScrollExtent()}.</p> 16027 * 16028 * <p>The default offset is the scroll offset of this view.</p> 16029 * 16030 * @return the vertical offset of the scrollbar's thumb 16031 * 16032 * @see #computeVerticalScrollRange() 16033 * @see #computeVerticalScrollExtent() 16034 * @see android.widget.ScrollBarDrawable 16035 */ 16036 protected int computeVerticalScrollOffset() { 16037 return mScrollY; 16038 } 16039 16040 /** 16041 * <p>Compute the vertical extent of the vertical scrollbar's thumb 16042 * within the vertical range. This value is used to compute the length 16043 * of the thumb within the scrollbar's track.</p> 16044 * 16045 * <p>The range is expressed in arbitrary units that must be the same as the 16046 * units used by {@link #computeVerticalScrollRange()} and 16047 * {@link #computeVerticalScrollOffset()}.</p> 16048 * 16049 * <p>The default extent is the drawing height of this view.</p> 16050 * 16051 * @return the vertical extent of the scrollbar's thumb 16052 * 16053 * @see #computeVerticalScrollRange() 16054 * @see #computeVerticalScrollOffset() 16055 * @see android.widget.ScrollBarDrawable 16056 */ 16057 protected int computeVerticalScrollExtent() { 16058 return getHeight(); 16059 } 16060 16061 /** 16062 * Check if this view can be scrolled horizontally in a certain direction. 16063 * 16064 * @param direction Negative to check scrolling left, positive to check scrolling right. 16065 * @return true if this view can be scrolled in the specified direction, false otherwise. 16066 */ 16067 public boolean canScrollHorizontally(int direction) { 16068 final int offset = computeHorizontalScrollOffset(); 16069 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 16070 if (range == 0) return false; 16071 if (direction < 0) { 16072 return offset > 0; 16073 } else { 16074 return offset < range - 1; 16075 } 16076 } 16077 16078 /** 16079 * Check if this view can be scrolled vertically in a certain direction. 16080 * 16081 * @param direction Negative to check scrolling up, positive to check scrolling down. 16082 * @return true if this view can be scrolled in the specified direction, false otherwise. 16083 */ 16084 public boolean canScrollVertically(int direction) { 16085 final int offset = computeVerticalScrollOffset(); 16086 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 16087 if (range == 0) return false; 16088 if (direction < 0) { 16089 return offset > 0; 16090 } else { 16091 return offset < range - 1; 16092 } 16093 } 16094 16095 void getScrollIndicatorBounds(@NonNull Rect out) { 16096 out.left = mScrollX; 16097 out.right = mScrollX + mRight - mLeft; 16098 out.top = mScrollY; 16099 out.bottom = mScrollY + mBottom - mTop; 16100 } 16101 16102 private void onDrawScrollIndicators(Canvas c) { 16103 if ((mPrivateFlags3 & SCROLL_INDICATORS_PFLAG3_MASK) == 0) { 16104 // No scroll indicators enabled. 16105 return; 16106 } 16107 16108 final Drawable dr = mScrollIndicatorDrawable; 16109 if (dr == null) { 16110 // Scroll indicators aren't supported here. 16111 return; 16112 } 16113 16114 final int h = dr.getIntrinsicHeight(); 16115 final int w = dr.getIntrinsicWidth(); 16116 final Rect rect = mAttachInfo.mTmpInvalRect; 16117 getScrollIndicatorBounds(rect); 16118 16119 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_TOP) != 0) { 16120 final boolean canScrollUp = canScrollVertically(-1); 16121 if (canScrollUp) { 16122 dr.setBounds(rect.left, rect.top, rect.right, rect.top + h); 16123 dr.draw(c); 16124 } 16125 } 16126 16127 if ((mPrivateFlags3 & PFLAG3_SCROLL_INDICATOR_BOTTOM) != 0) { 16128 final boolean canScrollDown = canScrollVertically(1); 16129 if (canScrollDown) { 16130 dr.setBounds(rect.left, rect.bottom - h, rect.right, rect.bottom); 16131 dr.draw(c); 16132 } 16133 } 16134 16135 final int leftRtl; 16136 final int rightRtl; 16137 if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 16138 leftRtl = PFLAG3_SCROLL_INDICATOR_END; 16139 rightRtl = PFLAG3_SCROLL_INDICATOR_START; 16140 } else { 16141 leftRtl = PFLAG3_SCROLL_INDICATOR_START; 16142 rightRtl = PFLAG3_SCROLL_INDICATOR_END; 16143 } 16144 16145 final int leftMask = PFLAG3_SCROLL_INDICATOR_LEFT | leftRtl; 16146 if ((mPrivateFlags3 & leftMask) != 0) { 16147 final boolean canScrollLeft = canScrollHorizontally(-1); 16148 if (canScrollLeft) { 16149 dr.setBounds(rect.left, rect.top, rect.left + w, rect.bottom); 16150 dr.draw(c); 16151 } 16152 } 16153 16154 final int rightMask = PFLAG3_SCROLL_INDICATOR_RIGHT | rightRtl; 16155 if ((mPrivateFlags3 & rightMask) != 0) { 16156 final boolean canScrollRight = canScrollHorizontally(1); 16157 if (canScrollRight) { 16158 dr.setBounds(rect.right - w, rect.top, rect.right, rect.bottom); 16159 dr.draw(c); 16160 } 16161 } 16162 } 16163 16164 private void getHorizontalScrollBarBounds(@Nullable Rect drawBounds, 16165 @Nullable Rect touchBounds) { 16166 final Rect bounds = drawBounds != null ? drawBounds : touchBounds; 16167 if (bounds == null) { 16168 return; 16169 } 16170 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 16171 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 16172 && !isVerticalScrollBarHidden(); 16173 final int size = getHorizontalScrollbarHeight(); 16174 final int verticalScrollBarGap = drawVerticalScrollBar ? 16175 getVerticalScrollbarWidth() : 0; 16176 final int width = mRight - mLeft; 16177 final int height = mBottom - mTop; 16178 bounds.top = mScrollY + height - size - (mUserPaddingBottom & inside); 16179 bounds.left = mScrollX + (mPaddingLeft & inside); 16180 bounds.right = mScrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 16181 bounds.bottom = bounds.top + size; 16182 16183 if (touchBounds == null) { 16184 return; 16185 } 16186 if (touchBounds != bounds) { 16187 touchBounds.set(bounds); 16188 } 16189 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget; 16190 if (touchBounds.height() < minTouchTarget) { 16191 final int adjust = (minTouchTarget - touchBounds.height()) / 2; 16192 touchBounds.bottom = Math.min(touchBounds.bottom + adjust, mScrollY + height); 16193 touchBounds.top = touchBounds.bottom - minTouchTarget; 16194 } 16195 if (touchBounds.width() < minTouchTarget) { 16196 final int adjust = (minTouchTarget - touchBounds.width()) / 2; 16197 touchBounds.left -= adjust; 16198 touchBounds.right = touchBounds.left + minTouchTarget; 16199 } 16200 } 16201 16202 private void getVerticalScrollBarBounds(@Nullable Rect bounds, @Nullable Rect touchBounds) { 16203 if (mRoundScrollbarRenderer == null) { 16204 getStraightVerticalScrollBarBounds(bounds, touchBounds); 16205 } else { 16206 getRoundVerticalScrollBarBounds(bounds != null ? bounds : touchBounds); 16207 } 16208 } 16209 16210 private void getRoundVerticalScrollBarBounds(Rect bounds) { 16211 final int width = mRight - mLeft; 16212 final int height = mBottom - mTop; 16213 // Do not take padding into account as we always want the scrollbars 16214 // to hug the screen for round wearable devices. 16215 bounds.left = mScrollX; 16216 bounds.top = mScrollY; 16217 bounds.right = bounds.left + width; 16218 bounds.bottom = mScrollY + height; 16219 } 16220 16221 private void getStraightVerticalScrollBarBounds(@Nullable Rect drawBounds, 16222 @Nullable Rect touchBounds) { 16223 final Rect bounds = drawBounds != null ? drawBounds : touchBounds; 16224 if (bounds == null) { 16225 return; 16226 } 16227 final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 16228 final int size = getVerticalScrollbarWidth(); 16229 int verticalScrollbarPosition = mVerticalScrollbarPosition; 16230 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 16231 verticalScrollbarPosition = isLayoutRtl() ? 16232 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 16233 } 16234 final int width = mRight - mLeft; 16235 final int height = mBottom - mTop; 16236 switch (verticalScrollbarPosition) { 16237 default: 16238 case SCROLLBAR_POSITION_RIGHT: 16239 bounds.left = mScrollX + width - size - (mUserPaddingRight & inside); 16240 break; 16241 case SCROLLBAR_POSITION_LEFT: 16242 bounds.left = mScrollX + (mUserPaddingLeft & inside); 16243 break; 16244 } 16245 bounds.top = mScrollY + (mPaddingTop & inside); 16246 bounds.right = bounds.left + size; 16247 bounds.bottom = mScrollY + height - (mUserPaddingBottom & inside); 16248 16249 if (touchBounds == null) { 16250 return; 16251 } 16252 if (touchBounds != bounds) { 16253 touchBounds.set(bounds); 16254 } 16255 final int minTouchTarget = mScrollCache.scrollBarMinTouchTarget; 16256 if (touchBounds.width() < minTouchTarget) { 16257 final int adjust = (minTouchTarget - touchBounds.width()) / 2; 16258 if (verticalScrollbarPosition == SCROLLBAR_POSITION_RIGHT) { 16259 touchBounds.right = Math.min(touchBounds.right + adjust, mScrollX + width); 16260 touchBounds.left = touchBounds.right - minTouchTarget; 16261 } else { 16262 touchBounds.left = Math.max(touchBounds.left + adjust, mScrollX); 16263 touchBounds.right = touchBounds.left + minTouchTarget; 16264 } 16265 } 16266 if (touchBounds.height() < minTouchTarget) { 16267 final int adjust = (minTouchTarget - touchBounds.height()) / 2; 16268 touchBounds.top -= adjust; 16269 touchBounds.bottom = touchBounds.top + minTouchTarget; 16270 } 16271 } 16272 16273 /** 16274 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 16275 * scrollbars are painted only if they have been awakened first.</p> 16276 * 16277 * @param canvas the canvas on which to draw the scrollbars 16278 * 16279 * @see #awakenScrollBars(int) 16280 */ 16281 protected final void onDrawScrollBars(Canvas canvas) { 16282 // scrollbars are drawn only when the animation is running 16283 final ScrollabilityCache cache = mScrollCache; 16284 16285 if (cache != null) { 16286 16287 int state = cache.state; 16288 16289 if (state == ScrollabilityCache.OFF) { 16290 return; 16291 } 16292 16293 boolean invalidate = false; 16294 16295 if (state == ScrollabilityCache.FADING) { 16296 // We're fading -- get our fade interpolation 16297 if (cache.interpolatorValues == null) { 16298 cache.interpolatorValues = new float[1]; 16299 } 16300 16301 float[] values = cache.interpolatorValues; 16302 16303 // Stops the animation if we're done 16304 if (cache.scrollBarInterpolator.timeToValues(values) == 16305 Interpolator.Result.FREEZE_END) { 16306 cache.state = ScrollabilityCache.OFF; 16307 } else { 16308 cache.scrollBar.mutate().setAlpha(Math.round(values[0])); 16309 } 16310 16311 // This will make the scroll bars inval themselves after 16312 // drawing. We only want this when we're fading so that 16313 // we prevent excessive redraws 16314 invalidate = true; 16315 } else { 16316 // We're just on -- but we may have been fading before so 16317 // reset alpha 16318 cache.scrollBar.mutate().setAlpha(255); 16319 } 16320 16321 final boolean drawHorizontalScrollBar = isHorizontalScrollBarEnabled(); 16322 final boolean drawVerticalScrollBar = isVerticalScrollBarEnabled() 16323 && !isVerticalScrollBarHidden(); 16324 16325 // Fork out the scroll bar drawing for round wearable devices. 16326 if (mRoundScrollbarRenderer != null) { 16327 if (drawVerticalScrollBar) { 16328 final Rect bounds = cache.mScrollBarBounds; 16329 getVerticalScrollBarBounds(bounds, null); 16330 mRoundScrollbarRenderer.drawRoundScrollbars( 16331 canvas, (float) cache.scrollBar.getAlpha() / 255f, bounds); 16332 if (invalidate) { 16333 invalidate(); 16334 } 16335 } 16336 // Do not draw horizontal scroll bars for round wearable devices. 16337 } else if (drawVerticalScrollBar || drawHorizontalScrollBar) { 16338 final ScrollBarDrawable scrollBar = cache.scrollBar; 16339 16340 if (drawHorizontalScrollBar) { 16341 scrollBar.setParameters(computeHorizontalScrollRange(), 16342 computeHorizontalScrollOffset(), 16343 computeHorizontalScrollExtent(), false); 16344 final Rect bounds = cache.mScrollBarBounds; 16345 getHorizontalScrollBarBounds(bounds, null); 16346 onDrawHorizontalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 16347 bounds.right, bounds.bottom); 16348 if (invalidate) { 16349 invalidate(bounds); 16350 } 16351 } 16352 16353 if (drawVerticalScrollBar) { 16354 scrollBar.setParameters(computeVerticalScrollRange(), 16355 computeVerticalScrollOffset(), 16356 computeVerticalScrollExtent(), true); 16357 final Rect bounds = cache.mScrollBarBounds; 16358 getVerticalScrollBarBounds(bounds, null); 16359 onDrawVerticalScrollBar(canvas, scrollBar, bounds.left, bounds.top, 16360 bounds.right, bounds.bottom); 16361 if (invalidate) { 16362 invalidate(bounds); 16363 } 16364 } 16365 } 16366 } 16367 } 16368 16369 /** 16370 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 16371 * FastScroller is visible. 16372 * @return whether to temporarily hide the vertical scrollbar 16373 * @hide 16374 */ 16375 protected boolean isVerticalScrollBarHidden() { 16376 return false; 16377 } 16378 16379 /** 16380 * <p>Draw the horizontal scrollbar if 16381 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 16382 * 16383 * @param canvas the canvas on which to draw the scrollbar 16384 * @param scrollBar the scrollbar's drawable 16385 * 16386 * @see #isHorizontalScrollBarEnabled() 16387 * @see #computeHorizontalScrollRange() 16388 * @see #computeHorizontalScrollExtent() 16389 * @see #computeHorizontalScrollOffset() 16390 * @see android.widget.ScrollBarDrawable 16391 * @hide 16392 */ 16393 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 16394 int l, int t, int r, int b) { 16395 scrollBar.setBounds(l, t, r, b); 16396 scrollBar.draw(canvas); 16397 } 16398 16399 /** 16400 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 16401 * returns true.</p> 16402 * 16403 * @param canvas the canvas on which to draw the scrollbar 16404 * @param scrollBar the scrollbar's drawable 16405 * 16406 * @see #isVerticalScrollBarEnabled() 16407 * @see #computeVerticalScrollRange() 16408 * @see #computeVerticalScrollExtent() 16409 * @see #computeVerticalScrollOffset() 16410 * @see android.widget.ScrollBarDrawable 16411 * @hide 16412 */ 16413 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 16414 int l, int t, int r, int b) { 16415 scrollBar.setBounds(l, t, r, b); 16416 scrollBar.draw(canvas); 16417 } 16418 16419 /** 16420 * Implement this to do your drawing. 16421 * 16422 * @param canvas the canvas on which the background will be drawn 16423 */ 16424 protected void onDraw(Canvas canvas) { 16425 } 16426 16427 /* 16428 * Caller is responsible for calling requestLayout if necessary. 16429 * (This allows addViewInLayout to not request a new layout.) 16430 */ 16431 void assignParent(ViewParent parent) { 16432 if (mParent == null) { 16433 mParent = parent; 16434 } else if (parent == null) { 16435 mParent = null; 16436 } else { 16437 throw new RuntimeException("view " + this + " being added, but" 16438 + " it already has a parent"); 16439 } 16440 } 16441 16442 /** 16443 * This is called when the view is attached to a window. At this point it 16444 * has a Surface and will start drawing. Note that this function is 16445 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 16446 * however it may be called any time before the first onDraw -- including 16447 * before or after {@link #onMeasure(int, int)}. 16448 * 16449 * @see #onDetachedFromWindow() 16450 */ 16451 @CallSuper 16452 protected void onAttachedToWindow() { 16453 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 16454 mParent.requestTransparentRegion(this); 16455 } 16456 16457 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 16458 16459 jumpDrawablesToCurrentState(); 16460 16461 resetSubtreeAccessibilityStateChanged(); 16462 16463 // rebuild, since Outline not maintained while View is detached 16464 rebuildOutline(); 16465 16466 if (isFocused()) { 16467 InputMethodManager imm = InputMethodManager.peekInstance(); 16468 if (imm != null) { 16469 imm.focusIn(this); 16470 } 16471 } 16472 } 16473 16474 /** 16475 * Resolve all RTL related properties. 16476 * 16477 * @return true if resolution of RTL properties has been done 16478 * 16479 * @hide 16480 */ 16481 public boolean resolveRtlPropertiesIfNeeded() { 16482 if (!needRtlPropertiesResolution()) return false; 16483 16484 // Order is important here: LayoutDirection MUST be resolved first 16485 if (!isLayoutDirectionResolved()) { 16486 resolveLayoutDirection(); 16487 resolveLayoutParams(); 16488 } 16489 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 16490 if (!isTextDirectionResolved()) { 16491 resolveTextDirection(); 16492 } 16493 if (!isTextAlignmentResolved()) { 16494 resolveTextAlignment(); 16495 } 16496 // Should resolve Drawables before Padding because we need the layout direction of the 16497 // Drawable to correctly resolve Padding. 16498 if (!areDrawablesResolved()) { 16499 resolveDrawables(); 16500 } 16501 if (!isPaddingResolved()) { 16502 resolvePadding(); 16503 } 16504 onRtlPropertiesChanged(getLayoutDirection()); 16505 return true; 16506 } 16507 16508 /** 16509 * Reset resolution of all RTL related properties. 16510 * 16511 * @hide 16512 */ 16513 public void resetRtlProperties() { 16514 resetResolvedLayoutDirection(); 16515 resetResolvedTextDirection(); 16516 resetResolvedTextAlignment(); 16517 resetResolvedPadding(); 16518 resetResolvedDrawables(); 16519 } 16520 16521 /** 16522 * @see #onScreenStateChanged(int) 16523 */ 16524 void dispatchScreenStateChanged(int screenState) { 16525 onScreenStateChanged(screenState); 16526 } 16527 16528 /** 16529 * This method is called whenever the state of the screen this view is 16530 * attached to changes. A state change will usually occurs when the screen 16531 * turns on or off (whether it happens automatically or the user does it 16532 * manually.) 16533 * 16534 * @param screenState The new state of the screen. Can be either 16535 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 16536 */ 16537 public void onScreenStateChanged(int screenState) { 16538 } 16539 16540 /** 16541 * @see #onMovedToDisplay(int, Configuration) 16542 */ 16543 void dispatchMovedToDisplay(Display display, Configuration config) { 16544 mAttachInfo.mDisplay = display; 16545 mAttachInfo.mDisplayState = display.getState(); 16546 onMovedToDisplay(display.getDisplayId(), config); 16547 } 16548 16549 /** 16550 * Called by the system when the hosting activity is moved from one display to another without 16551 * recreation. This means that the activity is declared to handle all changes to configuration 16552 * that happened when it was switched to another display, so it wasn't destroyed and created 16553 * again. 16554 * 16555 * <p>This call will be followed by {@link #onConfigurationChanged(Configuration)} if the 16556 * applied configuration actually changed. It is up to app developer to choose whether to handle 16557 * the change in this method or in the following {@link #onConfigurationChanged(Configuration)} 16558 * call. 16559 * 16560 * <p>Use this callback to track changes to the displays if some functionality relies on an 16561 * association with some display properties. 16562 * 16563 * @param displayId The id of the display to which the view was moved. 16564 * @param config Configuration of the resources on new display after move. 16565 * 16566 * @see #onConfigurationChanged(Configuration) 16567 */ 16568 public void onMovedToDisplay(int displayId, Configuration config) { 16569 } 16570 16571 /** 16572 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 16573 */ 16574 private boolean hasRtlSupport() { 16575 return mContext.getApplicationInfo().hasRtlSupport(); 16576 } 16577 16578 /** 16579 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 16580 * RTL not supported) 16581 */ 16582 private boolean isRtlCompatibilityMode() { 16583 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 16584 return targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN_MR1 || !hasRtlSupport(); 16585 } 16586 16587 /** 16588 * @return true if RTL properties need resolution. 16589 * 16590 */ 16591 private boolean needRtlPropertiesResolution() { 16592 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 16593 } 16594 16595 /** 16596 * Called when any RTL property (layout direction or text direction or text alignment) has 16597 * been changed. 16598 * 16599 * Subclasses need to override this method to take care of cached information that depends on the 16600 * resolved layout direction, or to inform child views that inherit their layout direction. 16601 * 16602 * The default implementation does nothing. 16603 * 16604 * @param layoutDirection the direction of the layout 16605 * 16606 * @see #LAYOUT_DIRECTION_LTR 16607 * @see #LAYOUT_DIRECTION_RTL 16608 */ 16609 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 16610 } 16611 16612 /** 16613 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 16614 * that the parent directionality can and will be resolved before its children. 16615 * 16616 * @return true if resolution has been done, false otherwise. 16617 * 16618 * @hide 16619 */ 16620 public boolean resolveLayoutDirection() { 16621 // Clear any previous layout direction resolution 16622 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 16623 16624 if (hasRtlSupport()) { 16625 // Set resolved depending on layout direction 16626 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 16627 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 16628 case LAYOUT_DIRECTION_INHERIT: 16629 // We cannot resolve yet. LTR is by default and let the resolution happen again 16630 // later to get the correct resolved value 16631 if (!canResolveLayoutDirection()) return false; 16632 16633 // Parent has not yet resolved, LTR is still the default 16634 try { 16635 if (!mParent.isLayoutDirectionResolved()) return false; 16636 16637 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 16638 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 16639 } 16640 } catch (AbstractMethodError e) { 16641 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 16642 " does not fully implement ViewParent", e); 16643 } 16644 break; 16645 case LAYOUT_DIRECTION_RTL: 16646 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 16647 break; 16648 case LAYOUT_DIRECTION_LOCALE: 16649 if((LAYOUT_DIRECTION_RTL == 16650 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 16651 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 16652 } 16653 break; 16654 default: 16655 // Nothing to do, LTR by default 16656 } 16657 } 16658 16659 // Set to resolved 16660 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 16661 return true; 16662 } 16663 16664 /** 16665 * Check if layout direction resolution can be done. 16666 * 16667 * @return true if layout direction resolution can be done otherwise return false. 16668 */ 16669 public boolean canResolveLayoutDirection() { 16670 switch (getRawLayoutDirection()) { 16671 case LAYOUT_DIRECTION_INHERIT: 16672 if (mParent != null) { 16673 try { 16674 return mParent.canResolveLayoutDirection(); 16675 } catch (AbstractMethodError e) { 16676 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 16677 " does not fully implement ViewParent", e); 16678 } 16679 } 16680 return false; 16681 16682 default: 16683 return true; 16684 } 16685 } 16686 16687 /** 16688 * Reset the resolved layout direction. Layout direction will be resolved during a call to 16689 * {@link #onMeasure(int, int)}. 16690 * 16691 * @hide 16692 */ 16693 public void resetResolvedLayoutDirection() { 16694 // Reset the current resolved bits 16695 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 16696 } 16697 16698 /** 16699 * @return true if the layout direction is inherited. 16700 * 16701 * @hide 16702 */ 16703 public boolean isLayoutDirectionInherited() { 16704 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 16705 } 16706 16707 /** 16708 * @return true if layout direction has been resolved. 16709 */ 16710 public boolean isLayoutDirectionResolved() { 16711 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 16712 } 16713 16714 /** 16715 * Return if padding has been resolved 16716 * 16717 * @hide 16718 */ 16719 boolean isPaddingResolved() { 16720 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 16721 } 16722 16723 /** 16724 * Resolves padding depending on layout direction, if applicable, and 16725 * recomputes internal padding values to adjust for scroll bars. 16726 * 16727 * @hide 16728 */ 16729 public void resolvePadding() { 16730 final int resolvedLayoutDirection = getLayoutDirection(); 16731 16732 if (!isRtlCompatibilityMode()) { 16733 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 16734 // If start / end padding are defined, they will be resolved (hence overriding) to 16735 // left / right or right / left depending on the resolved layout direction. 16736 // If start / end padding are not defined, use the left / right ones. 16737 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 16738 Rect padding = sThreadLocal.get(); 16739 if (padding == null) { 16740 padding = new Rect(); 16741 sThreadLocal.set(padding); 16742 } 16743 mBackground.getPadding(padding); 16744 if (!mLeftPaddingDefined) { 16745 mUserPaddingLeftInitial = padding.left; 16746 } 16747 if (!mRightPaddingDefined) { 16748 mUserPaddingRightInitial = padding.right; 16749 } 16750 } 16751 switch (resolvedLayoutDirection) { 16752 case LAYOUT_DIRECTION_RTL: 16753 if (mUserPaddingStart != UNDEFINED_PADDING) { 16754 mUserPaddingRight = mUserPaddingStart; 16755 } else { 16756 mUserPaddingRight = mUserPaddingRightInitial; 16757 } 16758 if (mUserPaddingEnd != UNDEFINED_PADDING) { 16759 mUserPaddingLeft = mUserPaddingEnd; 16760 } else { 16761 mUserPaddingLeft = mUserPaddingLeftInitial; 16762 } 16763 break; 16764 case LAYOUT_DIRECTION_LTR: 16765 default: 16766 if (mUserPaddingStart != UNDEFINED_PADDING) { 16767 mUserPaddingLeft = mUserPaddingStart; 16768 } else { 16769 mUserPaddingLeft = mUserPaddingLeftInitial; 16770 } 16771 if (mUserPaddingEnd != UNDEFINED_PADDING) { 16772 mUserPaddingRight = mUserPaddingEnd; 16773 } else { 16774 mUserPaddingRight = mUserPaddingRightInitial; 16775 } 16776 } 16777 16778 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 16779 } 16780 16781 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 16782 onRtlPropertiesChanged(resolvedLayoutDirection); 16783 16784 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 16785 } 16786 16787 /** 16788 * Reset the resolved layout direction. 16789 * 16790 * @hide 16791 */ 16792 public void resetResolvedPadding() { 16793 resetResolvedPaddingInternal(); 16794 } 16795 16796 /** 16797 * Used when we only want to reset *this* view's padding and not trigger overrides 16798 * in ViewGroup that reset children too. 16799 */ 16800 void resetResolvedPaddingInternal() { 16801 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 16802 } 16803 16804 /** 16805 * This is called when the view is detached from a window. At this point it 16806 * no longer has a surface for drawing. 16807 * 16808 * @see #onAttachedToWindow() 16809 */ 16810 @CallSuper 16811 protected void onDetachedFromWindow() { 16812 } 16813 16814 /** 16815 * This is a framework-internal mirror of onDetachedFromWindow() that's called 16816 * after onDetachedFromWindow(). 16817 * 16818 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 16819 * The super method should be called at the end of the overridden method to ensure 16820 * subclasses are destroyed first 16821 * 16822 * @hide 16823 */ 16824 @CallSuper 16825 protected void onDetachedFromWindowInternal() { 16826 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 16827 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 16828 mPrivateFlags3 &= ~PFLAG3_TEMPORARY_DETACH; 16829 16830 removeUnsetPressCallback(); 16831 removeLongPressCallback(); 16832 removePerformClickCallback(); 16833 removeSendViewScrolledAccessibilityEventCallback(); 16834 stopNestedScroll(); 16835 16836 // Anything that started animating right before detach should already 16837 // be in its final state when re-attached. 16838 jumpDrawablesToCurrentState(); 16839 16840 destroyDrawingCache(); 16841 16842 cleanupDraw(); 16843 mCurrentAnimation = null; 16844 16845 if ((mViewFlags & TOOLTIP) == TOOLTIP) { 16846 hideTooltip(); 16847 } 16848 } 16849 16850 private void cleanupDraw() { 16851 resetDisplayList(); 16852 if (mAttachInfo != null) { 16853 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 16854 } 16855 } 16856 16857 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 16858 } 16859 16860 /** 16861 * @return The number of times this view has been attached to a window 16862 */ 16863 protected int getWindowAttachCount() { 16864 return mWindowAttachCount; 16865 } 16866 16867 /** 16868 * Retrieve a unique token identifying the window this view is attached to. 16869 * @return Return the window's token for use in 16870 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 16871 */ 16872 public IBinder getWindowToken() { 16873 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 16874 } 16875 16876 /** 16877 * Retrieve the {@link WindowId} for the window this view is 16878 * currently attached to. 16879 */ 16880 public WindowId getWindowId() { 16881 if (mAttachInfo == null) { 16882 return null; 16883 } 16884 if (mAttachInfo.mWindowId == null) { 16885 try { 16886 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 16887 mAttachInfo.mWindowToken); 16888 mAttachInfo.mWindowId = new WindowId( 16889 mAttachInfo.mIWindowId); 16890 } catch (RemoteException e) { 16891 } 16892 } 16893 return mAttachInfo.mWindowId; 16894 } 16895 16896 /** 16897 * Retrieve a unique token identifying the top-level "real" window of 16898 * the window that this view is attached to. That is, this is like 16899 * {@link #getWindowToken}, except if the window this view in is a panel 16900 * window (attached to another containing window), then the token of 16901 * the containing window is returned instead. 16902 * 16903 * @return Returns the associated window token, either 16904 * {@link #getWindowToken()} or the containing window's token. 16905 */ 16906 public IBinder getApplicationWindowToken() { 16907 AttachInfo ai = mAttachInfo; 16908 if (ai != null) { 16909 IBinder appWindowToken = ai.mPanelParentWindowToken; 16910 if (appWindowToken == null) { 16911 appWindowToken = ai.mWindowToken; 16912 } 16913 return appWindowToken; 16914 } 16915 return null; 16916 } 16917 16918 /** 16919 * Gets the logical display to which the view's window has been attached. 16920 * 16921 * @return The logical display, or null if the view is not currently attached to a window. 16922 */ 16923 public Display getDisplay() { 16924 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 16925 } 16926 16927 /** 16928 * Retrieve private session object this view hierarchy is using to 16929 * communicate with the window manager. 16930 * @return the session object to communicate with the window manager 16931 */ 16932 /*package*/ IWindowSession getWindowSession() { 16933 return mAttachInfo != null ? mAttachInfo.mSession : null; 16934 } 16935 16936 /** 16937 * Return the visibility value of the least visible component passed. 16938 */ 16939 int combineVisibility(int vis1, int vis2) { 16940 // This works because VISIBLE < INVISIBLE < GONE. 16941 return Math.max(vis1, vis2); 16942 } 16943 16944 /** 16945 * @param info the {@link android.view.View.AttachInfo} to associated with 16946 * this view 16947 */ 16948 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 16949 mAttachInfo = info; 16950 if (mOverlay != null) { 16951 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 16952 } 16953 mWindowAttachCount++; 16954 // We will need to evaluate the drawable state at least once. 16955 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 16956 if (mFloatingTreeObserver != null) { 16957 info.mTreeObserver.merge(mFloatingTreeObserver); 16958 mFloatingTreeObserver = null; 16959 } 16960 16961 registerPendingFrameMetricsObservers(); 16962 16963 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 16964 mAttachInfo.mScrollContainers.add(this); 16965 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 16966 } 16967 // Transfer all pending runnables. 16968 if (mRunQueue != null) { 16969 mRunQueue.executeActions(info.mHandler); 16970 mRunQueue = null; 16971 } 16972 performCollectViewAttributes(mAttachInfo, visibility); 16973 onAttachedToWindow(); 16974 16975 ListenerInfo li = mListenerInfo; 16976 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 16977 li != null ? li.mOnAttachStateChangeListeners : null; 16978 if (listeners != null && listeners.size() > 0) { 16979 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 16980 // perform the dispatching. The iterator is a safe guard against listeners that 16981 // could mutate the list by calling the various add/remove methods. This prevents 16982 // the array from being modified while we iterate it. 16983 for (OnAttachStateChangeListener listener : listeners) { 16984 listener.onViewAttachedToWindow(this); 16985 } 16986 } 16987 16988 int vis = info.mWindowVisibility; 16989 if (vis != GONE) { 16990 onWindowVisibilityChanged(vis); 16991 if (isShown()) { 16992 // Calling onVisibilityAggregated directly here since the subtree will also 16993 // receive dispatchAttachedToWindow and this same call 16994 onVisibilityAggregated(vis == VISIBLE); 16995 } 16996 } 16997 16998 // Send onVisibilityChanged directly instead of dispatchVisibilityChanged. 16999 // As all views in the subtree will already receive dispatchAttachedToWindow 17000 // traversing the subtree again here is not desired. 17001 onVisibilityChanged(this, visibility); 17002 17003 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 17004 // If nobody has evaluated the drawable state yet, then do it now. 17005 refreshDrawableState(); 17006 } 17007 needGlobalAttributesUpdate(false); 17008 17009 notifyEnterOrExitForAutoFillIfNeeded(true); 17010 } 17011 17012 void dispatchDetachedFromWindow() { 17013 AttachInfo info = mAttachInfo; 17014 if (info != null) { 17015 int vis = info.mWindowVisibility; 17016 if (vis != GONE) { 17017 onWindowVisibilityChanged(GONE); 17018 if (isShown()) { 17019 // Invoking onVisibilityAggregated directly here since the subtree 17020 // will also receive detached from window 17021 onVisibilityAggregated(false); 17022 } 17023 } 17024 } 17025 17026 onDetachedFromWindow(); 17027 onDetachedFromWindowInternal(); 17028 17029 InputMethodManager imm = InputMethodManager.peekInstance(); 17030 if (imm != null) { 17031 imm.onViewDetachedFromWindow(this); 17032 } 17033 17034 ListenerInfo li = mListenerInfo; 17035 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 17036 li != null ? li.mOnAttachStateChangeListeners : null; 17037 if (listeners != null && listeners.size() > 0) { 17038 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 17039 // perform the dispatching. The iterator is a safe guard against listeners that 17040 // could mutate the list by calling the various add/remove methods. This prevents 17041 // the array from being modified while we iterate it. 17042 for (OnAttachStateChangeListener listener : listeners) { 17043 listener.onViewDetachedFromWindow(this); 17044 } 17045 } 17046 17047 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 17048 mAttachInfo.mScrollContainers.remove(this); 17049 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 17050 } 17051 17052 mAttachInfo = null; 17053 if (mOverlay != null) { 17054 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 17055 } 17056 17057 notifyEnterOrExitForAutoFillIfNeeded(false); 17058 } 17059 17060 /** 17061 * Cancel any deferred high-level input events that were previously posted to the event queue. 17062 * 17063 * <p>Many views post high-level events such as click handlers to the event queue 17064 * to run deferred in order to preserve a desired user experience - clearing visible 17065 * pressed states before executing, etc. This method will abort any events of this nature 17066 * that are currently in flight.</p> 17067 * 17068 * <p>Custom views that generate their own high-level deferred input events should override 17069 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 17070 * 17071 * <p>This will also cancel pending input events for any child views.</p> 17072 * 17073 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 17074 * This will not impact newer events posted after this call that may occur as a result of 17075 * lower-level input events still waiting in the queue. If you are trying to prevent 17076 * double-submitted events for the duration of some sort of asynchronous transaction 17077 * you should also take other steps to protect against unexpected double inputs e.g. calling 17078 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 17079 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 17080 */ 17081 public final void cancelPendingInputEvents() { 17082 dispatchCancelPendingInputEvents(); 17083 } 17084 17085 /** 17086 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 17087 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 17088 */ 17089 void dispatchCancelPendingInputEvents() { 17090 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 17091 onCancelPendingInputEvents(); 17092 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 17093 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 17094 " did not call through to super.onCancelPendingInputEvents()"); 17095 } 17096 } 17097 17098 /** 17099 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 17100 * a parent view. 17101 * 17102 * <p>This method is responsible for removing any pending high-level input events that were 17103 * posted to the event queue to run later. Custom view classes that post their own deferred 17104 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 17105 * {@link android.os.Handler} should override this method, call 17106 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 17107 * </p> 17108 */ 17109 public void onCancelPendingInputEvents() { 17110 removePerformClickCallback(); 17111 cancelLongPress(); 17112 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 17113 } 17114 17115 /** 17116 * Store this view hierarchy's frozen state into the given container. 17117 * 17118 * @param container The SparseArray in which to save the view's state. 17119 * 17120 * @see #restoreHierarchyState(android.util.SparseArray) 17121 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17122 * @see #onSaveInstanceState() 17123 */ 17124 public void saveHierarchyState(SparseArray<Parcelable> container) { 17125 dispatchSaveInstanceState(container); 17126 } 17127 17128 /** 17129 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 17130 * this view and its children. May be overridden to modify how freezing happens to a 17131 * view's children; for example, some views may want to not store state for their children. 17132 * 17133 * @param container The SparseArray in which to save the view's state. 17134 * 17135 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17136 * @see #saveHierarchyState(android.util.SparseArray) 17137 * @see #onSaveInstanceState() 17138 */ 17139 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 17140 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 17141 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 17142 Parcelable state = onSaveInstanceState(); 17143 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 17144 throw new IllegalStateException( 17145 "Derived class did not call super.onSaveInstanceState()"); 17146 } 17147 if (state != null) { 17148 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 17149 // + ": " + state); 17150 container.put(mID, state); 17151 } 17152 } 17153 } 17154 17155 /** 17156 * Hook allowing a view to generate a representation of its internal state 17157 * that can later be used to create a new instance with that same state. 17158 * This state should only contain information that is not persistent or can 17159 * not be reconstructed later. For example, you will never store your 17160 * current position on screen because that will be computed again when a 17161 * new instance of the view is placed in its view hierarchy. 17162 * <p> 17163 * Some examples of things you may store here: the current cursor position 17164 * in a text view (but usually not the text itself since that is stored in a 17165 * content provider or other persistent storage), the currently selected 17166 * item in a list view. 17167 * 17168 * @return Returns a Parcelable object containing the view's current dynamic 17169 * state, or null if there is nothing interesting to save. The 17170 * default implementation returns null. 17171 * @see #onRestoreInstanceState(android.os.Parcelable) 17172 * @see #saveHierarchyState(android.util.SparseArray) 17173 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17174 * @see #setSaveEnabled(boolean) 17175 */ 17176 @CallSuper 17177 protected Parcelable onSaveInstanceState() { 17178 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 17179 if (mStartActivityRequestWho != null) { 17180 BaseSavedState state = new BaseSavedState(AbsSavedState.EMPTY_STATE); 17181 state.mStartActivityRequestWhoSaved = mStartActivityRequestWho; 17182 return state; 17183 } 17184 return BaseSavedState.EMPTY_STATE; 17185 } 17186 17187 /** 17188 * Restore this view hierarchy's frozen state from the given container. 17189 * 17190 * @param container The SparseArray which holds previously frozen states. 17191 * 17192 * @see #saveHierarchyState(android.util.SparseArray) 17193 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17194 * @see #onRestoreInstanceState(android.os.Parcelable) 17195 */ 17196 public void restoreHierarchyState(SparseArray<Parcelable> container) { 17197 dispatchRestoreInstanceState(container); 17198 } 17199 17200 /** 17201 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 17202 * state for this view and its children. May be overridden to modify how restoring 17203 * happens to a view's children; for example, some views may want to not store state 17204 * for their children. 17205 * 17206 * @param container The SparseArray which holds previously saved state. 17207 * 17208 * @see #dispatchSaveInstanceState(android.util.SparseArray) 17209 * @see #restoreHierarchyState(android.util.SparseArray) 17210 * @see #onRestoreInstanceState(android.os.Parcelable) 17211 */ 17212 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 17213 if (mID != NO_ID) { 17214 Parcelable state = container.get(mID); 17215 if (state != null) { 17216 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 17217 // + ": " + state); 17218 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 17219 onRestoreInstanceState(state); 17220 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 17221 throw new IllegalStateException( 17222 "Derived class did not call super.onRestoreInstanceState()"); 17223 } 17224 } 17225 } 17226 } 17227 17228 /** 17229 * Hook allowing a view to re-apply a representation of its internal state that had previously 17230 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 17231 * null state. 17232 * 17233 * @param state The frozen state that had previously been returned by 17234 * {@link #onSaveInstanceState}. 17235 * 17236 * @see #onSaveInstanceState() 17237 * @see #restoreHierarchyState(android.util.SparseArray) 17238 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 17239 */ 17240 @CallSuper 17241 protected void onRestoreInstanceState(Parcelable state) { 17242 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 17243 if (state != null && !(state instanceof AbsSavedState)) { 17244 throw new IllegalArgumentException("Wrong state class, expecting View State but " 17245 + "received " + state.getClass().toString() + " instead. This usually happens " 17246 + "when two views of different type have the same id in the same hierarchy. " 17247 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 17248 + "other views do not use the same id."); 17249 } 17250 if (state != null && state instanceof BaseSavedState) { 17251 mStartActivityRequestWho = ((BaseSavedState) state).mStartActivityRequestWhoSaved; 17252 } 17253 } 17254 17255 /** 17256 * <p>Return the time at which the drawing of the view hierarchy started.</p> 17257 * 17258 * @return the drawing start time in milliseconds 17259 */ 17260 public long getDrawingTime() { 17261 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 17262 } 17263 17264 /** 17265 * <p>Enables or disables the duplication of the parent's state into this view. When 17266 * duplication is enabled, this view gets its drawable state from its parent rather 17267 * than from its own internal properties.</p> 17268 * 17269 * <p>Note: in the current implementation, setting this property to true after the 17270 * view was added to a ViewGroup might have no effect at all. This property should 17271 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 17272 * 17273 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 17274 * property is enabled, an exception will be thrown.</p> 17275 * 17276 * <p>Note: if the child view uses and updates additional states which are unknown to the 17277 * parent, these states should not be affected by this method.</p> 17278 * 17279 * @param enabled True to enable duplication of the parent's drawable state, false 17280 * to disable it. 17281 * 17282 * @see #getDrawableState() 17283 * @see #isDuplicateParentStateEnabled() 17284 */ 17285 public void setDuplicateParentStateEnabled(boolean enabled) { 17286 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 17287 } 17288 17289 /** 17290 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 17291 * 17292 * @return True if this view's drawable state is duplicated from the parent, 17293 * false otherwise 17294 * 17295 * @see #getDrawableState() 17296 * @see #setDuplicateParentStateEnabled(boolean) 17297 */ 17298 public boolean isDuplicateParentStateEnabled() { 17299 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 17300 } 17301 17302 /** 17303 * <p>Specifies the type of layer backing this view. The layer can be 17304 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17305 * {@link #LAYER_TYPE_HARDWARE}.</p> 17306 * 17307 * <p>A layer is associated with an optional {@link android.graphics.Paint} 17308 * instance that controls how the layer is composed on screen. The following 17309 * properties of the paint are taken into account when composing the layer:</p> 17310 * <ul> 17311 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 17312 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 17313 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 17314 * </ul> 17315 * 17316 * <p>If this view has an alpha value set to < 1.0 by calling 17317 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superseded 17318 * by this view's alpha value.</p> 17319 * 17320 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 17321 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 17322 * for more information on when and how to use layers.</p> 17323 * 17324 * @param layerType The type of layer to use with this view, must be one of 17325 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17326 * {@link #LAYER_TYPE_HARDWARE} 17327 * @param paint The paint used to compose the layer. This argument is optional 17328 * and can be null. It is ignored when the layer type is 17329 * {@link #LAYER_TYPE_NONE} 17330 * 17331 * @see #getLayerType() 17332 * @see #LAYER_TYPE_NONE 17333 * @see #LAYER_TYPE_SOFTWARE 17334 * @see #LAYER_TYPE_HARDWARE 17335 * @see #setAlpha(float) 17336 * 17337 * @attr ref android.R.styleable#View_layerType 17338 */ 17339 public void setLayerType(int layerType, @Nullable Paint paint) { 17340 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 17341 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 17342 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 17343 } 17344 17345 boolean typeChanged = mRenderNode.setLayerType(layerType); 17346 17347 if (!typeChanged) { 17348 setLayerPaint(paint); 17349 return; 17350 } 17351 17352 if (layerType != LAYER_TYPE_SOFTWARE) { 17353 // Destroy any previous software drawing cache if present 17354 // NOTE: even if previous layer type is HW, we do this to ensure we've cleaned up 17355 // drawing cache created in View#draw when drawing to a SW canvas. 17356 destroyDrawingCache(); 17357 } 17358 17359 mLayerType = layerType; 17360 mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint; 17361 mRenderNode.setLayerPaint(mLayerPaint); 17362 17363 // draw() behaves differently if we are on a layer, so we need to 17364 // invalidate() here 17365 invalidateParentCaches(); 17366 invalidate(true); 17367 } 17368 17369 /** 17370 * Updates the {@link Paint} object used with the current layer (used only if the current 17371 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 17372 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 17373 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 17374 * ensure that the view gets redrawn immediately. 17375 * 17376 * <p>A layer is associated with an optional {@link android.graphics.Paint} 17377 * instance that controls how the layer is composed on screen. The following 17378 * properties of the paint are taken into account when composing the layer:</p> 17379 * <ul> 17380 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 17381 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 17382 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 17383 * </ul> 17384 * 17385 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 17386 * alpha value of the layer's paint is superseded by this view's alpha value.</p> 17387 * 17388 * @param paint The paint used to compose the layer. This argument is optional 17389 * and can be null. It is ignored when the layer type is 17390 * {@link #LAYER_TYPE_NONE} 17391 * 17392 * @see #setLayerType(int, android.graphics.Paint) 17393 */ 17394 public void setLayerPaint(@Nullable Paint paint) { 17395 int layerType = getLayerType(); 17396 if (layerType != LAYER_TYPE_NONE) { 17397 mLayerPaint = paint; 17398 if (layerType == LAYER_TYPE_HARDWARE) { 17399 if (mRenderNode.setLayerPaint(paint)) { 17400 invalidateViewProperty(false, false); 17401 } 17402 } else { 17403 invalidate(); 17404 } 17405 } 17406 } 17407 17408 /** 17409 * Indicates what type of layer is currently associated with this view. By default 17410 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 17411 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 17412 * for more information on the different types of layers. 17413 * 17414 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 17415 * {@link #LAYER_TYPE_HARDWARE} 17416 * 17417 * @see #setLayerType(int, android.graphics.Paint) 17418 * @see #buildLayer() 17419 * @see #LAYER_TYPE_NONE 17420 * @see #LAYER_TYPE_SOFTWARE 17421 * @see #LAYER_TYPE_HARDWARE 17422 */ 17423 public int getLayerType() { 17424 return mLayerType; 17425 } 17426 17427 /** 17428 * Forces this view's layer to be created and this view to be rendered 17429 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 17430 * invoking this method will have no effect. 17431 * 17432 * This method can for instance be used to render a view into its layer before 17433 * starting an animation. If this view is complex, rendering into the layer 17434 * before starting the animation will avoid skipping frames. 17435 * 17436 * @throws IllegalStateException If this view is not attached to a window 17437 * 17438 * @see #setLayerType(int, android.graphics.Paint) 17439 */ 17440 public void buildLayer() { 17441 if (mLayerType == LAYER_TYPE_NONE) return; 17442 17443 final AttachInfo attachInfo = mAttachInfo; 17444 if (attachInfo == null) { 17445 throw new IllegalStateException("This view must be attached to a window first"); 17446 } 17447 17448 if (getWidth() == 0 || getHeight() == 0) { 17449 return; 17450 } 17451 17452 switch (mLayerType) { 17453 case LAYER_TYPE_HARDWARE: 17454 updateDisplayListIfDirty(); 17455 if (attachInfo.mThreadedRenderer != null && mRenderNode.isValid()) { 17456 attachInfo.mThreadedRenderer.buildLayer(mRenderNode); 17457 } 17458 break; 17459 case LAYER_TYPE_SOFTWARE: 17460 buildDrawingCache(true); 17461 break; 17462 } 17463 } 17464 17465 /** 17466 * Destroys all hardware rendering resources. This method is invoked 17467 * when the system needs to reclaim resources. Upon execution of this 17468 * method, you should free any OpenGL resources created by the view. 17469 * 17470 * Note: you <strong>must</strong> call 17471 * <code>super.destroyHardwareResources()</code> when overriding 17472 * this method. 17473 * 17474 * @hide 17475 */ 17476 @CallSuper 17477 protected void destroyHardwareResources() { 17478 if (mOverlay != null) { 17479 mOverlay.getOverlayView().destroyHardwareResources(); 17480 } 17481 if (mGhostView != null) { 17482 mGhostView.destroyHardwareResources(); 17483 } 17484 } 17485 17486 /** 17487 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 17488 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 17489 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 17490 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 17491 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 17492 * null.</p> 17493 * 17494 * <p>Enabling the drawing cache is similar to 17495 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 17496 * acceleration is turned off. When hardware acceleration is turned on, enabling the 17497 * drawing cache has no effect on rendering because the system uses a different mechanism 17498 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 17499 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 17500 * for information on how to enable software and hardware layers.</p> 17501 * 17502 * <p>This API can be used to manually generate 17503 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 17504 * {@link #getDrawingCache()}.</p> 17505 * 17506 * @param enabled true to enable the drawing cache, false otherwise 17507 * 17508 * @see #isDrawingCacheEnabled() 17509 * @see #getDrawingCache() 17510 * @see #buildDrawingCache() 17511 * @see #setLayerType(int, android.graphics.Paint) 17512 */ 17513 public void setDrawingCacheEnabled(boolean enabled) { 17514 mCachingFailed = false; 17515 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 17516 } 17517 17518 /** 17519 * <p>Indicates whether the drawing cache is enabled for this view.</p> 17520 * 17521 * @return true if the drawing cache is enabled 17522 * 17523 * @see #setDrawingCacheEnabled(boolean) 17524 * @see #getDrawingCache() 17525 */ 17526 @ViewDebug.ExportedProperty(category = "drawing") 17527 public boolean isDrawingCacheEnabled() { 17528 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 17529 } 17530 17531 /** 17532 * Debugging utility which recursively outputs the dirty state of a view and its 17533 * descendants. 17534 * 17535 * @hide 17536 */ 17537 @SuppressWarnings({"UnusedDeclaration"}) 17538 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 17539 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 17540 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 17541 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 17542 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 17543 if (clear) { 17544 mPrivateFlags &= clearMask; 17545 } 17546 if (this instanceof ViewGroup) { 17547 ViewGroup parent = (ViewGroup) this; 17548 final int count = parent.getChildCount(); 17549 for (int i = 0; i < count; i++) { 17550 final View child = parent.getChildAt(i); 17551 child.outputDirtyFlags(indent + " ", clear, clearMask); 17552 } 17553 } 17554 } 17555 17556 /** 17557 * This method is used by ViewGroup to cause its children to restore or recreate their 17558 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 17559 * to recreate its own display list, which would happen if it went through the normal 17560 * draw/dispatchDraw mechanisms. 17561 * 17562 * @hide 17563 */ 17564 protected void dispatchGetDisplayList() {} 17565 17566 /** 17567 * A view that is not attached or hardware accelerated cannot create a display list. 17568 * This method checks these conditions and returns the appropriate result. 17569 * 17570 * @return true if view has the ability to create a display list, false otherwise. 17571 * 17572 * @hide 17573 */ 17574 public boolean canHaveDisplayList() { 17575 return !(mAttachInfo == null || mAttachInfo.mThreadedRenderer == null); 17576 } 17577 17578 /** 17579 * Gets the RenderNode for the view, and updates its DisplayList (if needed and supported) 17580 * @hide 17581 */ 17582 @NonNull 17583 public RenderNode updateDisplayListIfDirty() { 17584 final RenderNode renderNode = mRenderNode; 17585 if (!canHaveDisplayList()) { 17586 // can't populate RenderNode, don't try 17587 return renderNode; 17588 } 17589 17590 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 17591 || !renderNode.isValid() 17592 || (mRecreateDisplayList)) { 17593 // Don't need to recreate the display list, just need to tell our 17594 // children to restore/recreate theirs 17595 if (renderNode.isValid() 17596 && !mRecreateDisplayList) { 17597 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17598 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17599 dispatchGetDisplayList(); 17600 17601 return renderNode; // no work needed 17602 } 17603 17604 // If we got here, we're recreating it. Mark it as such to ensure that 17605 // we copy in child display lists into ours in drawChild() 17606 mRecreateDisplayList = true; 17607 17608 int width = mRight - mLeft; 17609 int height = mBottom - mTop; 17610 int layerType = getLayerType(); 17611 17612 final DisplayListCanvas canvas = renderNode.start(width, height); 17613 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 17614 17615 try { 17616 if (layerType == LAYER_TYPE_SOFTWARE) { 17617 buildDrawingCache(true); 17618 Bitmap cache = getDrawingCache(true); 17619 if (cache != null) { 17620 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 17621 } 17622 } else { 17623 computeScroll(); 17624 17625 canvas.translate(-mScrollX, -mScrollY); 17626 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17627 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17628 17629 // Fast path for layouts with no backgrounds 17630 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17631 dispatchDraw(canvas); 17632 if (mOverlay != null && !mOverlay.isEmpty()) { 17633 mOverlay.getOverlayView().draw(canvas); 17634 } 17635 if (debugDraw()) { 17636 debugDrawFocus(canvas); 17637 } 17638 } else { 17639 draw(canvas); 17640 } 17641 } 17642 } finally { 17643 renderNode.end(canvas); 17644 setDisplayListProperties(renderNode); 17645 } 17646 } else { 17647 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 17648 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17649 } 17650 return renderNode; 17651 } 17652 17653 private void resetDisplayList() { 17654 mRenderNode.discardDisplayList(); 17655 if (mBackgroundRenderNode != null) { 17656 mBackgroundRenderNode.discardDisplayList(); 17657 } 17658 } 17659 17660 /** 17661 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 17662 * 17663 * @return A non-scaled bitmap representing this view or null if cache is disabled. 17664 * 17665 * @see #getDrawingCache(boolean) 17666 */ 17667 public Bitmap getDrawingCache() { 17668 return getDrawingCache(false); 17669 } 17670 17671 /** 17672 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 17673 * is null when caching is disabled. If caching is enabled and the cache is not ready, 17674 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 17675 * draw from the cache when the cache is enabled. To benefit from the cache, you must 17676 * request the drawing cache by calling this method and draw it on screen if the 17677 * returned bitmap is not null.</p> 17678 * 17679 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 17680 * this method will create a bitmap of the same size as this view. Because this bitmap 17681 * will be drawn scaled by the parent ViewGroup, the result on screen might show 17682 * scaling artifacts. To avoid such artifacts, you should call this method by setting 17683 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 17684 * size than the view. This implies that your application must be able to handle this 17685 * size.</p> 17686 * 17687 * @param autoScale Indicates whether the generated bitmap should be scaled based on 17688 * the current density of the screen when the application is in compatibility 17689 * mode. 17690 * 17691 * @return A bitmap representing this view or null if cache is disabled. 17692 * 17693 * @see #setDrawingCacheEnabled(boolean) 17694 * @see #isDrawingCacheEnabled() 17695 * @see #buildDrawingCache(boolean) 17696 * @see #destroyDrawingCache() 17697 */ 17698 public Bitmap getDrawingCache(boolean autoScale) { 17699 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 17700 return null; 17701 } 17702 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 17703 buildDrawingCache(autoScale); 17704 } 17705 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 17706 } 17707 17708 /** 17709 * <p>Frees the resources used by the drawing cache. If you call 17710 * {@link #buildDrawingCache()} manually without calling 17711 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 17712 * should cleanup the cache with this method afterwards.</p> 17713 * 17714 * @see #setDrawingCacheEnabled(boolean) 17715 * @see #buildDrawingCache() 17716 * @see #getDrawingCache() 17717 */ 17718 public void destroyDrawingCache() { 17719 if (mDrawingCache != null) { 17720 mDrawingCache.recycle(); 17721 mDrawingCache = null; 17722 } 17723 if (mUnscaledDrawingCache != null) { 17724 mUnscaledDrawingCache.recycle(); 17725 mUnscaledDrawingCache = null; 17726 } 17727 } 17728 17729 /** 17730 * Setting a solid background color for the drawing cache's bitmaps will improve 17731 * performance and memory usage. Note, though that this should only be used if this 17732 * view will always be drawn on top of a solid color. 17733 * 17734 * @param color The background color to use for the drawing cache's bitmap 17735 * 17736 * @see #setDrawingCacheEnabled(boolean) 17737 * @see #buildDrawingCache() 17738 * @see #getDrawingCache() 17739 */ 17740 public void setDrawingCacheBackgroundColor(@ColorInt int color) { 17741 if (color != mDrawingCacheBackgroundColor) { 17742 mDrawingCacheBackgroundColor = color; 17743 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 17744 } 17745 } 17746 17747 /** 17748 * @see #setDrawingCacheBackgroundColor(int) 17749 * 17750 * @return The background color to used for the drawing cache's bitmap 17751 */ 17752 @ColorInt 17753 public int getDrawingCacheBackgroundColor() { 17754 return mDrawingCacheBackgroundColor; 17755 } 17756 17757 /** 17758 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 17759 * 17760 * @see #buildDrawingCache(boolean) 17761 */ 17762 public void buildDrawingCache() { 17763 buildDrawingCache(false); 17764 } 17765 17766 /** 17767 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 17768 * 17769 * <p>If you call {@link #buildDrawingCache()} manually without calling 17770 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 17771 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 17772 * 17773 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 17774 * this method will create a bitmap of the same size as this view. Because this bitmap 17775 * will be drawn scaled by the parent ViewGroup, the result on screen might show 17776 * scaling artifacts. To avoid such artifacts, you should call this method by setting 17777 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 17778 * size than the view. This implies that your application must be able to handle this 17779 * size.</p> 17780 * 17781 * <p>You should avoid calling this method when hardware acceleration is enabled. If 17782 * you do not need the drawing cache bitmap, calling this method will increase memory 17783 * usage and cause the view to be rendered in software once, thus negatively impacting 17784 * performance.</p> 17785 * 17786 * @see #getDrawingCache() 17787 * @see #destroyDrawingCache() 17788 */ 17789 public void buildDrawingCache(boolean autoScale) { 17790 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 17791 mDrawingCache == null : mUnscaledDrawingCache == null)) { 17792 if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) { 17793 Trace.traceBegin(Trace.TRACE_TAG_VIEW, 17794 "buildDrawingCache/SW Layer for " + getClass().getSimpleName()); 17795 } 17796 try { 17797 buildDrawingCacheImpl(autoScale); 17798 } finally { 17799 Trace.traceEnd(Trace.TRACE_TAG_VIEW); 17800 } 17801 } 17802 } 17803 17804 /** 17805 * private, internal implementation of buildDrawingCache, used to enable tracing 17806 */ 17807 private void buildDrawingCacheImpl(boolean autoScale) { 17808 mCachingFailed = false; 17809 17810 int width = mRight - mLeft; 17811 int height = mBottom - mTop; 17812 17813 final AttachInfo attachInfo = mAttachInfo; 17814 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 17815 17816 if (autoScale && scalingRequired) { 17817 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 17818 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 17819 } 17820 17821 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 17822 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 17823 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 17824 17825 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 17826 final long drawingCacheSize = 17827 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 17828 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 17829 if (width > 0 && height > 0) { 17830 Log.w(VIEW_LOG_TAG, getClass().getSimpleName() + " not displayed because it is" 17831 + " too large to fit into a software layer (or drawing cache), needs " 17832 + projectedBitmapSize + " bytes, only " 17833 + drawingCacheSize + " available"); 17834 } 17835 destroyDrawingCache(); 17836 mCachingFailed = true; 17837 return; 17838 } 17839 17840 boolean clear = true; 17841 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 17842 17843 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 17844 Bitmap.Config quality; 17845 if (!opaque) { 17846 // Never pick ARGB_4444 because it looks awful 17847 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 17848 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 17849 case DRAWING_CACHE_QUALITY_AUTO: 17850 case DRAWING_CACHE_QUALITY_LOW: 17851 case DRAWING_CACHE_QUALITY_HIGH: 17852 default: 17853 quality = Bitmap.Config.ARGB_8888; 17854 break; 17855 } 17856 } else { 17857 // Optimization for translucent windows 17858 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 17859 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 17860 } 17861 17862 // Try to cleanup memory 17863 if (bitmap != null) bitmap.recycle(); 17864 17865 try { 17866 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 17867 width, height, quality); 17868 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 17869 if (autoScale) { 17870 mDrawingCache = bitmap; 17871 } else { 17872 mUnscaledDrawingCache = bitmap; 17873 } 17874 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 17875 } catch (OutOfMemoryError e) { 17876 // If there is not enough memory to create the bitmap cache, just 17877 // ignore the issue as bitmap caches are not required to draw the 17878 // view hierarchy 17879 if (autoScale) { 17880 mDrawingCache = null; 17881 } else { 17882 mUnscaledDrawingCache = null; 17883 } 17884 mCachingFailed = true; 17885 return; 17886 } 17887 17888 clear = drawingCacheBackgroundColor != 0; 17889 } 17890 17891 Canvas canvas; 17892 if (attachInfo != null) { 17893 canvas = attachInfo.mCanvas; 17894 if (canvas == null) { 17895 canvas = new Canvas(); 17896 } 17897 canvas.setBitmap(bitmap); 17898 // Temporarily clobber the cached Canvas in case one of our children 17899 // is also using a drawing cache. Without this, the children would 17900 // steal the canvas by attaching their own bitmap to it and bad, bad 17901 // thing would happen (invisible views, corrupted drawings, etc.) 17902 attachInfo.mCanvas = null; 17903 } else { 17904 // This case should hopefully never or seldom happen 17905 canvas = new Canvas(bitmap); 17906 } 17907 17908 if (clear) { 17909 bitmap.eraseColor(drawingCacheBackgroundColor); 17910 } 17911 17912 computeScroll(); 17913 final int restoreCount = canvas.save(); 17914 17915 if (autoScale && scalingRequired) { 17916 final float scale = attachInfo.mApplicationScale; 17917 canvas.scale(scale, scale); 17918 } 17919 17920 canvas.translate(-mScrollX, -mScrollY); 17921 17922 mPrivateFlags |= PFLAG_DRAWN; 17923 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 17924 mLayerType != LAYER_TYPE_NONE) { 17925 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 17926 } 17927 17928 // Fast path for layouts with no backgrounds 17929 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 17930 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 17931 dispatchDraw(canvas); 17932 if (mOverlay != null && !mOverlay.isEmpty()) { 17933 mOverlay.getOverlayView().draw(canvas); 17934 } 17935 } else { 17936 draw(canvas); 17937 } 17938 17939 canvas.restoreToCount(restoreCount); 17940 canvas.setBitmap(null); 17941 17942 if (attachInfo != null) { 17943 // Restore the cached Canvas for our siblings 17944 attachInfo.mCanvas = canvas; 17945 } 17946 } 17947 17948 /** 17949 * Create a snapshot of the view into a bitmap. We should probably make 17950 * some form of this public, but should think about the API. 17951 * 17952 * @hide 17953 */ 17954 public Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 17955 int width = mRight - mLeft; 17956 int height = mBottom - mTop; 17957 17958 final AttachInfo attachInfo = mAttachInfo; 17959 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 17960 width = (int) ((width * scale) + 0.5f); 17961 height = (int) ((height * scale) + 0.5f); 17962 17963 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 17964 width > 0 ? width : 1, height > 0 ? height : 1, quality); 17965 if (bitmap == null) { 17966 throw new OutOfMemoryError(); 17967 } 17968 17969 Resources resources = getResources(); 17970 if (resources != null) { 17971 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 17972 } 17973 17974 Canvas canvas; 17975 if (attachInfo != null) { 17976 canvas = attachInfo.mCanvas; 17977 if (canvas == null) { 17978 canvas = new Canvas(); 17979 } 17980 canvas.setBitmap(bitmap); 17981 // Temporarily clobber the cached Canvas in case one of our children 17982 // is also using a drawing cache. Without this, the children would 17983 // steal the canvas by attaching their own bitmap to it and bad, bad 17984 // things would happen (invisible views, corrupted drawings, etc.) 17985 attachInfo.mCanvas = null; 17986 } else { 17987 // This case should hopefully never or seldom happen 17988 canvas = new Canvas(bitmap); 17989 } 17990 boolean enabledHwBitmapsInSwMode = canvas.isHwBitmapsInSwModeEnabled(); 17991 canvas.setHwBitmapsInSwModeEnabled(true); 17992 if ((backgroundColor & 0xff000000) != 0) { 17993 bitmap.eraseColor(backgroundColor); 17994 } 17995 17996 computeScroll(); 17997 final int restoreCount = canvas.save(); 17998 canvas.scale(scale, scale); 17999 canvas.translate(-mScrollX, -mScrollY); 18000 18001 // Temporarily remove the dirty mask 18002 int flags = mPrivateFlags; 18003 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18004 18005 // Fast path for layouts with no backgrounds 18006 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18007 dispatchDraw(canvas); 18008 if (mOverlay != null && !mOverlay.isEmpty()) { 18009 mOverlay.getOverlayView().draw(canvas); 18010 } 18011 } else { 18012 draw(canvas); 18013 } 18014 18015 mPrivateFlags = flags; 18016 18017 canvas.restoreToCount(restoreCount); 18018 canvas.setBitmap(null); 18019 canvas.setHwBitmapsInSwModeEnabled(enabledHwBitmapsInSwMode); 18020 18021 if (attachInfo != null) { 18022 // Restore the cached Canvas for our siblings 18023 attachInfo.mCanvas = canvas; 18024 } 18025 18026 return bitmap; 18027 } 18028 18029 /** 18030 * Indicates whether this View is currently in edit mode. A View is usually 18031 * in edit mode when displayed within a developer tool. For instance, if 18032 * this View is being drawn by a visual user interface builder, this method 18033 * should return true. 18034 * 18035 * Subclasses should check the return value of this method to provide 18036 * different behaviors if their normal behavior might interfere with the 18037 * host environment. For instance: the class spawns a thread in its 18038 * constructor, the drawing code relies on device-specific features, etc. 18039 * 18040 * This method is usually checked in the drawing code of custom widgets. 18041 * 18042 * @return True if this View is in edit mode, false otherwise. 18043 */ 18044 public boolean isInEditMode() { 18045 return false; 18046 } 18047 18048 /** 18049 * If the View draws content inside its padding and enables fading edges, 18050 * it needs to support padding offsets. Padding offsets are added to the 18051 * fading edges to extend the length of the fade so that it covers pixels 18052 * drawn inside the padding. 18053 * 18054 * Subclasses of this class should override this method if they need 18055 * to draw content inside the padding. 18056 * 18057 * @return True if padding offset must be applied, false otherwise. 18058 * 18059 * @see #getLeftPaddingOffset() 18060 * @see #getRightPaddingOffset() 18061 * @see #getTopPaddingOffset() 18062 * @see #getBottomPaddingOffset() 18063 * 18064 * @since CURRENT 18065 */ 18066 protected boolean isPaddingOffsetRequired() { 18067 return false; 18068 } 18069 18070 /** 18071 * Amount by which to extend the left fading region. Called only when 18072 * {@link #isPaddingOffsetRequired()} returns true. 18073 * 18074 * @return The left padding offset in pixels. 18075 * 18076 * @see #isPaddingOffsetRequired() 18077 * 18078 * @since CURRENT 18079 */ 18080 protected int getLeftPaddingOffset() { 18081 return 0; 18082 } 18083 18084 /** 18085 * Amount by which to extend the right fading region. Called only when 18086 * {@link #isPaddingOffsetRequired()} returns true. 18087 * 18088 * @return The right padding offset in pixels. 18089 * 18090 * @see #isPaddingOffsetRequired() 18091 * 18092 * @since CURRENT 18093 */ 18094 protected int getRightPaddingOffset() { 18095 return 0; 18096 } 18097 18098 /** 18099 * Amount by which to extend the top fading region. Called only when 18100 * {@link #isPaddingOffsetRequired()} returns true. 18101 * 18102 * @return The top padding offset in pixels. 18103 * 18104 * @see #isPaddingOffsetRequired() 18105 * 18106 * @since CURRENT 18107 */ 18108 protected int getTopPaddingOffset() { 18109 return 0; 18110 } 18111 18112 /** 18113 * Amount by which to extend the bottom fading region. Called only when 18114 * {@link #isPaddingOffsetRequired()} returns true. 18115 * 18116 * @return The bottom padding offset in pixels. 18117 * 18118 * @see #isPaddingOffsetRequired() 18119 * 18120 * @since CURRENT 18121 */ 18122 protected int getBottomPaddingOffset() { 18123 return 0; 18124 } 18125 18126 /** 18127 * @hide 18128 * @param offsetRequired 18129 */ 18130 protected int getFadeTop(boolean offsetRequired) { 18131 int top = mPaddingTop; 18132 if (offsetRequired) top += getTopPaddingOffset(); 18133 return top; 18134 } 18135 18136 /** 18137 * @hide 18138 * @param offsetRequired 18139 */ 18140 protected int getFadeHeight(boolean offsetRequired) { 18141 int padding = mPaddingTop; 18142 if (offsetRequired) padding += getTopPaddingOffset(); 18143 return mBottom - mTop - mPaddingBottom - padding; 18144 } 18145 18146 /** 18147 * <p>Indicates whether this view is attached to a hardware accelerated 18148 * window or not.</p> 18149 * 18150 * <p>Even if this method returns true, it does not mean that every call 18151 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 18152 * accelerated {@link android.graphics.Canvas}. For instance, if this view 18153 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 18154 * window is hardware accelerated, 18155 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 18156 * return false, and this method will return true.</p> 18157 * 18158 * @return True if the view is attached to a window and the window is 18159 * hardware accelerated; false in any other case. 18160 */ 18161 @ViewDebug.ExportedProperty(category = "drawing") 18162 public boolean isHardwareAccelerated() { 18163 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 18164 } 18165 18166 /** 18167 * Sets a rectangular area on this view to which the view will be clipped 18168 * when it is drawn. Setting the value to null will remove the clip bounds 18169 * and the view will draw normally, using its full bounds. 18170 * 18171 * @param clipBounds The rectangular area, in the local coordinates of 18172 * this view, to which future drawing operations will be clipped. 18173 */ 18174 public void setClipBounds(Rect clipBounds) { 18175 if (clipBounds == mClipBounds 18176 || (clipBounds != null && clipBounds.equals(mClipBounds))) { 18177 return; 18178 } 18179 if (clipBounds != null) { 18180 if (mClipBounds == null) { 18181 mClipBounds = new Rect(clipBounds); 18182 } else { 18183 mClipBounds.set(clipBounds); 18184 } 18185 } else { 18186 mClipBounds = null; 18187 } 18188 mRenderNode.setClipBounds(mClipBounds); 18189 invalidateViewProperty(false, false); 18190 } 18191 18192 /** 18193 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 18194 * 18195 * @return A copy of the current clip bounds if clip bounds are set, 18196 * otherwise null. 18197 */ 18198 public Rect getClipBounds() { 18199 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 18200 } 18201 18202 18203 /** 18204 * Populates an output rectangle with the clip bounds of the view, 18205 * returning {@code true} if successful or {@code false} if the view's 18206 * clip bounds are {@code null}. 18207 * 18208 * @param outRect rectangle in which to place the clip bounds of the view 18209 * @return {@code true} if successful or {@code false} if the view's 18210 * clip bounds are {@code null} 18211 */ 18212 public boolean getClipBounds(Rect outRect) { 18213 if (mClipBounds != null) { 18214 outRect.set(mClipBounds); 18215 return true; 18216 } 18217 return false; 18218 } 18219 18220 /** 18221 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 18222 * case of an active Animation being run on the view. 18223 */ 18224 private boolean applyLegacyAnimation(ViewGroup parent, long drawingTime, 18225 Animation a, boolean scalingRequired) { 18226 Transformation invalidationTransform; 18227 final int flags = parent.mGroupFlags; 18228 final boolean initialized = a.isInitialized(); 18229 if (!initialized) { 18230 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 18231 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 18232 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 18233 onAnimationStart(); 18234 } 18235 18236 final Transformation t = parent.getChildTransformation(); 18237 boolean more = a.getTransformation(drawingTime, t, 1f); 18238 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 18239 if (parent.mInvalidationTransformation == null) { 18240 parent.mInvalidationTransformation = new Transformation(); 18241 } 18242 invalidationTransform = parent.mInvalidationTransformation; 18243 a.getTransformation(drawingTime, invalidationTransform, 1f); 18244 } else { 18245 invalidationTransform = t; 18246 } 18247 18248 if (more) { 18249 if (!a.willChangeBounds()) { 18250 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 18251 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 18252 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 18253 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 18254 // The child need to draw an animation, potentially offscreen, so 18255 // make sure we do not cancel invalidate requests 18256 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 18257 parent.invalidate(mLeft, mTop, mRight, mBottom); 18258 } 18259 } else { 18260 if (parent.mInvalidateRegion == null) { 18261 parent.mInvalidateRegion = new RectF(); 18262 } 18263 final RectF region = parent.mInvalidateRegion; 18264 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 18265 invalidationTransform); 18266 18267 // The child need to draw an animation, potentially offscreen, so 18268 // make sure we do not cancel invalidate requests 18269 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 18270 18271 final int left = mLeft + (int) region.left; 18272 final int top = mTop + (int) region.top; 18273 parent.invalidate(left, top, left + (int) (region.width() + .5f), 18274 top + (int) (region.height() + .5f)); 18275 } 18276 } 18277 return more; 18278 } 18279 18280 /** 18281 * This method is called by getDisplayList() when a display list is recorded for a View. 18282 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 18283 */ 18284 void setDisplayListProperties(RenderNode renderNode) { 18285 if (renderNode != null) { 18286 renderNode.setHasOverlappingRendering(getHasOverlappingRendering()); 18287 renderNode.setClipToBounds(mParent instanceof ViewGroup 18288 && ((ViewGroup) mParent).getClipChildren()); 18289 18290 float alpha = 1; 18291 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 18292 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 18293 ViewGroup parentVG = (ViewGroup) mParent; 18294 final Transformation t = parentVG.getChildTransformation(); 18295 if (parentVG.getChildStaticTransformation(this, t)) { 18296 final int transformType = t.getTransformationType(); 18297 if (transformType != Transformation.TYPE_IDENTITY) { 18298 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 18299 alpha = t.getAlpha(); 18300 } 18301 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 18302 renderNode.setStaticMatrix(t.getMatrix()); 18303 } 18304 } 18305 } 18306 } 18307 if (mTransformationInfo != null) { 18308 alpha *= getFinalAlpha(); 18309 if (alpha < 1) { 18310 final int multipliedAlpha = (int) (255 * alpha); 18311 if (onSetAlpha(multipliedAlpha)) { 18312 alpha = 1; 18313 } 18314 } 18315 renderNode.setAlpha(alpha); 18316 } else if (alpha < 1) { 18317 renderNode.setAlpha(alpha); 18318 } 18319 } 18320 } 18321 18322 /** 18323 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 18324 * 18325 * This is where the View specializes rendering behavior based on layer type, 18326 * and hardware acceleration. 18327 */ 18328 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 18329 final boolean hardwareAcceleratedCanvas = canvas.isHardwareAccelerated(); 18330 /* If an attached view draws to a HW canvas, it may use its RenderNode + DisplayList. 18331 * 18332 * If a view is dettached, its DisplayList shouldn't exist. If the canvas isn't 18333 * HW accelerated, it can't handle drawing RenderNodes. 18334 */ 18335 boolean drawingWithRenderNode = mAttachInfo != null 18336 && mAttachInfo.mHardwareAccelerated 18337 && hardwareAcceleratedCanvas; 18338 18339 boolean more = false; 18340 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 18341 final int parentFlags = parent.mGroupFlags; 18342 18343 if ((parentFlags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) != 0) { 18344 parent.getChildTransformation().clear(); 18345 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18346 } 18347 18348 Transformation transformToApply = null; 18349 boolean concatMatrix = false; 18350 final boolean scalingRequired = mAttachInfo != null && mAttachInfo.mScalingRequired; 18351 final Animation a = getAnimation(); 18352 if (a != null) { 18353 more = applyLegacyAnimation(parent, drawingTime, a, scalingRequired); 18354 concatMatrix = a.willChangeTransformationMatrix(); 18355 if (concatMatrix) { 18356 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 18357 } 18358 transformToApply = parent.getChildTransformation(); 18359 } else { 18360 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 18361 // No longer animating: clear out old animation matrix 18362 mRenderNode.setAnimationMatrix(null); 18363 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 18364 } 18365 if (!drawingWithRenderNode 18366 && (parentFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 18367 final Transformation t = parent.getChildTransformation(); 18368 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 18369 if (hasTransform) { 18370 final int transformType = t.getTransformationType(); 18371 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 18372 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 18373 } 18374 } 18375 } 18376 18377 concatMatrix |= !childHasIdentityMatrix; 18378 18379 // Sets the flag as early as possible to allow draw() implementations 18380 // to call invalidate() successfully when doing animations 18381 mPrivateFlags |= PFLAG_DRAWN; 18382 18383 if (!concatMatrix && 18384 (parentFlags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 18385 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 18386 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 18387 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 18388 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 18389 return more; 18390 } 18391 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 18392 18393 if (hardwareAcceleratedCanvas) { 18394 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 18395 // retain the flag's value temporarily in the mRecreateDisplayList flag 18396 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) != 0; 18397 mPrivateFlags &= ~PFLAG_INVALIDATED; 18398 } 18399 18400 RenderNode renderNode = null; 18401 Bitmap cache = null; 18402 int layerType = getLayerType(); // TODO: signify cache state with just 'cache' local 18403 if (layerType == LAYER_TYPE_SOFTWARE || !drawingWithRenderNode) { 18404 if (layerType != LAYER_TYPE_NONE) { 18405 // If not drawing with RenderNode, treat HW layers as SW 18406 layerType = LAYER_TYPE_SOFTWARE; 18407 buildDrawingCache(true); 18408 } 18409 cache = getDrawingCache(true); 18410 } 18411 18412 if (drawingWithRenderNode) { 18413 // Delay getting the display list until animation-driven alpha values are 18414 // set up and possibly passed on to the view 18415 renderNode = updateDisplayListIfDirty(); 18416 if (!renderNode.isValid()) { 18417 // Uncommon, but possible. If a view is removed from the hierarchy during the call 18418 // to getDisplayList(), the display list will be marked invalid and we should not 18419 // try to use it again. 18420 renderNode = null; 18421 drawingWithRenderNode = false; 18422 } 18423 } 18424 18425 int sx = 0; 18426 int sy = 0; 18427 if (!drawingWithRenderNode) { 18428 computeScroll(); 18429 sx = mScrollX; 18430 sy = mScrollY; 18431 } 18432 18433 final boolean drawingWithDrawingCache = cache != null && !drawingWithRenderNode; 18434 final boolean offsetForScroll = cache == null && !drawingWithRenderNode; 18435 18436 int restoreTo = -1; 18437 if (!drawingWithRenderNode || transformToApply != null) { 18438 restoreTo = canvas.save(); 18439 } 18440 if (offsetForScroll) { 18441 canvas.translate(mLeft - sx, mTop - sy); 18442 } else { 18443 if (!drawingWithRenderNode) { 18444 canvas.translate(mLeft, mTop); 18445 } 18446 if (scalingRequired) { 18447 if (drawingWithRenderNode) { 18448 // TODO: Might not need this if we put everything inside the DL 18449 restoreTo = canvas.save(); 18450 } 18451 // mAttachInfo cannot be null, otherwise scalingRequired == false 18452 final float scale = 1.0f / mAttachInfo.mApplicationScale; 18453 canvas.scale(scale, scale); 18454 } 18455 } 18456 18457 float alpha = drawingWithRenderNode ? 1 : (getAlpha() * getTransitionAlpha()); 18458 if (transformToApply != null 18459 || alpha < 1 18460 || !hasIdentityMatrix() 18461 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 18462 if (transformToApply != null || !childHasIdentityMatrix) { 18463 int transX = 0; 18464 int transY = 0; 18465 18466 if (offsetForScroll) { 18467 transX = -sx; 18468 transY = -sy; 18469 } 18470 18471 if (transformToApply != null) { 18472 if (concatMatrix) { 18473 if (drawingWithRenderNode) { 18474 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 18475 } else { 18476 // Undo the scroll translation, apply the transformation matrix, 18477 // then redo the scroll translate to get the correct result. 18478 canvas.translate(-transX, -transY); 18479 canvas.concat(transformToApply.getMatrix()); 18480 canvas.translate(transX, transY); 18481 } 18482 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18483 } 18484 18485 float transformAlpha = transformToApply.getAlpha(); 18486 if (transformAlpha < 1) { 18487 alpha *= transformAlpha; 18488 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18489 } 18490 } 18491 18492 if (!childHasIdentityMatrix && !drawingWithRenderNode) { 18493 canvas.translate(-transX, -transY); 18494 canvas.concat(getMatrix()); 18495 canvas.translate(transX, transY); 18496 } 18497 } 18498 18499 // Deal with alpha if it is or used to be <1 18500 if (alpha < 1 || (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) != 0) { 18501 if (alpha < 1) { 18502 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 18503 } else { 18504 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 18505 } 18506 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 18507 if (!drawingWithDrawingCache) { 18508 final int multipliedAlpha = (int) (255 * alpha); 18509 if (!onSetAlpha(multipliedAlpha)) { 18510 if (drawingWithRenderNode) { 18511 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 18512 } else if (layerType == LAYER_TYPE_NONE) { 18513 canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(), 18514 multipliedAlpha); 18515 } 18516 } else { 18517 // Alpha is handled by the child directly, clobber the layer's alpha 18518 mPrivateFlags |= PFLAG_ALPHA_SET; 18519 } 18520 } 18521 } 18522 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 18523 onSetAlpha(255); 18524 mPrivateFlags &= ~PFLAG_ALPHA_SET; 18525 } 18526 18527 if (!drawingWithRenderNode) { 18528 // apply clips directly, since RenderNode won't do it for this draw 18529 if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 && cache == null) { 18530 if (offsetForScroll) { 18531 canvas.clipRect(sx, sy, sx + getWidth(), sy + getHeight()); 18532 } else { 18533 if (!scalingRequired || cache == null) { 18534 canvas.clipRect(0, 0, getWidth(), getHeight()); 18535 } else { 18536 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 18537 } 18538 } 18539 } 18540 18541 if (mClipBounds != null) { 18542 // clip bounds ignore scroll 18543 canvas.clipRect(mClipBounds); 18544 } 18545 } 18546 18547 if (!drawingWithDrawingCache) { 18548 if (drawingWithRenderNode) { 18549 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18550 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 18551 } else { 18552 // Fast path for layouts with no backgrounds 18553 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 18554 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18555 dispatchDraw(canvas); 18556 } else { 18557 draw(canvas); 18558 } 18559 } 18560 } else if (cache != null) { 18561 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 18562 if (layerType == LAYER_TYPE_NONE || mLayerPaint == null) { 18563 // no layer paint, use temporary paint to draw bitmap 18564 Paint cachePaint = parent.mCachePaint; 18565 if (cachePaint == null) { 18566 cachePaint = new Paint(); 18567 cachePaint.setDither(false); 18568 parent.mCachePaint = cachePaint; 18569 } 18570 cachePaint.setAlpha((int) (alpha * 255)); 18571 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 18572 } else { 18573 // use layer paint to draw the bitmap, merging the two alphas, but also restore 18574 int layerPaintAlpha = mLayerPaint.getAlpha(); 18575 if (alpha < 1) { 18576 mLayerPaint.setAlpha((int) (alpha * layerPaintAlpha)); 18577 } 18578 canvas.drawBitmap(cache, 0.0f, 0.0f, mLayerPaint); 18579 if (alpha < 1) { 18580 mLayerPaint.setAlpha(layerPaintAlpha); 18581 } 18582 } 18583 } 18584 18585 if (restoreTo >= 0) { 18586 canvas.restoreToCount(restoreTo); 18587 } 18588 18589 if (a != null && !more) { 18590 if (!hardwareAcceleratedCanvas && !a.getFillAfter()) { 18591 onSetAlpha(255); 18592 } 18593 parent.finishAnimatingView(this, a); 18594 } 18595 18596 if (more && hardwareAcceleratedCanvas) { 18597 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 18598 // alpha animations should cause the child to recreate its display list 18599 invalidate(true); 18600 } 18601 } 18602 18603 mRecreateDisplayList = false; 18604 18605 return more; 18606 } 18607 18608 static Paint getDebugPaint() { 18609 if (sDebugPaint == null) { 18610 sDebugPaint = new Paint(); 18611 sDebugPaint.setAntiAlias(false); 18612 } 18613 return sDebugPaint; 18614 } 18615 18616 final int dipsToPixels(int dips) { 18617 float scale = getContext().getResources().getDisplayMetrics().density; 18618 return (int) (dips * scale + 0.5f); 18619 } 18620 18621 final private void debugDrawFocus(Canvas canvas) { 18622 if (isFocused()) { 18623 final int cornerSquareSize = dipsToPixels(DEBUG_CORNERS_SIZE_DIP); 18624 final int l = mScrollX; 18625 final int r = l + mRight - mLeft; 18626 final int t = mScrollY; 18627 final int b = t + mBottom - mTop; 18628 18629 final Paint paint = getDebugPaint(); 18630 paint.setColor(DEBUG_CORNERS_COLOR); 18631 18632 // Draw squares in corners. 18633 paint.setStyle(Paint.Style.FILL); 18634 canvas.drawRect(l, t, l + cornerSquareSize, t + cornerSquareSize, paint); 18635 canvas.drawRect(r - cornerSquareSize, t, r, t + cornerSquareSize, paint); 18636 canvas.drawRect(l, b - cornerSquareSize, l + cornerSquareSize, b, paint); 18637 canvas.drawRect(r - cornerSquareSize, b - cornerSquareSize, r, b, paint); 18638 18639 // Draw big X across the view. 18640 paint.setStyle(Paint.Style.STROKE); 18641 canvas.drawLine(l, t, r, b, paint); 18642 canvas.drawLine(l, b, r, t, paint); 18643 } 18644 } 18645 18646 /** 18647 * Manually render this view (and all of its children) to the given Canvas. 18648 * The view must have already done a full layout before this function is 18649 * called. When implementing a view, implement 18650 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 18651 * If you do need to override this method, call the superclass version. 18652 * 18653 * @param canvas The Canvas to which the View is rendered. 18654 */ 18655 @CallSuper 18656 public void draw(Canvas canvas) { 18657 final int privateFlags = mPrivateFlags; 18658 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 18659 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 18660 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 18661 18662 /* 18663 * Draw traversal performs several drawing steps which must be executed 18664 * in the appropriate order: 18665 * 18666 * 1. Draw the background 18667 * 2. If necessary, save the canvas' layers to prepare for fading 18668 * 3. Draw view's content 18669 * 4. Draw children 18670 * 5. If necessary, draw the fading edges and restore layers 18671 * 6. Draw decorations (scrollbars for instance) 18672 */ 18673 18674 // Step 1, draw the background, if needed 18675 int saveCount; 18676 18677 if (!dirtyOpaque) { 18678 drawBackground(canvas); 18679 } 18680 18681 // skip step 2 & 5 if possible (common case) 18682 final int viewFlags = mViewFlags; 18683 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 18684 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 18685 if (!verticalEdges && !horizontalEdges) { 18686 // Step 3, draw the content 18687 if (!dirtyOpaque) onDraw(canvas); 18688 18689 // Step 4, draw the children 18690 dispatchDraw(canvas); 18691 18692 // Overlay is part of the content and draws beneath Foreground 18693 if (mOverlay != null && !mOverlay.isEmpty()) { 18694 mOverlay.getOverlayView().dispatchDraw(canvas); 18695 } 18696 18697 // Step 6, draw decorations (foreground, scrollbars) 18698 onDrawForeground(canvas); 18699 18700 // Step 7, draw the default focus highlight 18701 drawDefaultFocusHighlight(canvas); 18702 18703 if (debugDraw()) { 18704 debugDrawFocus(canvas); 18705 } 18706 18707 // we're done... 18708 return; 18709 } 18710 18711 /* 18712 * Here we do the full fledged routine... 18713 * (this is an uncommon case where speed matters less, 18714 * this is why we repeat some of the tests that have been 18715 * done above) 18716 */ 18717 18718 boolean drawTop = false; 18719 boolean drawBottom = false; 18720 boolean drawLeft = false; 18721 boolean drawRight = false; 18722 18723 float topFadeStrength = 0.0f; 18724 float bottomFadeStrength = 0.0f; 18725 float leftFadeStrength = 0.0f; 18726 float rightFadeStrength = 0.0f; 18727 18728 // Step 2, save the canvas' layers 18729 int paddingLeft = mPaddingLeft; 18730 18731 final boolean offsetRequired = isPaddingOffsetRequired(); 18732 if (offsetRequired) { 18733 paddingLeft += getLeftPaddingOffset(); 18734 } 18735 18736 int left = mScrollX + paddingLeft; 18737 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 18738 int top = mScrollY + getFadeTop(offsetRequired); 18739 int bottom = top + getFadeHeight(offsetRequired); 18740 18741 if (offsetRequired) { 18742 right += getRightPaddingOffset(); 18743 bottom += getBottomPaddingOffset(); 18744 } 18745 18746 final ScrollabilityCache scrollabilityCache = mScrollCache; 18747 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 18748 int length = (int) fadeHeight; 18749 18750 // clip the fade length if top and bottom fades overlap 18751 // overlapping fades produce odd-looking artifacts 18752 if (verticalEdges && (top + length > bottom - length)) { 18753 length = (bottom - top) / 2; 18754 } 18755 18756 // also clip horizontal fades if necessary 18757 if (horizontalEdges && (left + length > right - length)) { 18758 length = (right - left) / 2; 18759 } 18760 18761 if (verticalEdges) { 18762 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 18763 drawTop = topFadeStrength * fadeHeight > 1.0f; 18764 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 18765 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 18766 } 18767 18768 if (horizontalEdges) { 18769 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 18770 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 18771 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 18772 drawRight = rightFadeStrength * fadeHeight > 1.0f; 18773 } 18774 18775 saveCount = canvas.getSaveCount(); 18776 18777 int solidColor = getSolidColor(); 18778 if (solidColor == 0) { 18779 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 18780 18781 if (drawTop) { 18782 canvas.saveLayer(left, top, right, top + length, null, flags); 18783 } 18784 18785 if (drawBottom) { 18786 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 18787 } 18788 18789 if (drawLeft) { 18790 canvas.saveLayer(left, top, left + length, bottom, null, flags); 18791 } 18792 18793 if (drawRight) { 18794 canvas.saveLayer(right - length, top, right, bottom, null, flags); 18795 } 18796 } else { 18797 scrollabilityCache.setFadeColor(solidColor); 18798 } 18799 18800 // Step 3, draw the content 18801 if (!dirtyOpaque) onDraw(canvas); 18802 18803 // Step 4, draw the children 18804 dispatchDraw(canvas); 18805 18806 // Step 5, draw the fade effect and restore layers 18807 final Paint p = scrollabilityCache.paint; 18808 final Matrix matrix = scrollabilityCache.matrix; 18809 final Shader fade = scrollabilityCache.shader; 18810 18811 if (drawTop) { 18812 matrix.setScale(1, fadeHeight * topFadeStrength); 18813 matrix.postTranslate(left, top); 18814 fade.setLocalMatrix(matrix); 18815 p.setShader(fade); 18816 canvas.drawRect(left, top, right, top + length, p); 18817 } 18818 18819 if (drawBottom) { 18820 matrix.setScale(1, fadeHeight * bottomFadeStrength); 18821 matrix.postRotate(180); 18822 matrix.postTranslate(left, bottom); 18823 fade.setLocalMatrix(matrix); 18824 p.setShader(fade); 18825 canvas.drawRect(left, bottom - length, right, bottom, p); 18826 } 18827 18828 if (drawLeft) { 18829 matrix.setScale(1, fadeHeight * leftFadeStrength); 18830 matrix.postRotate(-90); 18831 matrix.postTranslate(left, top); 18832 fade.setLocalMatrix(matrix); 18833 p.setShader(fade); 18834 canvas.drawRect(left, top, left + length, bottom, p); 18835 } 18836 18837 if (drawRight) { 18838 matrix.setScale(1, fadeHeight * rightFadeStrength); 18839 matrix.postRotate(90); 18840 matrix.postTranslate(right, top); 18841 fade.setLocalMatrix(matrix); 18842 p.setShader(fade); 18843 canvas.drawRect(right - length, top, right, bottom, p); 18844 } 18845 18846 canvas.restoreToCount(saveCount); 18847 18848 // Overlay is part of the content and draws beneath Foreground 18849 if (mOverlay != null && !mOverlay.isEmpty()) { 18850 mOverlay.getOverlayView().dispatchDraw(canvas); 18851 } 18852 18853 // Step 6, draw decorations (foreground, scrollbars) 18854 onDrawForeground(canvas); 18855 18856 if (debugDraw()) { 18857 debugDrawFocus(canvas); 18858 } 18859 } 18860 18861 /** 18862 * Draws the background onto the specified canvas. 18863 * 18864 * @param canvas Canvas on which to draw the background 18865 */ 18866 private void drawBackground(Canvas canvas) { 18867 final Drawable background = mBackground; 18868 if (background == null) { 18869 return; 18870 } 18871 18872 setBackgroundBounds(); 18873 18874 // Attempt to use a display list if requested. 18875 if (canvas.isHardwareAccelerated() && mAttachInfo != null 18876 && mAttachInfo.mThreadedRenderer != null) { 18877 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 18878 18879 final RenderNode renderNode = mBackgroundRenderNode; 18880 if (renderNode != null && renderNode.isValid()) { 18881 setBackgroundRenderNodeProperties(renderNode); 18882 ((DisplayListCanvas) canvas).drawRenderNode(renderNode); 18883 return; 18884 } 18885 } 18886 18887 final int scrollX = mScrollX; 18888 final int scrollY = mScrollY; 18889 if ((scrollX | scrollY) == 0) { 18890 background.draw(canvas); 18891 } else { 18892 canvas.translate(scrollX, scrollY); 18893 background.draw(canvas); 18894 canvas.translate(-scrollX, -scrollY); 18895 } 18896 } 18897 18898 /** 18899 * Sets the correct background bounds and rebuilds the outline, if needed. 18900 * <p/> 18901 * This is called by LayoutLib. 18902 */ 18903 void setBackgroundBounds() { 18904 if (mBackgroundSizeChanged && mBackground != null) { 18905 mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 18906 mBackgroundSizeChanged = false; 18907 rebuildOutline(); 18908 } 18909 } 18910 18911 private void setBackgroundRenderNodeProperties(RenderNode renderNode) { 18912 renderNode.setTranslationX(mScrollX); 18913 renderNode.setTranslationY(mScrollY); 18914 } 18915 18916 /** 18917 * Creates a new display list or updates the existing display list for the 18918 * specified Drawable. 18919 * 18920 * @param drawable Drawable for which to create a display list 18921 * @param renderNode Existing RenderNode, or {@code null} 18922 * @return A valid display list for the specified drawable 18923 */ 18924 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 18925 if (renderNode == null) { 18926 renderNode = RenderNode.create(drawable.getClass().getName(), this); 18927 } 18928 18929 final Rect bounds = drawable.getBounds(); 18930 final int width = bounds.width(); 18931 final int height = bounds.height(); 18932 final DisplayListCanvas canvas = renderNode.start(width, height); 18933 18934 // Reverse left/top translation done by drawable canvas, which will 18935 // instead be applied by rendernode's LTRB bounds below. This way, the 18936 // drawable's bounds match with its rendernode bounds and its content 18937 // will lie within those bounds in the rendernode tree. 18938 canvas.translate(-bounds.left, -bounds.top); 18939 18940 try { 18941 drawable.draw(canvas); 18942 } finally { 18943 renderNode.end(canvas); 18944 } 18945 18946 // Set up drawable properties that are view-independent. 18947 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 18948 renderNode.setProjectBackwards(drawable.isProjected()); 18949 renderNode.setProjectionReceiver(true); 18950 renderNode.setClipToBounds(false); 18951 return renderNode; 18952 } 18953 18954 /** 18955 * Returns the overlay for this view, creating it if it does not yet exist. 18956 * Adding drawables to the overlay will cause them to be displayed whenever 18957 * the view itself is redrawn. Objects in the overlay should be actively 18958 * managed: remove them when they should not be displayed anymore. The 18959 * overlay will always have the same size as its host view. 18960 * 18961 * <p>Note: Overlays do not currently work correctly with {@link 18962 * SurfaceView} or {@link TextureView}; contents in overlays for these 18963 * types of views may not display correctly.</p> 18964 * 18965 * @return The ViewOverlay object for this view. 18966 * @see ViewOverlay 18967 */ 18968 public ViewOverlay getOverlay() { 18969 if (mOverlay == null) { 18970 mOverlay = new ViewOverlay(mContext, this); 18971 } 18972 return mOverlay; 18973 } 18974 18975 /** 18976 * Override this if your view is known to always be drawn on top of a solid color background, 18977 * and needs to draw fading edges. Returning a non-zero color enables the view system to 18978 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 18979 * should be set to 0xFF. 18980 * 18981 * @see #setVerticalFadingEdgeEnabled(boolean) 18982 * @see #setHorizontalFadingEdgeEnabled(boolean) 18983 * 18984 * @return The known solid color background for this view, or 0 if the color may vary 18985 */ 18986 @ViewDebug.ExportedProperty(category = "drawing") 18987 @ColorInt 18988 public int getSolidColor() { 18989 return 0; 18990 } 18991 18992 /** 18993 * Build a human readable string representation of the specified view flags. 18994 * 18995 * @param flags the view flags to convert to a string 18996 * @return a String representing the supplied flags 18997 */ 18998 private static String printFlags(int flags) { 18999 String output = ""; 19000 int numFlags = 0; 19001 if ((flags & FOCUSABLE) == FOCUSABLE) { 19002 output += "TAKES_FOCUS"; 19003 numFlags++; 19004 } 19005 19006 switch (flags & VISIBILITY_MASK) { 19007 case INVISIBLE: 19008 if (numFlags > 0) { 19009 output += " "; 19010 } 19011 output += "INVISIBLE"; 19012 // USELESS HERE numFlags++; 19013 break; 19014 case GONE: 19015 if (numFlags > 0) { 19016 output += " "; 19017 } 19018 output += "GONE"; 19019 // USELESS HERE numFlags++; 19020 break; 19021 default: 19022 break; 19023 } 19024 return output; 19025 } 19026 19027 /** 19028 * Build a human readable string representation of the specified private 19029 * view flags. 19030 * 19031 * @param privateFlags the private view flags to convert to a string 19032 * @return a String representing the supplied flags 19033 */ 19034 private static String printPrivateFlags(int privateFlags) { 19035 String output = ""; 19036 int numFlags = 0; 19037 19038 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 19039 output += "WANTS_FOCUS"; 19040 numFlags++; 19041 } 19042 19043 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 19044 if (numFlags > 0) { 19045 output += " "; 19046 } 19047 output += "FOCUSED"; 19048 numFlags++; 19049 } 19050 19051 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 19052 if (numFlags > 0) { 19053 output += " "; 19054 } 19055 output += "SELECTED"; 19056 numFlags++; 19057 } 19058 19059 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 19060 if (numFlags > 0) { 19061 output += " "; 19062 } 19063 output += "IS_ROOT_NAMESPACE"; 19064 numFlags++; 19065 } 19066 19067 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 19068 if (numFlags > 0) { 19069 output += " "; 19070 } 19071 output += "HAS_BOUNDS"; 19072 numFlags++; 19073 } 19074 19075 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 19076 if (numFlags > 0) { 19077 output += " "; 19078 } 19079 output += "DRAWN"; 19080 // USELESS HERE numFlags++; 19081 } 19082 return output; 19083 } 19084 19085 /** 19086 * <p>Indicates whether or not this view's layout will be requested during 19087 * the next hierarchy layout pass.</p> 19088 * 19089 * @return true if the layout will be forced during next layout pass 19090 */ 19091 public boolean isLayoutRequested() { 19092 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 19093 } 19094 19095 /** 19096 * Return true if o is a ViewGroup that is laying out using optical bounds. 19097 * @hide 19098 */ 19099 public static boolean isLayoutModeOptical(Object o) { 19100 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 19101 } 19102 19103 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 19104 Insets parentInsets = mParent instanceof View ? 19105 ((View) mParent).getOpticalInsets() : Insets.NONE; 19106 Insets childInsets = getOpticalInsets(); 19107 return setFrame( 19108 left + parentInsets.left - childInsets.left, 19109 top + parentInsets.top - childInsets.top, 19110 right + parentInsets.left + childInsets.right, 19111 bottom + parentInsets.top + childInsets.bottom); 19112 } 19113 19114 /** 19115 * Assign a size and position to a view and all of its 19116 * descendants 19117 * 19118 * <p>This is the second phase of the layout mechanism. 19119 * (The first is measuring). In this phase, each parent calls 19120 * layout on all of its children to position them. 19121 * This is typically done using the child measurements 19122 * that were stored in the measure pass().</p> 19123 * 19124 * <p>Derived classes should not override this method. 19125 * Derived classes with children should override 19126 * onLayout. In that method, they should 19127 * call layout on each of their children.</p> 19128 * 19129 * @param l Left position, relative to parent 19130 * @param t Top position, relative to parent 19131 * @param r Right position, relative to parent 19132 * @param b Bottom position, relative to parent 19133 */ 19134 @SuppressWarnings({"unchecked"}) 19135 public void layout(int l, int t, int r, int b) { 19136 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 19137 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 19138 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 19139 } 19140 19141 int oldL = mLeft; 19142 int oldT = mTop; 19143 int oldB = mBottom; 19144 int oldR = mRight; 19145 19146 boolean changed = isLayoutModeOptical(mParent) ? 19147 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 19148 19149 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 19150 onLayout(changed, l, t, r, b); 19151 19152 if (shouldDrawRoundScrollbar()) { 19153 if(mRoundScrollbarRenderer == null) { 19154 mRoundScrollbarRenderer = new RoundScrollbarRenderer(this); 19155 } 19156 } else { 19157 mRoundScrollbarRenderer = null; 19158 } 19159 19160 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 19161 19162 ListenerInfo li = mListenerInfo; 19163 if (li != null && li.mOnLayoutChangeListeners != null) { 19164 ArrayList<OnLayoutChangeListener> listenersCopy = 19165 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 19166 int numListeners = listenersCopy.size(); 19167 for (int i = 0; i < numListeners; ++i) { 19168 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 19169 } 19170 } 19171 } 19172 19173 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 19174 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 19175 } 19176 19177 /** 19178 * Called from layout when this view should 19179 * assign a size and position to each of its children. 19180 * 19181 * Derived classes with children should override 19182 * this method and call layout on each of 19183 * their children. 19184 * @param changed This is a new size or position for this view 19185 * @param left Left position, relative to parent 19186 * @param top Top position, relative to parent 19187 * @param right Right position, relative to parent 19188 * @param bottom Bottom position, relative to parent 19189 */ 19190 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 19191 } 19192 19193 /** 19194 * Assign a size and position to this view. 19195 * 19196 * This is called from layout. 19197 * 19198 * @param left Left position, relative to parent 19199 * @param top Top position, relative to parent 19200 * @param right Right position, relative to parent 19201 * @param bottom Bottom position, relative to parent 19202 * @return true if the new size and position are different than the 19203 * previous ones 19204 * {@hide} 19205 */ 19206 protected boolean setFrame(int left, int top, int right, int bottom) { 19207 boolean changed = false; 19208 19209 if (DBG) { 19210 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 19211 + right + "," + bottom + ")"); 19212 } 19213 19214 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 19215 changed = true; 19216 19217 // Remember our drawn bit 19218 int drawn = mPrivateFlags & PFLAG_DRAWN; 19219 19220 int oldWidth = mRight - mLeft; 19221 int oldHeight = mBottom - mTop; 19222 int newWidth = right - left; 19223 int newHeight = bottom - top; 19224 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 19225 19226 // Invalidate our old position 19227 invalidate(sizeChanged); 19228 19229 mLeft = left; 19230 mTop = top; 19231 mRight = right; 19232 mBottom = bottom; 19233 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 19234 19235 mPrivateFlags |= PFLAG_HAS_BOUNDS; 19236 19237 19238 if (sizeChanged) { 19239 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 19240 } 19241 19242 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) { 19243 // If we are visible, force the DRAWN bit to on so that 19244 // this invalidate will go through (at least to our parent). 19245 // This is because someone may have invalidated this view 19246 // before this call to setFrame came in, thereby clearing 19247 // the DRAWN bit. 19248 mPrivateFlags |= PFLAG_DRAWN; 19249 invalidate(sizeChanged); 19250 // parent display list may need to be recreated based on a change in the bounds 19251 // of any child 19252 invalidateParentCaches(); 19253 } 19254 19255 // Reset drawn bit to original value (invalidate turns it off) 19256 mPrivateFlags |= drawn; 19257 19258 mBackgroundSizeChanged = true; 19259 mDefaultFocusHighlightSizeChanged = true; 19260 if (mForegroundInfo != null) { 19261 mForegroundInfo.mBoundsChanged = true; 19262 } 19263 19264 notifySubtreeAccessibilityStateChangedIfNeeded(); 19265 } 19266 return changed; 19267 } 19268 19269 /** 19270 * Same as setFrame, but public and hidden. For use in {@link android.transition.ChangeBounds}. 19271 * @hide 19272 */ 19273 public void setLeftTopRightBottom(int left, int top, int right, int bottom) { 19274 setFrame(left, top, right, bottom); 19275 } 19276 19277 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 19278 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 19279 if (mOverlay != null) { 19280 mOverlay.getOverlayView().setRight(newWidth); 19281 mOverlay.getOverlayView().setBottom(newHeight); 19282 } 19283 rebuildOutline(); 19284 } 19285 19286 /** 19287 * Finalize inflating a view from XML. This is called as the last phase 19288 * of inflation, after all child views have been added. 19289 * 19290 * <p>Even if the subclass overrides onFinishInflate, they should always be 19291 * sure to call the super method, so that we get called. 19292 */ 19293 @CallSuper 19294 protected void onFinishInflate() { 19295 } 19296 19297 /** 19298 * Returns the resources associated with this view. 19299 * 19300 * @return Resources object. 19301 */ 19302 public Resources getResources() { 19303 return mResources; 19304 } 19305 19306 /** 19307 * Invalidates the specified Drawable. 19308 * 19309 * @param drawable the drawable to invalidate 19310 */ 19311 @Override 19312 public void invalidateDrawable(@NonNull Drawable drawable) { 19313 if (verifyDrawable(drawable)) { 19314 final Rect dirty = drawable.getDirtyBounds(); 19315 final int scrollX = mScrollX; 19316 final int scrollY = mScrollY; 19317 19318 invalidate(dirty.left + scrollX, dirty.top + scrollY, 19319 dirty.right + scrollX, dirty.bottom + scrollY); 19320 rebuildOutline(); 19321 } 19322 } 19323 19324 /** 19325 * Schedules an action on a drawable to occur at a specified time. 19326 * 19327 * @param who the recipient of the action 19328 * @param what the action to run on the drawable 19329 * @param when the time at which the action must occur. Uses the 19330 * {@link SystemClock#uptimeMillis} timebase. 19331 */ 19332 @Override 19333 public void scheduleDrawable(@NonNull Drawable who, @NonNull Runnable what, long when) { 19334 if (verifyDrawable(who) && what != null) { 19335 final long delay = when - SystemClock.uptimeMillis(); 19336 if (mAttachInfo != null) { 19337 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 19338 Choreographer.CALLBACK_ANIMATION, what, who, 19339 Choreographer.subtractFrameDelay(delay)); 19340 } else { 19341 // Postpone the runnable until we know 19342 // on which thread it needs to run. 19343 getRunQueue().postDelayed(what, delay); 19344 } 19345 } 19346 } 19347 19348 /** 19349 * Cancels a scheduled action on a drawable. 19350 * 19351 * @param who the recipient of the action 19352 * @param what the action to cancel 19353 */ 19354 @Override 19355 public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) { 19356 if (verifyDrawable(who) && what != null) { 19357 if (mAttachInfo != null) { 19358 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 19359 Choreographer.CALLBACK_ANIMATION, what, who); 19360 } 19361 getRunQueue().removeCallbacks(what); 19362 } 19363 } 19364 19365 /** 19366 * Unschedule any events associated with the given Drawable. This can be 19367 * used when selecting a new Drawable into a view, so that the previous 19368 * one is completely unscheduled. 19369 * 19370 * @param who The Drawable to unschedule. 19371 * 19372 * @see #drawableStateChanged 19373 */ 19374 public void unscheduleDrawable(Drawable who) { 19375 if (mAttachInfo != null && who != null) { 19376 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 19377 Choreographer.CALLBACK_ANIMATION, null, who); 19378 } 19379 } 19380 19381 /** 19382 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 19383 * that the View directionality can and will be resolved before its Drawables. 19384 * 19385 * Will call {@link View#onResolveDrawables} when resolution is done. 19386 * 19387 * @hide 19388 */ 19389 protected void resolveDrawables() { 19390 // Drawables resolution may need to happen before resolving the layout direction (which is 19391 // done only during the measure() call). 19392 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 19393 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 19394 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 19395 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 19396 // direction to be resolved as its resolved value will be the same as its raw value. 19397 if (!isLayoutDirectionResolved() && 19398 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 19399 return; 19400 } 19401 19402 final int layoutDirection = isLayoutDirectionResolved() ? 19403 getLayoutDirection() : getRawLayoutDirection(); 19404 19405 if (mBackground != null) { 19406 mBackground.setLayoutDirection(layoutDirection); 19407 } 19408 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 19409 mForegroundInfo.mDrawable.setLayoutDirection(layoutDirection); 19410 } 19411 if (mDefaultFocusHighlight != null) { 19412 mDefaultFocusHighlight.setLayoutDirection(layoutDirection); 19413 } 19414 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 19415 onResolveDrawables(layoutDirection); 19416 } 19417 19418 boolean areDrawablesResolved() { 19419 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 19420 } 19421 19422 /** 19423 * Called when layout direction has been resolved. 19424 * 19425 * The default implementation does nothing. 19426 * 19427 * @param layoutDirection The resolved layout direction. 19428 * 19429 * @see #LAYOUT_DIRECTION_LTR 19430 * @see #LAYOUT_DIRECTION_RTL 19431 * 19432 * @hide 19433 */ 19434 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 19435 } 19436 19437 /** 19438 * @hide 19439 */ 19440 protected void resetResolvedDrawables() { 19441 resetResolvedDrawablesInternal(); 19442 } 19443 19444 void resetResolvedDrawablesInternal() { 19445 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 19446 } 19447 19448 /** 19449 * If your view subclass is displaying its own Drawable objects, it should 19450 * override this function and return true for any Drawable it is 19451 * displaying. This allows animations for those drawables to be 19452 * scheduled. 19453 * 19454 * <p>Be sure to call through to the super class when overriding this 19455 * function. 19456 * 19457 * @param who The Drawable to verify. Return true if it is one you are 19458 * displaying, else return the result of calling through to the 19459 * super class. 19460 * 19461 * @return boolean If true than the Drawable is being displayed in the 19462 * view; else false and it is not allowed to animate. 19463 * 19464 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 19465 * @see #drawableStateChanged() 19466 */ 19467 @CallSuper 19468 protected boolean verifyDrawable(@NonNull Drawable who) { 19469 // Avoid verifying the scroll bar drawable so that we don't end up in 19470 // an invalidation loop. This effectively prevents the scroll bar 19471 // drawable from triggering invalidations and scheduling runnables. 19472 return who == mBackground || (mForegroundInfo != null && mForegroundInfo.mDrawable == who) 19473 || (mDefaultFocusHighlight == who); 19474 } 19475 19476 /** 19477 * This function is called whenever the state of the view changes in such 19478 * a way that it impacts the state of drawables being shown. 19479 * <p> 19480 * If the View has a StateListAnimator, it will also be called to run necessary state 19481 * change animations. 19482 * <p> 19483 * Be sure to call through to the superclass when overriding this function. 19484 * 19485 * @see Drawable#setState(int[]) 19486 */ 19487 @CallSuper 19488 protected void drawableStateChanged() { 19489 final int[] state = getDrawableState(); 19490 boolean changed = false; 19491 19492 final Drawable bg = mBackground; 19493 if (bg != null && bg.isStateful()) { 19494 changed |= bg.setState(state); 19495 } 19496 19497 final Drawable hl = mDefaultFocusHighlight; 19498 if (hl != null && hl.isStateful()) { 19499 changed |= hl.setState(state); 19500 } 19501 19502 final Drawable fg = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 19503 if (fg != null && fg.isStateful()) { 19504 changed |= fg.setState(state); 19505 } 19506 19507 if (mScrollCache != null) { 19508 final Drawable scrollBar = mScrollCache.scrollBar; 19509 if (scrollBar != null && scrollBar.isStateful()) { 19510 changed |= scrollBar.setState(state) 19511 && mScrollCache.state != ScrollabilityCache.OFF; 19512 } 19513 } 19514 19515 if (mStateListAnimator != null) { 19516 mStateListAnimator.setState(state); 19517 } 19518 19519 if (changed) { 19520 invalidate(); 19521 } 19522 } 19523 19524 /** 19525 * This function is called whenever the view hotspot changes and needs to 19526 * be propagated to drawables or child views managed by the view. 19527 * <p> 19528 * Dispatching to child views is handled by 19529 * {@link #dispatchDrawableHotspotChanged(float, float)}. 19530 * <p> 19531 * Be sure to call through to the superclass when overriding this function. 19532 * 19533 * @param x hotspot x coordinate 19534 * @param y hotspot y coordinate 19535 */ 19536 @CallSuper 19537 public void drawableHotspotChanged(float x, float y) { 19538 if (mBackground != null) { 19539 mBackground.setHotspot(x, y); 19540 } 19541 if (mDefaultFocusHighlight != null) { 19542 mDefaultFocusHighlight.setHotspot(x, y); 19543 } 19544 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 19545 mForegroundInfo.mDrawable.setHotspot(x, y); 19546 } 19547 19548 dispatchDrawableHotspotChanged(x, y); 19549 } 19550 19551 /** 19552 * Dispatches drawableHotspotChanged to all of this View's children. 19553 * 19554 * @param x hotspot x coordinate 19555 * @param y hotspot y coordinate 19556 * @see #drawableHotspotChanged(float, float) 19557 */ 19558 public void dispatchDrawableHotspotChanged(float x, float y) { 19559 } 19560 19561 /** 19562 * Call this to force a view to update its drawable state. This will cause 19563 * drawableStateChanged to be called on this view. Views that are interested 19564 * in the new state should call getDrawableState. 19565 * 19566 * @see #drawableStateChanged 19567 * @see #getDrawableState 19568 */ 19569 public void refreshDrawableState() { 19570 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 19571 drawableStateChanged(); 19572 19573 ViewParent parent = mParent; 19574 if (parent != null) { 19575 parent.childDrawableStateChanged(this); 19576 } 19577 } 19578 19579 /** 19580 * Create a default focus highlight if it doesn't exist. 19581 * @return a default focus highlight. 19582 */ 19583 private Drawable getDefaultFocusHighlightDrawable() { 19584 if (mDefaultFocusHighlightCache == null) { 19585 if (mContext != null) { 19586 final int[] attrs = new int[] { android.R.attr.selectableItemBackground }; 19587 final TypedArray ta = mContext.obtainStyledAttributes(attrs); 19588 mDefaultFocusHighlightCache = ta.getDrawable(0); 19589 ta.recycle(); 19590 } 19591 } 19592 return mDefaultFocusHighlightCache; 19593 } 19594 19595 /** 19596 * Set the current default focus highlight. 19597 * @param highlight the highlight drawable, or {@code null} if it's no longer needed. 19598 */ 19599 private void setDefaultFocusHighlight(Drawable highlight) { 19600 mDefaultFocusHighlight = highlight; 19601 mDefaultFocusHighlightSizeChanged = true; 19602 if (highlight != null) { 19603 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 19604 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 19605 } 19606 highlight.setLayoutDirection(getLayoutDirection()); 19607 if (highlight.isStateful()) { 19608 highlight.setState(getDrawableState()); 19609 } 19610 if (isAttachedToWindow()) { 19611 highlight.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 19612 } 19613 // Set callback last, since the view may still be initializing. 19614 highlight.setCallback(this); 19615 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 19616 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 19617 mPrivateFlags |= PFLAG_SKIP_DRAW; 19618 } 19619 requestLayout(); 19620 invalidate(); 19621 } 19622 19623 /** 19624 * Check whether we need to draw a default focus highlight when this view gets focused, 19625 * which requires: 19626 * <ul> 19627 * <li>In the background, {@link android.R.attr#state_focused} is not defined.</li> 19628 * <li>This view is not in touch mode.</li> 19629 * <li>This view doesn't opt out for a default focus highlight, via 19630 * {@link #setDefaultFocusHighlightEnabled(boolean)}.</li> 19631 * </ul> 19632 * @return {@code true} if a default focus highlight is needed. 19633 */ 19634 private boolean isDefaultFocusHighlightNeeded(Drawable background) { 19635 final boolean hasFocusStateSpecified = background == null || !background.isStateful() 19636 || !background.hasFocusStateSpecified(); 19637 return !isInTouchMode() && getDefaultFocusHighlightEnabled() && hasFocusStateSpecified; 19638 } 19639 19640 /** 19641 * When this view is focused, switches on/off the default focused highlight. 19642 * <p> 19643 * This always happens when this view is focused, and only at this moment the default focus 19644 * highlight can be visible. 19645 */ 19646 private void switchDefaultFocusHighlight() { 19647 if (isFocused()) { 19648 final boolean needed = isDefaultFocusHighlightNeeded(mBackground); 19649 final boolean active = mDefaultFocusHighlight != null; 19650 if (needed && !active) { 19651 setDefaultFocusHighlight(getDefaultFocusHighlightDrawable()); 19652 } else if (!needed && active) { 19653 // The highlight is no longer needed, so tear it down. 19654 setDefaultFocusHighlight(null); 19655 } 19656 } 19657 } 19658 19659 /** 19660 * Draw the default focus highlight onto the canvas. 19661 * @param canvas the canvas where we're drawing the highlight. 19662 */ 19663 private void drawDefaultFocusHighlight(Canvas canvas) { 19664 if (mDefaultFocusHighlight != null) { 19665 if (mDefaultFocusHighlightSizeChanged) { 19666 mDefaultFocusHighlightSizeChanged = false; 19667 final int l = mScrollX; 19668 final int r = l + mRight - mLeft; 19669 final int t = mScrollY; 19670 final int b = t + mBottom - mTop; 19671 mDefaultFocusHighlight.setBounds(l, t, r, b); 19672 } 19673 mDefaultFocusHighlight.draw(canvas); 19674 } 19675 } 19676 19677 /** 19678 * Return an array of resource IDs of the drawable states representing the 19679 * current state of the view. 19680 * 19681 * @return The current drawable state 19682 * 19683 * @see Drawable#setState(int[]) 19684 * @see #drawableStateChanged() 19685 * @see #onCreateDrawableState(int) 19686 */ 19687 public final int[] getDrawableState() { 19688 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 19689 return mDrawableState; 19690 } else { 19691 mDrawableState = onCreateDrawableState(0); 19692 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 19693 return mDrawableState; 19694 } 19695 } 19696 19697 /** 19698 * Generate the new {@link android.graphics.drawable.Drawable} state for 19699 * this view. This is called by the view 19700 * system when the cached Drawable state is determined to be invalid. To 19701 * retrieve the current state, you should use {@link #getDrawableState}. 19702 * 19703 * @param extraSpace if non-zero, this is the number of extra entries you 19704 * would like in the returned array in which you can place your own 19705 * states. 19706 * 19707 * @return Returns an array holding the current {@link Drawable} state of 19708 * the view. 19709 * 19710 * @see #mergeDrawableStates(int[], int[]) 19711 */ 19712 protected int[] onCreateDrawableState(int extraSpace) { 19713 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 19714 mParent instanceof View) { 19715 return ((View) mParent).onCreateDrawableState(extraSpace); 19716 } 19717 19718 int[] drawableState; 19719 19720 int privateFlags = mPrivateFlags; 19721 19722 int viewStateIndex = 0; 19723 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= StateSet.VIEW_STATE_PRESSED; 19724 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= StateSet.VIEW_STATE_ENABLED; 19725 if (isFocused()) viewStateIndex |= StateSet.VIEW_STATE_FOCUSED; 19726 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= StateSet.VIEW_STATE_SELECTED; 19727 if (hasWindowFocus()) viewStateIndex |= StateSet.VIEW_STATE_WINDOW_FOCUSED; 19728 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= StateSet.VIEW_STATE_ACTIVATED; 19729 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 19730 ThreadedRenderer.isAvailable()) { 19731 // This is set if HW acceleration is requested, even if the current 19732 // process doesn't allow it. This is just to allow app preview 19733 // windows to better match their app. 19734 viewStateIndex |= StateSet.VIEW_STATE_ACCELERATED; 19735 } 19736 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= StateSet.VIEW_STATE_HOVERED; 19737 19738 final int privateFlags2 = mPrivateFlags2; 19739 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) { 19740 viewStateIndex |= StateSet.VIEW_STATE_DRAG_CAN_ACCEPT; 19741 } 19742 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) { 19743 viewStateIndex |= StateSet.VIEW_STATE_DRAG_HOVERED; 19744 } 19745 19746 drawableState = StateSet.get(viewStateIndex); 19747 19748 //noinspection ConstantIfStatement 19749 if (false) { 19750 Log.i("View", "drawableStateIndex=" + viewStateIndex); 19751 Log.i("View", toString() 19752 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 19753 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 19754 + " fo=" + hasFocus() 19755 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 19756 + " wf=" + hasWindowFocus() 19757 + ": " + Arrays.toString(drawableState)); 19758 } 19759 19760 if (extraSpace == 0) { 19761 return drawableState; 19762 } 19763 19764 final int[] fullState; 19765 if (drawableState != null) { 19766 fullState = new int[drawableState.length + extraSpace]; 19767 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 19768 } else { 19769 fullState = new int[extraSpace]; 19770 } 19771 19772 return fullState; 19773 } 19774 19775 /** 19776 * Merge your own state values in <var>additionalState</var> into the base 19777 * state values <var>baseState</var> that were returned by 19778 * {@link #onCreateDrawableState(int)}. 19779 * 19780 * @param baseState The base state values returned by 19781 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 19782 * own additional state values. 19783 * 19784 * @param additionalState The additional state values you would like 19785 * added to <var>baseState</var>; this array is not modified. 19786 * 19787 * @return As a convenience, the <var>baseState</var> array you originally 19788 * passed into the function is returned. 19789 * 19790 * @see #onCreateDrawableState(int) 19791 */ 19792 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 19793 final int N = baseState.length; 19794 int i = N - 1; 19795 while (i >= 0 && baseState[i] == 0) { 19796 i--; 19797 } 19798 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 19799 return baseState; 19800 } 19801 19802 /** 19803 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 19804 * on all Drawable objects associated with this view. 19805 * <p> 19806 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 19807 * attached to this view. 19808 */ 19809 @CallSuper 19810 public void jumpDrawablesToCurrentState() { 19811 if (mBackground != null) { 19812 mBackground.jumpToCurrentState(); 19813 } 19814 if (mStateListAnimator != null) { 19815 mStateListAnimator.jumpToCurrentState(); 19816 } 19817 if (mDefaultFocusHighlight != null) { 19818 mDefaultFocusHighlight.jumpToCurrentState(); 19819 } 19820 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null) { 19821 mForegroundInfo.mDrawable.jumpToCurrentState(); 19822 } 19823 } 19824 19825 /** 19826 * Sets the background color for this view. 19827 * @param color the color of the background 19828 */ 19829 @RemotableViewMethod 19830 public void setBackgroundColor(@ColorInt int color) { 19831 if (mBackground instanceof ColorDrawable) { 19832 ((ColorDrawable) mBackground.mutate()).setColor(color); 19833 computeOpaqueFlags(); 19834 mBackgroundResource = 0; 19835 } else { 19836 setBackground(new ColorDrawable(color)); 19837 } 19838 } 19839 19840 /** 19841 * Set the background to a given resource. The resource should refer to 19842 * a Drawable object or 0 to remove the background. 19843 * @param resid The identifier of the resource. 19844 * 19845 * @attr ref android.R.styleable#View_background 19846 */ 19847 @RemotableViewMethod 19848 public void setBackgroundResource(@DrawableRes int resid) { 19849 if (resid != 0 && resid == mBackgroundResource) { 19850 return; 19851 } 19852 19853 Drawable d = null; 19854 if (resid != 0) { 19855 d = mContext.getDrawable(resid); 19856 } 19857 setBackground(d); 19858 19859 mBackgroundResource = resid; 19860 } 19861 19862 /** 19863 * Set the background to a given Drawable, or remove the background. If the 19864 * background has padding, this View's padding is set to the background's 19865 * padding. However, when a background is removed, this View's padding isn't 19866 * touched. If setting the padding is desired, please use 19867 * {@link #setPadding(int, int, int, int)}. 19868 * 19869 * @param background The Drawable to use as the background, or null to remove the 19870 * background 19871 */ 19872 public void setBackground(Drawable background) { 19873 //noinspection deprecation 19874 setBackgroundDrawable(background); 19875 } 19876 19877 /** 19878 * @deprecated use {@link #setBackground(Drawable)} instead 19879 */ 19880 @Deprecated 19881 public void setBackgroundDrawable(Drawable background) { 19882 computeOpaqueFlags(); 19883 19884 if (background == mBackground) { 19885 return; 19886 } 19887 19888 boolean requestLayout = false; 19889 19890 mBackgroundResource = 0; 19891 19892 /* 19893 * Regardless of whether we're setting a new background or not, we want 19894 * to clear the previous drawable. setVisible first while we still have the callback set. 19895 */ 19896 if (mBackground != null) { 19897 if (isAttachedToWindow()) { 19898 mBackground.setVisible(false, false); 19899 } 19900 mBackground.setCallback(null); 19901 unscheduleDrawable(mBackground); 19902 } 19903 19904 if (background != null) { 19905 Rect padding = sThreadLocal.get(); 19906 if (padding == null) { 19907 padding = new Rect(); 19908 sThreadLocal.set(padding); 19909 } 19910 resetResolvedDrawablesInternal(); 19911 background.setLayoutDirection(getLayoutDirection()); 19912 if (background.getPadding(padding)) { 19913 resetResolvedPaddingInternal(); 19914 switch (background.getLayoutDirection()) { 19915 case LAYOUT_DIRECTION_RTL: 19916 mUserPaddingLeftInitial = padding.right; 19917 mUserPaddingRightInitial = padding.left; 19918 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 19919 break; 19920 case LAYOUT_DIRECTION_LTR: 19921 default: 19922 mUserPaddingLeftInitial = padding.left; 19923 mUserPaddingRightInitial = padding.right; 19924 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 19925 } 19926 mLeftPaddingDefined = false; 19927 mRightPaddingDefined = false; 19928 } 19929 19930 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 19931 // if it has a different minimum size, we should layout again 19932 if (mBackground == null 19933 || mBackground.getMinimumHeight() != background.getMinimumHeight() 19934 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 19935 requestLayout = true; 19936 } 19937 19938 // Set mBackground before we set this as the callback and start making other 19939 // background drawable state change calls. In particular, the setVisible call below 19940 // can result in drawables attempting to start animations or otherwise invalidate, 19941 // which requires the view set as the callback (us) to recognize the drawable as 19942 // belonging to it as per verifyDrawable. 19943 mBackground = background; 19944 if (background.isStateful()) { 19945 background.setState(getDrawableState()); 19946 } 19947 if (isAttachedToWindow()) { 19948 background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 19949 } 19950 19951 applyBackgroundTint(); 19952 19953 // Set callback last, since the view may still be initializing. 19954 background.setCallback(this); 19955 19956 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 19957 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 19958 requestLayout = true; 19959 } 19960 } else { 19961 /* Remove the background */ 19962 mBackground = null; 19963 if ((mViewFlags & WILL_NOT_DRAW) != 0 19964 && (mDefaultFocusHighlight == null) 19965 && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { 19966 mPrivateFlags |= PFLAG_SKIP_DRAW; 19967 } 19968 19969 /* 19970 * When the background is set, we try to apply its padding to this 19971 * View. When the background is removed, we don't touch this View's 19972 * padding. This is noted in the Javadocs. Hence, we don't need to 19973 * requestLayout(), the invalidate() below is sufficient. 19974 */ 19975 19976 // The old background's minimum size could have affected this 19977 // View's layout, so let's requestLayout 19978 requestLayout = true; 19979 } 19980 19981 computeOpaqueFlags(); 19982 19983 if (requestLayout) { 19984 requestLayout(); 19985 } 19986 19987 mBackgroundSizeChanged = true; 19988 invalidate(true); 19989 invalidateOutline(); 19990 } 19991 19992 /** 19993 * Gets the background drawable 19994 * 19995 * @return The drawable used as the background for this view, if any. 19996 * 19997 * @see #setBackground(Drawable) 19998 * 19999 * @attr ref android.R.styleable#View_background 20000 */ 20001 public Drawable getBackground() { 20002 return mBackground; 20003 } 20004 20005 /** 20006 * Applies a tint to the background drawable. Does not modify the current tint 20007 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 20008 * <p> 20009 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 20010 * mutate the drawable and apply the specified tint and tint mode using 20011 * {@link Drawable#setTintList(ColorStateList)}. 20012 * 20013 * @param tint the tint to apply, may be {@code null} to clear tint 20014 * 20015 * @attr ref android.R.styleable#View_backgroundTint 20016 * @see #getBackgroundTintList() 20017 * @see Drawable#setTintList(ColorStateList) 20018 */ 20019 public void setBackgroundTintList(@Nullable ColorStateList tint) { 20020 if (mBackgroundTint == null) { 20021 mBackgroundTint = new TintInfo(); 20022 } 20023 mBackgroundTint.mTintList = tint; 20024 mBackgroundTint.mHasTintList = true; 20025 20026 applyBackgroundTint(); 20027 } 20028 20029 /** 20030 * Return the tint applied to the background drawable, if specified. 20031 * 20032 * @return the tint applied to the background drawable 20033 * @attr ref android.R.styleable#View_backgroundTint 20034 * @see #setBackgroundTintList(ColorStateList) 20035 */ 20036 @Nullable 20037 public ColorStateList getBackgroundTintList() { 20038 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 20039 } 20040 20041 /** 20042 * Specifies the blending mode used to apply the tint specified by 20043 * {@link #setBackgroundTintList(ColorStateList)}} to the background 20044 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 20045 * 20046 * @param tintMode the blending mode used to apply the tint, may be 20047 * {@code null} to clear tint 20048 * @attr ref android.R.styleable#View_backgroundTintMode 20049 * @see #getBackgroundTintMode() 20050 * @see Drawable#setTintMode(PorterDuff.Mode) 20051 */ 20052 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 20053 if (mBackgroundTint == null) { 20054 mBackgroundTint = new TintInfo(); 20055 } 20056 mBackgroundTint.mTintMode = tintMode; 20057 mBackgroundTint.mHasTintMode = true; 20058 20059 applyBackgroundTint(); 20060 } 20061 20062 /** 20063 * Return the blending mode used to apply the tint to the background 20064 * drawable, if specified. 20065 * 20066 * @return the blending mode used to apply the tint to the background 20067 * drawable 20068 * @attr ref android.R.styleable#View_backgroundTintMode 20069 * @see #setBackgroundTintMode(PorterDuff.Mode) 20070 */ 20071 @Nullable 20072 public PorterDuff.Mode getBackgroundTintMode() { 20073 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 20074 } 20075 20076 private void applyBackgroundTint() { 20077 if (mBackground != null && mBackgroundTint != null) { 20078 final TintInfo tintInfo = mBackgroundTint; 20079 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 20080 mBackground = mBackground.mutate(); 20081 20082 if (tintInfo.mHasTintList) { 20083 mBackground.setTintList(tintInfo.mTintList); 20084 } 20085 20086 if (tintInfo.mHasTintMode) { 20087 mBackground.setTintMode(tintInfo.mTintMode); 20088 } 20089 20090 // The drawable (or one of its children) may not have been 20091 // stateful before applying the tint, so let's try again. 20092 if (mBackground.isStateful()) { 20093 mBackground.setState(getDrawableState()); 20094 } 20095 } 20096 } 20097 } 20098 20099 /** 20100 * Returns the drawable used as the foreground of this View. The 20101 * foreground drawable, if non-null, is always drawn on top of the view's content. 20102 * 20103 * @return a Drawable or null if no foreground was set 20104 * 20105 * @see #onDrawForeground(Canvas) 20106 */ 20107 public Drawable getForeground() { 20108 return mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 20109 } 20110 20111 /** 20112 * Supply a Drawable that is to be rendered on top of all of the content in the view. 20113 * 20114 * @param foreground the Drawable to be drawn on top of the children 20115 * 20116 * @attr ref android.R.styleable#View_foreground 20117 */ 20118 public void setForeground(Drawable foreground) { 20119 if (mForegroundInfo == null) { 20120 if (foreground == null) { 20121 // Nothing to do. 20122 return; 20123 } 20124 mForegroundInfo = new ForegroundInfo(); 20125 } 20126 20127 if (foreground == mForegroundInfo.mDrawable) { 20128 // Nothing to do 20129 return; 20130 } 20131 20132 if (mForegroundInfo.mDrawable != null) { 20133 if (isAttachedToWindow()) { 20134 mForegroundInfo.mDrawable.setVisible(false, false); 20135 } 20136 mForegroundInfo.mDrawable.setCallback(null); 20137 unscheduleDrawable(mForegroundInfo.mDrawable); 20138 } 20139 20140 mForegroundInfo.mDrawable = foreground; 20141 mForegroundInfo.mBoundsChanged = true; 20142 if (foreground != null) { 20143 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 20144 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 20145 } 20146 foreground.setLayoutDirection(getLayoutDirection()); 20147 if (foreground.isStateful()) { 20148 foreground.setState(getDrawableState()); 20149 } 20150 applyForegroundTint(); 20151 if (isAttachedToWindow()) { 20152 foreground.setVisible(getWindowVisibility() == VISIBLE && isShown(), false); 20153 } 20154 // Set callback last, since the view may still be initializing. 20155 foreground.setCallback(this); 20156 } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null 20157 && (mDefaultFocusHighlight == null)) { 20158 mPrivateFlags |= PFLAG_SKIP_DRAW; 20159 } 20160 requestLayout(); 20161 invalidate(); 20162 } 20163 20164 /** 20165 * Magic bit used to support features of framework-internal window decor implementation details. 20166 * This used to live exclusively in FrameLayout. 20167 * 20168 * @return true if the foreground should draw inside the padding region or false 20169 * if it should draw inset by the view's padding 20170 * @hide internal use only; only used by FrameLayout and internal screen layouts. 20171 */ 20172 public boolean isForegroundInsidePadding() { 20173 return mForegroundInfo != null ? mForegroundInfo.mInsidePadding : true; 20174 } 20175 20176 /** 20177 * Describes how the foreground is positioned. 20178 * 20179 * @return foreground gravity. 20180 * 20181 * @see #setForegroundGravity(int) 20182 * 20183 * @attr ref android.R.styleable#View_foregroundGravity 20184 */ 20185 public int getForegroundGravity() { 20186 return mForegroundInfo != null ? mForegroundInfo.mGravity 20187 : Gravity.START | Gravity.TOP; 20188 } 20189 20190 /** 20191 * Describes how the foreground is positioned. Defaults to START and TOP. 20192 * 20193 * @param gravity see {@link android.view.Gravity} 20194 * 20195 * @see #getForegroundGravity() 20196 * 20197 * @attr ref android.R.styleable#View_foregroundGravity 20198 */ 20199 public void setForegroundGravity(int gravity) { 20200 if (mForegroundInfo == null) { 20201 mForegroundInfo = new ForegroundInfo(); 20202 } 20203 20204 if (mForegroundInfo.mGravity != gravity) { 20205 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 20206 gravity |= Gravity.START; 20207 } 20208 20209 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 20210 gravity |= Gravity.TOP; 20211 } 20212 20213 mForegroundInfo.mGravity = gravity; 20214 requestLayout(); 20215 } 20216 } 20217 20218 /** 20219 * Applies a tint to the foreground drawable. Does not modify the current tint 20220 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 20221 * <p> 20222 * Subsequent calls to {@link #setForeground(Drawable)} will automatically 20223 * mutate the drawable and apply the specified tint and tint mode using 20224 * {@link Drawable#setTintList(ColorStateList)}. 20225 * 20226 * @param tint the tint to apply, may be {@code null} to clear tint 20227 * 20228 * @attr ref android.R.styleable#View_foregroundTint 20229 * @see #getForegroundTintList() 20230 * @see Drawable#setTintList(ColorStateList) 20231 */ 20232 public void setForegroundTintList(@Nullable ColorStateList tint) { 20233 if (mForegroundInfo == null) { 20234 mForegroundInfo = new ForegroundInfo(); 20235 } 20236 if (mForegroundInfo.mTintInfo == null) { 20237 mForegroundInfo.mTintInfo = new TintInfo(); 20238 } 20239 mForegroundInfo.mTintInfo.mTintList = tint; 20240 mForegroundInfo.mTintInfo.mHasTintList = true; 20241 20242 applyForegroundTint(); 20243 } 20244 20245 /** 20246 * Return the tint applied to the foreground drawable, if specified. 20247 * 20248 * @return the tint applied to the foreground drawable 20249 * @attr ref android.R.styleable#View_foregroundTint 20250 * @see #setForegroundTintList(ColorStateList) 20251 */ 20252 @Nullable 20253 public ColorStateList getForegroundTintList() { 20254 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 20255 ? mForegroundInfo.mTintInfo.mTintList : null; 20256 } 20257 20258 /** 20259 * Specifies the blending mode used to apply the tint specified by 20260 * {@link #setForegroundTintList(ColorStateList)}} to the background 20261 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 20262 * 20263 * @param tintMode the blending mode used to apply the tint, may be 20264 * {@code null} to clear tint 20265 * @attr ref android.R.styleable#View_foregroundTintMode 20266 * @see #getForegroundTintMode() 20267 * @see Drawable#setTintMode(PorterDuff.Mode) 20268 */ 20269 public void setForegroundTintMode(@Nullable PorterDuff.Mode tintMode) { 20270 if (mForegroundInfo == null) { 20271 mForegroundInfo = new ForegroundInfo(); 20272 } 20273 if (mForegroundInfo.mTintInfo == null) { 20274 mForegroundInfo.mTintInfo = new TintInfo(); 20275 } 20276 mForegroundInfo.mTintInfo.mTintMode = tintMode; 20277 mForegroundInfo.mTintInfo.mHasTintMode = true; 20278 20279 applyForegroundTint(); 20280 } 20281 20282 /** 20283 * Return the blending mode used to apply the tint to the foreground 20284 * drawable, if specified. 20285 * 20286 * @return the blending mode used to apply the tint to the foreground 20287 * drawable 20288 * @attr ref android.R.styleable#View_foregroundTintMode 20289 * @see #setForegroundTintMode(PorterDuff.Mode) 20290 */ 20291 @Nullable 20292 public PorterDuff.Mode getForegroundTintMode() { 20293 return mForegroundInfo != null && mForegroundInfo.mTintInfo != null 20294 ? mForegroundInfo.mTintInfo.mTintMode : null; 20295 } 20296 20297 private void applyForegroundTint() { 20298 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 20299 && mForegroundInfo.mTintInfo != null) { 20300 final TintInfo tintInfo = mForegroundInfo.mTintInfo; 20301 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 20302 mForegroundInfo.mDrawable = mForegroundInfo.mDrawable.mutate(); 20303 20304 if (tintInfo.mHasTintList) { 20305 mForegroundInfo.mDrawable.setTintList(tintInfo.mTintList); 20306 } 20307 20308 if (tintInfo.mHasTintMode) { 20309 mForegroundInfo.mDrawable.setTintMode(tintInfo.mTintMode); 20310 } 20311 20312 // The drawable (or one of its children) may not have been 20313 // stateful before applying the tint, so let's try again. 20314 if (mForegroundInfo.mDrawable.isStateful()) { 20315 mForegroundInfo.mDrawable.setState(getDrawableState()); 20316 } 20317 } 20318 } 20319 } 20320 20321 /** 20322 * Draw any foreground content for this view. 20323 * 20324 * <p>Foreground content may consist of scroll bars, a {@link #setForeground foreground} 20325 * drawable or other view-specific decorations. The foreground is drawn on top of the 20326 * primary view content.</p> 20327 * 20328 * @param canvas canvas to draw into 20329 */ 20330 public void onDrawForeground(Canvas canvas) { 20331 onDrawScrollIndicators(canvas); 20332 onDrawScrollBars(canvas); 20333 20334 final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; 20335 if (foreground != null) { 20336 if (mForegroundInfo.mBoundsChanged) { 20337 mForegroundInfo.mBoundsChanged = false; 20338 final Rect selfBounds = mForegroundInfo.mSelfBounds; 20339 final Rect overlayBounds = mForegroundInfo.mOverlayBounds; 20340 20341 if (mForegroundInfo.mInsidePadding) { 20342 selfBounds.set(0, 0, getWidth(), getHeight()); 20343 } else { 20344 selfBounds.set(getPaddingLeft(), getPaddingTop(), 20345 getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()); 20346 } 20347 20348 final int ld = getLayoutDirection(); 20349 Gravity.apply(mForegroundInfo.mGravity, foreground.getIntrinsicWidth(), 20350 foreground.getIntrinsicHeight(), selfBounds, overlayBounds, ld); 20351 foreground.setBounds(overlayBounds); 20352 } 20353 20354 foreground.draw(canvas); 20355 } 20356 } 20357 20358 /** 20359 * Sets the padding. The view may add on the space required to display 20360 * the scrollbars, depending on the style and visibility of the scrollbars. 20361 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 20362 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 20363 * from the values set in this call. 20364 * 20365 * @attr ref android.R.styleable#View_padding 20366 * @attr ref android.R.styleable#View_paddingBottom 20367 * @attr ref android.R.styleable#View_paddingLeft 20368 * @attr ref android.R.styleable#View_paddingRight 20369 * @attr ref android.R.styleable#View_paddingTop 20370 * @param left the left padding in pixels 20371 * @param top the top padding in pixels 20372 * @param right the right padding in pixels 20373 * @param bottom the bottom padding in pixels 20374 */ 20375 public void setPadding(int left, int top, int right, int bottom) { 20376 resetResolvedPaddingInternal(); 20377 20378 mUserPaddingStart = UNDEFINED_PADDING; 20379 mUserPaddingEnd = UNDEFINED_PADDING; 20380 20381 mUserPaddingLeftInitial = left; 20382 mUserPaddingRightInitial = right; 20383 20384 mLeftPaddingDefined = true; 20385 mRightPaddingDefined = true; 20386 20387 internalSetPadding(left, top, right, bottom); 20388 } 20389 20390 /** 20391 * @hide 20392 */ 20393 protected void internalSetPadding(int left, int top, int right, int bottom) { 20394 mUserPaddingLeft = left; 20395 mUserPaddingRight = right; 20396 mUserPaddingBottom = bottom; 20397 20398 final int viewFlags = mViewFlags; 20399 boolean changed = false; 20400 20401 // Common case is there are no scroll bars. 20402 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 20403 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 20404 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 20405 ? 0 : getVerticalScrollbarWidth(); 20406 switch (mVerticalScrollbarPosition) { 20407 case SCROLLBAR_POSITION_DEFAULT: 20408 if (isLayoutRtl()) { 20409 left += offset; 20410 } else { 20411 right += offset; 20412 } 20413 break; 20414 case SCROLLBAR_POSITION_RIGHT: 20415 right += offset; 20416 break; 20417 case SCROLLBAR_POSITION_LEFT: 20418 left += offset; 20419 break; 20420 } 20421 } 20422 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 20423 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 20424 ? 0 : getHorizontalScrollbarHeight(); 20425 } 20426 } 20427 20428 if (mPaddingLeft != left) { 20429 changed = true; 20430 mPaddingLeft = left; 20431 } 20432 if (mPaddingTop != top) { 20433 changed = true; 20434 mPaddingTop = top; 20435 } 20436 if (mPaddingRight != right) { 20437 changed = true; 20438 mPaddingRight = right; 20439 } 20440 if (mPaddingBottom != bottom) { 20441 changed = true; 20442 mPaddingBottom = bottom; 20443 } 20444 20445 if (changed) { 20446 requestLayout(); 20447 invalidateOutline(); 20448 } 20449 } 20450 20451 /** 20452 * Sets the relative padding. The view may add on the space required to display 20453 * the scrollbars, depending on the style and visibility of the scrollbars. 20454 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 20455 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 20456 * from the values set in this call. 20457 * 20458 * @attr ref android.R.styleable#View_padding 20459 * @attr ref android.R.styleable#View_paddingBottom 20460 * @attr ref android.R.styleable#View_paddingStart 20461 * @attr ref android.R.styleable#View_paddingEnd 20462 * @attr ref android.R.styleable#View_paddingTop 20463 * @param start the start padding in pixels 20464 * @param top the top padding in pixels 20465 * @param end the end padding in pixels 20466 * @param bottom the bottom padding in pixels 20467 */ 20468 public void setPaddingRelative(int start, int top, int end, int bottom) { 20469 resetResolvedPaddingInternal(); 20470 20471 mUserPaddingStart = start; 20472 mUserPaddingEnd = end; 20473 mLeftPaddingDefined = true; 20474 mRightPaddingDefined = true; 20475 20476 switch(getLayoutDirection()) { 20477 case LAYOUT_DIRECTION_RTL: 20478 mUserPaddingLeftInitial = end; 20479 mUserPaddingRightInitial = start; 20480 internalSetPadding(end, top, start, bottom); 20481 break; 20482 case LAYOUT_DIRECTION_LTR: 20483 default: 20484 mUserPaddingLeftInitial = start; 20485 mUserPaddingRightInitial = end; 20486 internalSetPadding(start, top, end, bottom); 20487 } 20488 } 20489 20490 /** 20491 * Returns the top padding of this view. 20492 * 20493 * @return the top padding in pixels 20494 */ 20495 public int getPaddingTop() { 20496 return mPaddingTop; 20497 } 20498 20499 /** 20500 * Returns the bottom padding of this view. If there are inset and enabled 20501 * scrollbars, this value may include the space required to display the 20502 * scrollbars as well. 20503 * 20504 * @return the bottom padding in pixels 20505 */ 20506 public int getPaddingBottom() { 20507 return mPaddingBottom; 20508 } 20509 20510 /** 20511 * Returns the left padding of this view. If there are inset and enabled 20512 * scrollbars, this value may include the space required to display the 20513 * scrollbars as well. 20514 * 20515 * @return the left padding in pixels 20516 */ 20517 public int getPaddingLeft() { 20518 if (!isPaddingResolved()) { 20519 resolvePadding(); 20520 } 20521 return mPaddingLeft; 20522 } 20523 20524 /** 20525 * Returns the start padding of this view depending on its resolved layout direction. 20526 * If there are inset and enabled scrollbars, this value may include the space 20527 * required to display the scrollbars as well. 20528 * 20529 * @return the start padding in pixels 20530 */ 20531 public int getPaddingStart() { 20532 if (!isPaddingResolved()) { 20533 resolvePadding(); 20534 } 20535 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 20536 mPaddingRight : mPaddingLeft; 20537 } 20538 20539 /** 20540 * Returns the right padding of this view. If there are inset and enabled 20541 * scrollbars, this value may include the space required to display the 20542 * scrollbars as well. 20543 * 20544 * @return the right padding in pixels 20545 */ 20546 public int getPaddingRight() { 20547 if (!isPaddingResolved()) { 20548 resolvePadding(); 20549 } 20550 return mPaddingRight; 20551 } 20552 20553 /** 20554 * Returns the end padding of this view depending on its resolved layout direction. 20555 * If there are inset and enabled scrollbars, this value may include the space 20556 * required to display the scrollbars as well. 20557 * 20558 * @return the end padding in pixels 20559 */ 20560 public int getPaddingEnd() { 20561 if (!isPaddingResolved()) { 20562 resolvePadding(); 20563 } 20564 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 20565 mPaddingLeft : mPaddingRight; 20566 } 20567 20568 /** 20569 * Return if the padding has been set through relative values 20570 * {@link #setPaddingRelative(int, int, int, int)} or through 20571 * @attr ref android.R.styleable#View_paddingStart or 20572 * @attr ref android.R.styleable#View_paddingEnd 20573 * 20574 * @return true if the padding is relative or false if it is not. 20575 */ 20576 public boolean isPaddingRelative() { 20577 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 20578 } 20579 20580 Insets computeOpticalInsets() { 20581 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 20582 } 20583 20584 /** 20585 * @hide 20586 */ 20587 public void resetPaddingToInitialValues() { 20588 if (isRtlCompatibilityMode()) { 20589 mPaddingLeft = mUserPaddingLeftInitial; 20590 mPaddingRight = mUserPaddingRightInitial; 20591 return; 20592 } 20593 if (isLayoutRtl()) { 20594 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 20595 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 20596 } else { 20597 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 20598 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 20599 } 20600 } 20601 20602 /** 20603 * @hide 20604 */ 20605 public Insets getOpticalInsets() { 20606 if (mLayoutInsets == null) { 20607 mLayoutInsets = computeOpticalInsets(); 20608 } 20609 return mLayoutInsets; 20610 } 20611 20612 /** 20613 * Set this view's optical insets. 20614 * 20615 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 20616 * property. Views that compute their own optical insets should call it as part of measurement. 20617 * This method does not request layout. If you are setting optical insets outside of 20618 * measure/layout itself you will want to call requestLayout() yourself. 20619 * </p> 20620 * @hide 20621 */ 20622 public void setOpticalInsets(Insets insets) { 20623 mLayoutInsets = insets; 20624 } 20625 20626 /** 20627 * Changes the selection state of this view. A view can be selected or not. 20628 * Note that selection is not the same as focus. Views are typically 20629 * selected in the context of an AdapterView like ListView or GridView; 20630 * the selected view is the view that is highlighted. 20631 * 20632 * @param selected true if the view must be selected, false otherwise 20633 */ 20634 public void setSelected(boolean selected) { 20635 //noinspection DoubleNegation 20636 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 20637 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 20638 if (!selected) resetPressedState(); 20639 invalidate(true); 20640 refreshDrawableState(); 20641 dispatchSetSelected(selected); 20642 if (selected) { 20643 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 20644 } else { 20645 notifyViewAccessibilityStateChangedIfNeeded( 20646 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 20647 } 20648 } 20649 } 20650 20651 /** 20652 * Dispatch setSelected to all of this View's children. 20653 * 20654 * @see #setSelected(boolean) 20655 * 20656 * @param selected The new selected state 20657 */ 20658 protected void dispatchSetSelected(boolean selected) { 20659 } 20660 20661 /** 20662 * Indicates the selection state of this view. 20663 * 20664 * @return true if the view is selected, false otherwise 20665 */ 20666 @ViewDebug.ExportedProperty 20667 public boolean isSelected() { 20668 return (mPrivateFlags & PFLAG_SELECTED) != 0; 20669 } 20670 20671 /** 20672 * Changes the activated state of this view. A view can be activated or not. 20673 * Note that activation is not the same as selection. Selection is 20674 * a transient property, representing the view (hierarchy) the user is 20675 * currently interacting with. Activation is a longer-term state that the 20676 * user can move views in and out of. For example, in a list view with 20677 * single or multiple selection enabled, the views in the current selection 20678 * set are activated. (Um, yeah, we are deeply sorry about the terminology 20679 * here.) The activated state is propagated down to children of the view it 20680 * is set on. 20681 * 20682 * @param activated true if the view must be activated, false otherwise 20683 */ 20684 public void setActivated(boolean activated) { 20685 //noinspection DoubleNegation 20686 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 20687 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 20688 invalidate(true); 20689 refreshDrawableState(); 20690 dispatchSetActivated(activated); 20691 } 20692 } 20693 20694 /** 20695 * Dispatch setActivated to all of this View's children. 20696 * 20697 * @see #setActivated(boolean) 20698 * 20699 * @param activated The new activated state 20700 */ 20701 protected void dispatchSetActivated(boolean activated) { 20702 } 20703 20704 /** 20705 * Indicates the activation state of this view. 20706 * 20707 * @return true if the view is activated, false otherwise 20708 */ 20709 @ViewDebug.ExportedProperty 20710 public boolean isActivated() { 20711 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 20712 } 20713 20714 /** 20715 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 20716 * observer can be used to get notifications when global events, like 20717 * layout, happen. 20718 * 20719 * The returned ViewTreeObserver observer is not guaranteed to remain 20720 * valid for the lifetime of this View. If the caller of this method keeps 20721 * a long-lived reference to ViewTreeObserver, it should always check for 20722 * the return value of {@link ViewTreeObserver#isAlive()}. 20723 * 20724 * @return The ViewTreeObserver for this view's hierarchy. 20725 */ 20726 public ViewTreeObserver getViewTreeObserver() { 20727 if (mAttachInfo != null) { 20728 return mAttachInfo.mTreeObserver; 20729 } 20730 if (mFloatingTreeObserver == null) { 20731 mFloatingTreeObserver = new ViewTreeObserver(mContext); 20732 } 20733 return mFloatingTreeObserver; 20734 } 20735 20736 /** 20737 * <p>Finds the topmost view in the current view hierarchy.</p> 20738 * 20739 * @return the topmost view containing this view 20740 */ 20741 public View getRootView() { 20742 if (mAttachInfo != null) { 20743 final View v = mAttachInfo.mRootView; 20744 if (v != null) { 20745 return v; 20746 } 20747 } 20748 20749 View parent = this; 20750 20751 while (parent.mParent != null && parent.mParent instanceof View) { 20752 parent = (View) parent.mParent; 20753 } 20754 20755 return parent; 20756 } 20757 20758 /** 20759 * Transforms a motion event from view-local coordinates to on-screen 20760 * coordinates. 20761 * 20762 * @param ev the view-local motion event 20763 * @return false if the transformation could not be applied 20764 * @hide 20765 */ 20766 public boolean toGlobalMotionEvent(MotionEvent ev) { 20767 final AttachInfo info = mAttachInfo; 20768 if (info == null) { 20769 return false; 20770 } 20771 20772 final Matrix m = info.mTmpMatrix; 20773 m.set(Matrix.IDENTITY_MATRIX); 20774 transformMatrixToGlobal(m); 20775 ev.transform(m); 20776 return true; 20777 } 20778 20779 /** 20780 * Transforms a motion event from on-screen coordinates to view-local 20781 * coordinates. 20782 * 20783 * @param ev the on-screen motion event 20784 * @return false if the transformation could not be applied 20785 * @hide 20786 */ 20787 public boolean toLocalMotionEvent(MotionEvent ev) { 20788 final AttachInfo info = mAttachInfo; 20789 if (info == null) { 20790 return false; 20791 } 20792 20793 final Matrix m = info.mTmpMatrix; 20794 m.set(Matrix.IDENTITY_MATRIX); 20795 transformMatrixToLocal(m); 20796 ev.transform(m); 20797 return true; 20798 } 20799 20800 /** 20801 * Modifies the input matrix such that it maps view-local coordinates to 20802 * on-screen coordinates. 20803 * 20804 * @param m input matrix to modify 20805 * @hide 20806 */ 20807 public void transformMatrixToGlobal(Matrix m) { 20808 final ViewParent parent = mParent; 20809 if (parent instanceof View) { 20810 final View vp = (View) parent; 20811 vp.transformMatrixToGlobal(m); 20812 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 20813 } else if (parent instanceof ViewRootImpl) { 20814 final ViewRootImpl vr = (ViewRootImpl) parent; 20815 vr.transformMatrixToGlobal(m); 20816 m.preTranslate(0, -vr.mCurScrollY); 20817 } 20818 20819 m.preTranslate(mLeft, mTop); 20820 20821 if (!hasIdentityMatrix()) { 20822 m.preConcat(getMatrix()); 20823 } 20824 } 20825 20826 /** 20827 * Modifies the input matrix such that it maps on-screen coordinates to 20828 * view-local coordinates. 20829 * 20830 * @param m input matrix to modify 20831 * @hide 20832 */ 20833 public void transformMatrixToLocal(Matrix m) { 20834 final ViewParent parent = mParent; 20835 if (parent instanceof View) { 20836 final View vp = (View) parent; 20837 vp.transformMatrixToLocal(m); 20838 m.postTranslate(vp.mScrollX, vp.mScrollY); 20839 } else if (parent instanceof ViewRootImpl) { 20840 final ViewRootImpl vr = (ViewRootImpl) parent; 20841 vr.transformMatrixToLocal(m); 20842 m.postTranslate(0, vr.mCurScrollY); 20843 } 20844 20845 m.postTranslate(-mLeft, -mTop); 20846 20847 if (!hasIdentityMatrix()) { 20848 m.postConcat(getInverseMatrix()); 20849 } 20850 } 20851 20852 /** 20853 * @hide 20854 */ 20855 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 20856 @ViewDebug.IntToString(from = 0, to = "x"), 20857 @ViewDebug.IntToString(from = 1, to = "y") 20858 }) 20859 public int[] getLocationOnScreen() { 20860 int[] location = new int[2]; 20861 getLocationOnScreen(location); 20862 return location; 20863 } 20864 20865 /** 20866 * <p>Computes the coordinates of this view on the screen. The argument 20867 * must be an array of two integers. After the method returns, the array 20868 * contains the x and y location in that order.</p> 20869 * 20870 * @param outLocation an array of two integers in which to hold the coordinates 20871 */ 20872 public void getLocationOnScreen(@Size(2) int[] outLocation) { 20873 getLocationInWindow(outLocation); 20874 20875 final AttachInfo info = mAttachInfo; 20876 if (info != null) { 20877 outLocation[0] += info.mWindowLeft; 20878 outLocation[1] += info.mWindowTop; 20879 } 20880 } 20881 20882 /** 20883 * <p>Computes the coordinates of this view in its window. The argument 20884 * must be an array of two integers. After the method returns, the array 20885 * contains the x and y location in that order.</p> 20886 * 20887 * @param outLocation an array of two integers in which to hold the coordinates 20888 */ 20889 public void getLocationInWindow(@Size(2) int[] outLocation) { 20890 if (outLocation == null || outLocation.length < 2) { 20891 throw new IllegalArgumentException("outLocation must be an array of two integers"); 20892 } 20893 20894 outLocation[0] = 0; 20895 outLocation[1] = 0; 20896 20897 transformFromViewToWindowSpace(outLocation); 20898 } 20899 20900 /** @hide */ 20901 public void transformFromViewToWindowSpace(@Size(2) int[] inOutLocation) { 20902 if (inOutLocation == null || inOutLocation.length < 2) { 20903 throw new IllegalArgumentException("inOutLocation must be an array of two integers"); 20904 } 20905 20906 if (mAttachInfo == null) { 20907 // When the view is not attached to a window, this method does not make sense 20908 inOutLocation[0] = inOutLocation[1] = 0; 20909 return; 20910 } 20911 20912 float position[] = mAttachInfo.mTmpTransformLocation; 20913 position[0] = inOutLocation[0]; 20914 position[1] = inOutLocation[1]; 20915 20916 if (!hasIdentityMatrix()) { 20917 getMatrix().mapPoints(position); 20918 } 20919 20920 position[0] += mLeft; 20921 position[1] += mTop; 20922 20923 ViewParent viewParent = mParent; 20924 while (viewParent instanceof View) { 20925 final View view = (View) viewParent; 20926 20927 position[0] -= view.mScrollX; 20928 position[1] -= view.mScrollY; 20929 20930 if (!view.hasIdentityMatrix()) { 20931 view.getMatrix().mapPoints(position); 20932 } 20933 20934 position[0] += view.mLeft; 20935 position[1] += view.mTop; 20936 20937 viewParent = view.mParent; 20938 } 20939 20940 if (viewParent instanceof ViewRootImpl) { 20941 // *cough* 20942 final ViewRootImpl vr = (ViewRootImpl) viewParent; 20943 position[1] -= vr.mCurScrollY; 20944 } 20945 20946 inOutLocation[0] = Math.round(position[0]); 20947 inOutLocation[1] = Math.round(position[1]); 20948 } 20949 20950 /** 20951 * @param id the id of the view to be found 20952 * @return the view of the specified id, null if cannot be found 20953 * @hide 20954 */ 20955 protected <T extends View> T findViewTraversal(@IdRes int id) { 20956 if (id == mID) { 20957 return (T) this; 20958 } 20959 return null; 20960 } 20961 20962 /** 20963 * @param tag the tag of the view to be found 20964 * @return the view of specified tag, null if cannot be found 20965 * @hide 20966 */ 20967 protected <T extends View> T findViewWithTagTraversal(Object tag) { 20968 if (tag != null && tag.equals(mTag)) { 20969 return (T) this; 20970 } 20971 return null; 20972 } 20973 20974 /** 20975 * @param predicate The predicate to evaluate. 20976 * @param childToSkip If not null, ignores this child during the recursive traversal. 20977 * @return The first view that matches the predicate or null. 20978 * @hide 20979 */ 20980 protected <T extends View> T findViewByPredicateTraversal(Predicate<View> predicate, 20981 View childToSkip) { 20982 if (predicate.test(this)) { 20983 return (T) this; 20984 } 20985 return null; 20986 } 20987 20988 /** 20989 * Finds the first descendant view with the given ID, the view itself if 20990 * the ID matches {@link #getId()}, or {@code null} if the ID is invalid 20991 * (< 0) or there is no matching view in the hierarchy. 20992 * <p> 20993 * <strong>Note:</strong> In most cases -- depending on compiler support -- 20994 * the resulting view is automatically cast to the target class type. If 20995 * the target class type is unconstrained, an explicit cast may be 20996 * necessary. 20997 * 20998 * @param id the ID to search for 20999 * @return a view with given ID if found, or {@code null} otherwise 21000 * @see View#findViewById(int) 21001 */ 21002 @Nullable 21003 public final <T extends View> T findViewById(@IdRes int id) { 21004 if (id < 0) { 21005 return null; 21006 } 21007 return findViewTraversal(id); 21008 } 21009 21010 /** 21011 * Finds a view by its unuque and stable accessibility id. 21012 * 21013 * @param accessibilityId The searched accessibility id. 21014 * @return The found view. 21015 */ 21016 final <T extends View> T findViewByAccessibilityId(int accessibilityId) { 21017 if (accessibilityId < 0) { 21018 return null; 21019 } 21020 T view = findViewByAccessibilityIdTraversal(accessibilityId); 21021 if (view != null) { 21022 return view.includeForAccessibility() ? view : null; 21023 } 21024 return null; 21025 } 21026 21027 /** 21028 * Performs the traversal to find a view by its unuque and stable accessibility id. 21029 * 21030 * <strong>Note:</strong>This method does not stop at the root namespace 21031 * boundary since the user can touch the screen at an arbitrary location 21032 * potentially crossing the root namespace bounday which will send an 21033 * accessibility event to accessibility services and they should be able 21034 * to obtain the event source. Also accessibility ids are guaranteed to be 21035 * unique in the window. 21036 * 21037 * @param accessibilityId The accessibility id. 21038 * @return The found view. 21039 * @hide 21040 */ 21041 public <T extends View> T findViewByAccessibilityIdTraversal(int accessibilityId) { 21042 if (getAccessibilityViewId() == accessibilityId) { 21043 return (T) this; 21044 } 21045 return null; 21046 } 21047 21048 /** 21049 * Look for a child view with the given tag. If this view has the given 21050 * tag, return this view. 21051 * 21052 * @param tag The tag to search for, using "tag.equals(getTag())". 21053 * @return The View that has the given tag in the hierarchy or null 21054 */ 21055 public final <T extends View> T findViewWithTag(Object tag) { 21056 if (tag == null) { 21057 return null; 21058 } 21059 return findViewWithTagTraversal(tag); 21060 } 21061 21062 /** 21063 * Look for a child view that matches the specified predicate. 21064 * If this view matches the predicate, return this view. 21065 * 21066 * @param predicate The predicate to evaluate. 21067 * @return The first view that matches the predicate or null. 21068 * @hide 21069 */ 21070 public final <T extends View> T findViewByPredicate(Predicate<View> predicate) { 21071 return findViewByPredicateTraversal(predicate, null); 21072 } 21073 21074 /** 21075 * Look for a child view that matches the specified predicate, 21076 * starting with the specified view and its descendents and then 21077 * recusively searching the ancestors and siblings of that view 21078 * until this view is reached. 21079 * 21080 * This method is useful in cases where the predicate does not match 21081 * a single unique view (perhaps multiple views use the same id) 21082 * and we are trying to find the view that is "closest" in scope to the 21083 * starting view. 21084 * 21085 * @param start The view to start from. 21086 * @param predicate The predicate to evaluate. 21087 * @return The first view that matches the predicate or null. 21088 * @hide 21089 */ 21090 public final <T extends View> T findViewByPredicateInsideOut( 21091 View start, Predicate<View> predicate) { 21092 View childToSkip = null; 21093 for (;;) { 21094 T view = start.findViewByPredicateTraversal(predicate, childToSkip); 21095 if (view != null || start == this) { 21096 return view; 21097 } 21098 21099 ViewParent parent = start.getParent(); 21100 if (parent == null || !(parent instanceof View)) { 21101 return null; 21102 } 21103 21104 childToSkip = start; 21105 start = (View) parent; 21106 } 21107 } 21108 21109 /** 21110 * Sets the identifier for this view. The identifier does not have to be 21111 * unique in this view's hierarchy. The identifier should be a positive 21112 * number. 21113 * 21114 * @see #NO_ID 21115 * @see #getId() 21116 * @see #findViewById(int) 21117 * 21118 * @param id a number used to identify the view 21119 * 21120 * @attr ref android.R.styleable#View_id 21121 */ 21122 public void setId(@IdRes int id) { 21123 mID = id; 21124 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 21125 mID = generateViewId(); 21126 } 21127 } 21128 21129 /** 21130 * {@hide} 21131 * 21132 * @param isRoot true if the view belongs to the root namespace, false 21133 * otherwise 21134 */ 21135 public void setIsRootNamespace(boolean isRoot) { 21136 if (isRoot) { 21137 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 21138 } else { 21139 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 21140 } 21141 } 21142 21143 /** 21144 * {@hide} 21145 * 21146 * @return true if the view belongs to the root namespace, false otherwise 21147 */ 21148 public boolean isRootNamespace() { 21149 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 21150 } 21151 21152 /** 21153 * Returns this view's identifier. 21154 * 21155 * @return a positive integer used to identify the view or {@link #NO_ID} 21156 * if the view has no ID 21157 * 21158 * @see #setId(int) 21159 * @see #findViewById(int) 21160 * @attr ref android.R.styleable#View_id 21161 */ 21162 @IdRes 21163 @ViewDebug.CapturedViewProperty 21164 public int getId() { 21165 return mID; 21166 } 21167 21168 /** 21169 * Returns this view's tag. 21170 * 21171 * @return the Object stored in this view as a tag, or {@code null} if not 21172 * set 21173 * 21174 * @see #setTag(Object) 21175 * @see #getTag(int) 21176 */ 21177 @ViewDebug.ExportedProperty 21178 public Object getTag() { 21179 return mTag; 21180 } 21181 21182 /** 21183 * Sets the tag associated with this view. A tag can be used to mark 21184 * a view in its hierarchy and does not have to be unique within the 21185 * hierarchy. Tags can also be used to store data within a view without 21186 * resorting to another data structure. 21187 * 21188 * @param tag an Object to tag the view with 21189 * 21190 * @see #getTag() 21191 * @see #setTag(int, Object) 21192 */ 21193 public void setTag(final Object tag) { 21194 mTag = tag; 21195 } 21196 21197 /** 21198 * Returns the tag associated with this view and the specified key. 21199 * 21200 * @param key The key identifying the tag 21201 * 21202 * @return the Object stored in this view as a tag, or {@code null} if not 21203 * set 21204 * 21205 * @see #setTag(int, Object) 21206 * @see #getTag() 21207 */ 21208 public Object getTag(int key) { 21209 if (mKeyedTags != null) return mKeyedTags.get(key); 21210 return null; 21211 } 21212 21213 /** 21214 * Sets a tag associated with this view and a key. A tag can be used 21215 * to mark a view in its hierarchy and does not have to be unique within 21216 * the hierarchy. Tags can also be used to store data within a view 21217 * without resorting to another data structure. 21218 * 21219 * The specified key should be an id declared in the resources of the 21220 * application to ensure it is unique (see the <a 21221 * href="{@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 21222 * Keys identified as belonging to 21223 * the Android framework or not associated with any package will cause 21224 * an {@link IllegalArgumentException} to be thrown. 21225 * 21226 * @param key The key identifying the tag 21227 * @param tag An Object to tag the view with 21228 * 21229 * @throws IllegalArgumentException If they specified key is not valid 21230 * 21231 * @see #setTag(Object) 21232 * @see #getTag(int) 21233 */ 21234 public void setTag(int key, final Object tag) { 21235 // If the package id is 0x00 or 0x01, it's either an undefined package 21236 // or a framework id 21237 if ((key >>> 24) < 2) { 21238 throw new IllegalArgumentException("The key must be an application-specific " 21239 + "resource id."); 21240 } 21241 21242 setKeyedTag(key, tag); 21243 } 21244 21245 /** 21246 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 21247 * framework id. 21248 * 21249 * @hide 21250 */ 21251 public void setTagInternal(int key, Object tag) { 21252 if ((key >>> 24) != 0x1) { 21253 throw new IllegalArgumentException("The key must be a framework-specific " 21254 + "resource id."); 21255 } 21256 21257 setKeyedTag(key, tag); 21258 } 21259 21260 private void setKeyedTag(int key, Object tag) { 21261 if (mKeyedTags == null) { 21262 mKeyedTags = new SparseArray<Object>(2); 21263 } 21264 21265 mKeyedTags.put(key, tag); 21266 } 21267 21268 /** 21269 * Prints information about this view in the log output, with the tag 21270 * {@link #VIEW_LOG_TAG}. 21271 * 21272 * @hide 21273 */ 21274 public void debug() { 21275 debug(0); 21276 } 21277 21278 /** 21279 * Prints information about this view in the log output, with the tag 21280 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 21281 * indentation defined by the <code>depth</code>. 21282 * 21283 * @param depth the indentation level 21284 * 21285 * @hide 21286 */ 21287 protected void debug(int depth) { 21288 String output = debugIndent(depth - 1); 21289 21290 output += "+ " + this; 21291 int id = getId(); 21292 if (id != -1) { 21293 output += " (id=" + id + ")"; 21294 } 21295 Object tag = getTag(); 21296 if (tag != null) { 21297 output += " (tag=" + tag + ")"; 21298 } 21299 Log.d(VIEW_LOG_TAG, output); 21300 21301 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 21302 output = debugIndent(depth) + " FOCUSED"; 21303 Log.d(VIEW_LOG_TAG, output); 21304 } 21305 21306 output = debugIndent(depth); 21307 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 21308 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 21309 + "} "; 21310 Log.d(VIEW_LOG_TAG, output); 21311 21312 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 21313 || mPaddingBottom != 0) { 21314 output = debugIndent(depth); 21315 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 21316 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 21317 Log.d(VIEW_LOG_TAG, output); 21318 } 21319 21320 output = debugIndent(depth); 21321 output += "mMeasureWidth=" + mMeasuredWidth + 21322 " mMeasureHeight=" + mMeasuredHeight; 21323 Log.d(VIEW_LOG_TAG, output); 21324 21325 output = debugIndent(depth); 21326 if (mLayoutParams == null) { 21327 output += "BAD! no layout params"; 21328 } else { 21329 output = mLayoutParams.debug(output); 21330 } 21331 Log.d(VIEW_LOG_TAG, output); 21332 21333 output = debugIndent(depth); 21334 output += "flags={"; 21335 output += View.printFlags(mViewFlags); 21336 output += "}"; 21337 Log.d(VIEW_LOG_TAG, output); 21338 21339 output = debugIndent(depth); 21340 output += "privateFlags={"; 21341 output += View.printPrivateFlags(mPrivateFlags); 21342 output += "}"; 21343 Log.d(VIEW_LOG_TAG, output); 21344 } 21345 21346 /** 21347 * Creates a string of whitespaces used for indentation. 21348 * 21349 * @param depth the indentation level 21350 * @return a String containing (depth * 2 + 3) * 2 white spaces 21351 * 21352 * @hide 21353 */ 21354 protected static String debugIndent(int depth) { 21355 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 21356 for (int i = 0; i < (depth * 2) + 3; i++) { 21357 spaces.append(' ').append(' '); 21358 } 21359 return spaces.toString(); 21360 } 21361 21362 /** 21363 * <p>Return the offset of the widget's text baseline from the widget's top 21364 * boundary. If this widget does not support baseline alignment, this 21365 * method returns -1. </p> 21366 * 21367 * @return the offset of the baseline within the widget's bounds or -1 21368 * if baseline alignment is not supported 21369 */ 21370 @ViewDebug.ExportedProperty(category = "layout") 21371 public int getBaseline() { 21372 return -1; 21373 } 21374 21375 /** 21376 * Returns whether the view hierarchy is currently undergoing a layout pass. This 21377 * information is useful to avoid situations such as calling {@link #requestLayout()} during 21378 * a layout pass. 21379 * 21380 * @return whether the view hierarchy is currently undergoing a layout pass 21381 */ 21382 public boolean isInLayout() { 21383 ViewRootImpl viewRoot = getViewRootImpl(); 21384 return (viewRoot != null && viewRoot.isInLayout()); 21385 } 21386 21387 /** 21388 * Call this when something has changed which has invalidated the 21389 * layout of this view. This will schedule a layout pass of the view 21390 * tree. This should not be called while the view hierarchy is currently in a layout 21391 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 21392 * end of the current layout pass (and then layout will run again) or after the current 21393 * frame is drawn and the next layout occurs. 21394 * 21395 * <p>Subclasses which override this method should call the superclass method to 21396 * handle possible request-during-layout errors correctly.</p> 21397 */ 21398 @CallSuper 21399 public void requestLayout() { 21400 if (mMeasureCache != null) mMeasureCache.clear(); 21401 21402 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 21403 // Only trigger request-during-layout logic if this is the view requesting it, 21404 // not the views in its parent hierarchy 21405 ViewRootImpl viewRoot = getViewRootImpl(); 21406 if (viewRoot != null && viewRoot.isInLayout()) { 21407 if (!viewRoot.requestLayoutDuringLayout(this)) { 21408 return; 21409 } 21410 } 21411 mAttachInfo.mViewRequestingLayout = this; 21412 } 21413 21414 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 21415 mPrivateFlags |= PFLAG_INVALIDATED; 21416 21417 if (mParent != null && !mParent.isLayoutRequested()) { 21418 mParent.requestLayout(); 21419 } 21420 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 21421 mAttachInfo.mViewRequestingLayout = null; 21422 } 21423 } 21424 21425 /** 21426 * Forces this view to be laid out during the next layout pass. 21427 * This method does not call requestLayout() or forceLayout() 21428 * on the parent. 21429 */ 21430 public void forceLayout() { 21431 if (mMeasureCache != null) mMeasureCache.clear(); 21432 21433 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 21434 mPrivateFlags |= PFLAG_INVALIDATED; 21435 } 21436 21437 /** 21438 * <p> 21439 * This is called to find out how big a view should be. The parent 21440 * supplies constraint information in the width and height parameters. 21441 * </p> 21442 * 21443 * <p> 21444 * The actual measurement work of a view is performed in 21445 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 21446 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 21447 * </p> 21448 * 21449 * 21450 * @param widthMeasureSpec Horizontal space requirements as imposed by the 21451 * parent 21452 * @param heightMeasureSpec Vertical space requirements as imposed by the 21453 * parent 21454 * 21455 * @see #onMeasure(int, int) 21456 */ 21457 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 21458 boolean optical = isLayoutModeOptical(this); 21459 if (optical != isLayoutModeOptical(mParent)) { 21460 Insets insets = getOpticalInsets(); 21461 int oWidth = insets.left + insets.right; 21462 int oHeight = insets.top + insets.bottom; 21463 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 21464 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 21465 } 21466 21467 // Suppress sign extension for the low bytes 21468 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 21469 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 21470 21471 final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 21472 21473 // Optimize layout by avoiding an extra EXACTLY pass when the view is 21474 // already measured as the correct size. In API 23 and below, this 21475 // extra pass is required to make LinearLayout re-distribute weight. 21476 final boolean specChanged = widthMeasureSpec != mOldWidthMeasureSpec 21477 || heightMeasureSpec != mOldHeightMeasureSpec; 21478 final boolean isSpecExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY 21479 && MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY; 21480 final boolean matchesSpecSize = getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) 21481 && getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec); 21482 final boolean needsLayout = specChanged 21483 && (sAlwaysRemeasureExactly || !isSpecExactly || !matchesSpecSize); 21484 21485 if (forceLayout || needsLayout) { 21486 // first clears the measured dimension flag 21487 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 21488 21489 resolveRtlPropertiesIfNeeded(); 21490 21491 int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key); 21492 if (cacheIndex < 0 || sIgnoreMeasureCache) { 21493 // measure ourselves, this should set the measured dimension flag back 21494 onMeasure(widthMeasureSpec, heightMeasureSpec); 21495 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 21496 } else { 21497 long value = mMeasureCache.valueAt(cacheIndex); 21498 // Casting a long to int drops the high 32 bits, no mask needed 21499 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 21500 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 21501 } 21502 21503 // flag not set, setMeasuredDimension() was not invoked, we raise 21504 // an exception to warn the developer 21505 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 21506 throw new IllegalStateException("View with id " + getId() + ": " 21507 + getClass().getName() + "#onMeasure() did not set the" 21508 + " measured dimension by calling" 21509 + " setMeasuredDimension()"); 21510 } 21511 21512 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 21513 } 21514 21515 mOldWidthMeasureSpec = widthMeasureSpec; 21516 mOldHeightMeasureSpec = heightMeasureSpec; 21517 21518 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 21519 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 21520 } 21521 21522 /** 21523 * <p> 21524 * Measure the view and its content to determine the measured width and the 21525 * measured height. This method is invoked by {@link #measure(int, int)} and 21526 * should be overridden by subclasses to provide accurate and efficient 21527 * measurement of their contents. 21528 * </p> 21529 * 21530 * <p> 21531 * <strong>CONTRACT:</strong> When overriding this method, you 21532 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 21533 * measured width and height of this view. Failure to do so will trigger an 21534 * <code>IllegalStateException</code>, thrown by 21535 * {@link #measure(int, int)}. Calling the superclass' 21536 * {@link #onMeasure(int, int)} is a valid use. 21537 * </p> 21538 * 21539 * <p> 21540 * The base class implementation of measure defaults to the background size, 21541 * unless a larger size is allowed by the MeasureSpec. Subclasses should 21542 * override {@link #onMeasure(int, int)} to provide better measurements of 21543 * their content. 21544 * </p> 21545 * 21546 * <p> 21547 * If this method is overridden, it is the subclass's responsibility to make 21548 * sure the measured height and width are at least the view's minimum height 21549 * and width ({@link #getSuggestedMinimumHeight()} and 21550 * {@link #getSuggestedMinimumWidth()}). 21551 * </p> 21552 * 21553 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 21554 * The requirements are encoded with 21555 * {@link android.view.View.MeasureSpec}. 21556 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 21557 * The requirements are encoded with 21558 * {@link android.view.View.MeasureSpec}. 21559 * 21560 * @see #getMeasuredWidth() 21561 * @see #getMeasuredHeight() 21562 * @see #setMeasuredDimension(int, int) 21563 * @see #getSuggestedMinimumHeight() 21564 * @see #getSuggestedMinimumWidth() 21565 * @see android.view.View.MeasureSpec#getMode(int) 21566 * @see android.view.View.MeasureSpec#getSize(int) 21567 */ 21568 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 21569 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 21570 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 21571 } 21572 21573 /** 21574 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 21575 * measured width and measured height. Failing to do so will trigger an 21576 * exception at measurement time.</p> 21577 * 21578 * @param measuredWidth The measured width of this view. May be a complex 21579 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21580 * {@link #MEASURED_STATE_TOO_SMALL}. 21581 * @param measuredHeight The measured height of this view. May be a complex 21582 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21583 * {@link #MEASURED_STATE_TOO_SMALL}. 21584 */ 21585 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 21586 boolean optical = isLayoutModeOptical(this); 21587 if (optical != isLayoutModeOptical(mParent)) { 21588 Insets insets = getOpticalInsets(); 21589 int opticalWidth = insets.left + insets.right; 21590 int opticalHeight = insets.top + insets.bottom; 21591 21592 measuredWidth += optical ? opticalWidth : -opticalWidth; 21593 measuredHeight += optical ? opticalHeight : -opticalHeight; 21594 } 21595 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 21596 } 21597 21598 /** 21599 * Sets the measured dimension without extra processing for things like optical bounds. 21600 * Useful for reapplying consistent values that have already been cooked with adjustments 21601 * for optical bounds, etc. such as those from the measurement cache. 21602 * 21603 * @param measuredWidth The measured width of this view. May be a complex 21604 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21605 * {@link #MEASURED_STATE_TOO_SMALL}. 21606 * @param measuredHeight The measured height of this view. May be a complex 21607 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 21608 * {@link #MEASURED_STATE_TOO_SMALL}. 21609 */ 21610 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 21611 mMeasuredWidth = measuredWidth; 21612 mMeasuredHeight = measuredHeight; 21613 21614 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 21615 } 21616 21617 /** 21618 * Merge two states as returned by {@link #getMeasuredState()}. 21619 * @param curState The current state as returned from a view or the result 21620 * of combining multiple views. 21621 * @param newState The new view state to combine. 21622 * @return Returns a new integer reflecting the combination of the two 21623 * states. 21624 */ 21625 public static int combineMeasuredStates(int curState, int newState) { 21626 return curState | newState; 21627 } 21628 21629 /** 21630 * Version of {@link #resolveSizeAndState(int, int, int)} 21631 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 21632 */ 21633 public static int resolveSize(int size, int measureSpec) { 21634 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 21635 } 21636 21637 /** 21638 * Utility to reconcile a desired size and state, with constraints imposed 21639 * by a MeasureSpec. Will take the desired size, unless a different size 21640 * is imposed by the constraints. The returned value is a compound integer, 21641 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 21642 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the 21643 * resulting size is smaller than the size the view wants to be. 21644 * 21645 * @param size How big the view wants to be. 21646 * @param measureSpec Constraints imposed by the parent. 21647 * @param childMeasuredState Size information bit mask for the view's 21648 * children. 21649 * @return Size information bit mask as defined by 21650 * {@link #MEASURED_SIZE_MASK} and 21651 * {@link #MEASURED_STATE_TOO_SMALL}. 21652 */ 21653 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 21654 final int specMode = MeasureSpec.getMode(measureSpec); 21655 final int specSize = MeasureSpec.getSize(measureSpec); 21656 final int result; 21657 switch (specMode) { 21658 case MeasureSpec.AT_MOST: 21659 if (specSize < size) { 21660 result = specSize | MEASURED_STATE_TOO_SMALL; 21661 } else { 21662 result = size; 21663 } 21664 break; 21665 case MeasureSpec.EXACTLY: 21666 result = specSize; 21667 break; 21668 case MeasureSpec.UNSPECIFIED: 21669 default: 21670 result = size; 21671 } 21672 return result | (childMeasuredState & MEASURED_STATE_MASK); 21673 } 21674 21675 /** 21676 * Utility to return a default size. Uses the supplied size if the 21677 * MeasureSpec imposed no constraints. Will get larger if allowed 21678 * by the MeasureSpec. 21679 * 21680 * @param size Default size for this view 21681 * @param measureSpec Constraints imposed by the parent 21682 * @return The size this view should be. 21683 */ 21684 public static int getDefaultSize(int size, int measureSpec) { 21685 int result = size; 21686 int specMode = MeasureSpec.getMode(measureSpec); 21687 int specSize = MeasureSpec.getSize(measureSpec); 21688 21689 switch (specMode) { 21690 case MeasureSpec.UNSPECIFIED: 21691 result = size; 21692 break; 21693 case MeasureSpec.AT_MOST: 21694 case MeasureSpec.EXACTLY: 21695 result = specSize; 21696 break; 21697 } 21698 return result; 21699 } 21700 21701 /** 21702 * Returns the suggested minimum height that the view should use. This 21703 * returns the maximum of the view's minimum height 21704 * and the background's minimum height 21705 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 21706 * <p> 21707 * When being used in {@link #onMeasure(int, int)}, the caller should still 21708 * ensure the returned height is within the requirements of the parent. 21709 * 21710 * @return The suggested minimum height of the view. 21711 */ 21712 protected int getSuggestedMinimumHeight() { 21713 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 21714 21715 } 21716 21717 /** 21718 * Returns the suggested minimum width that the view should use. This 21719 * returns the maximum of the view's minimum width 21720 * and the background's minimum width 21721 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 21722 * <p> 21723 * When being used in {@link #onMeasure(int, int)}, the caller should still 21724 * ensure the returned width is within the requirements of the parent. 21725 * 21726 * @return The suggested minimum width of the view. 21727 */ 21728 protected int getSuggestedMinimumWidth() { 21729 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 21730 } 21731 21732 /** 21733 * Returns the minimum height of the view. 21734 * 21735 * @return the minimum height the view will try to be, in pixels 21736 * 21737 * @see #setMinimumHeight(int) 21738 * 21739 * @attr ref android.R.styleable#View_minHeight 21740 */ 21741 public int getMinimumHeight() { 21742 return mMinHeight; 21743 } 21744 21745 /** 21746 * Sets the minimum height of the view. It is not guaranteed the view will 21747 * be able to achieve this minimum height (for example, if its parent layout 21748 * constrains it with less available height). 21749 * 21750 * @param minHeight The minimum height the view will try to be, in pixels 21751 * 21752 * @see #getMinimumHeight() 21753 * 21754 * @attr ref android.R.styleable#View_minHeight 21755 */ 21756 @RemotableViewMethod 21757 public void setMinimumHeight(int minHeight) { 21758 mMinHeight = minHeight; 21759 requestLayout(); 21760 } 21761 21762 /** 21763 * Returns the minimum width of the view. 21764 * 21765 * @return the minimum width the view will try to be, in pixels 21766 * 21767 * @see #setMinimumWidth(int) 21768 * 21769 * @attr ref android.R.styleable#View_minWidth 21770 */ 21771 public int getMinimumWidth() { 21772 return mMinWidth; 21773 } 21774 21775 /** 21776 * Sets the minimum width of the view. It is not guaranteed the view will 21777 * be able to achieve this minimum width (for example, if its parent layout 21778 * constrains it with less available width). 21779 * 21780 * @param minWidth The minimum width the view will try to be, in pixels 21781 * 21782 * @see #getMinimumWidth() 21783 * 21784 * @attr ref android.R.styleable#View_minWidth 21785 */ 21786 public void setMinimumWidth(int minWidth) { 21787 mMinWidth = minWidth; 21788 requestLayout(); 21789 21790 } 21791 21792 /** 21793 * Get the animation currently associated with this view. 21794 * 21795 * @return The animation that is currently playing or 21796 * scheduled to play for this view. 21797 */ 21798 public Animation getAnimation() { 21799 return mCurrentAnimation; 21800 } 21801 21802 /** 21803 * Start the specified animation now. 21804 * 21805 * @param animation the animation to start now 21806 */ 21807 public void startAnimation(Animation animation) { 21808 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 21809 setAnimation(animation); 21810 invalidateParentCaches(); 21811 invalidate(true); 21812 } 21813 21814 /** 21815 * Cancels any animations for this view. 21816 */ 21817 public void clearAnimation() { 21818 if (mCurrentAnimation != null) { 21819 mCurrentAnimation.detach(); 21820 } 21821 mCurrentAnimation = null; 21822 invalidateParentIfNeeded(); 21823 } 21824 21825 /** 21826 * Sets the next animation to play for this view. 21827 * If you want the animation to play immediately, use 21828 * {@link #startAnimation(android.view.animation.Animation)} instead. 21829 * This method provides allows fine-grained 21830 * control over the start time and invalidation, but you 21831 * must make sure that 1) the animation has a start time set, and 21832 * 2) the view's parent (which controls animations on its children) 21833 * will be invalidated when the animation is supposed to 21834 * start. 21835 * 21836 * @param animation The next animation, or null. 21837 */ 21838 public void setAnimation(Animation animation) { 21839 mCurrentAnimation = animation; 21840 21841 if (animation != null) { 21842 // If the screen is off assume the animation start time is now instead of 21843 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 21844 // would cause the animation to start when the screen turns back on 21845 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 21846 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 21847 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 21848 } 21849 animation.reset(); 21850 } 21851 } 21852 21853 /** 21854 * Invoked by a parent ViewGroup to notify the start of the animation 21855 * currently associated with this view. If you override this method, 21856 * always call super.onAnimationStart(); 21857 * 21858 * @see #setAnimation(android.view.animation.Animation) 21859 * @see #getAnimation() 21860 */ 21861 @CallSuper 21862 protected void onAnimationStart() { 21863 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 21864 } 21865 21866 /** 21867 * Invoked by a parent ViewGroup to notify the end of the animation 21868 * currently associated with this view. If you override this method, 21869 * always call super.onAnimationEnd(); 21870 * 21871 * @see #setAnimation(android.view.animation.Animation) 21872 * @see #getAnimation() 21873 */ 21874 @CallSuper 21875 protected void onAnimationEnd() { 21876 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 21877 } 21878 21879 /** 21880 * Invoked if there is a Transform that involves alpha. Subclass that can 21881 * draw themselves with the specified alpha should return true, and then 21882 * respect that alpha when their onDraw() is called. If this returns false 21883 * then the view may be redirected to draw into an offscreen buffer to 21884 * fulfill the request, which will look fine, but may be slower than if the 21885 * subclass handles it internally. The default implementation returns false. 21886 * 21887 * @param alpha The alpha (0..255) to apply to the view's drawing 21888 * @return true if the view can draw with the specified alpha. 21889 */ 21890 protected boolean onSetAlpha(int alpha) { 21891 return false; 21892 } 21893 21894 /** 21895 * This is used by the RootView to perform an optimization when 21896 * the view hierarchy contains one or several SurfaceView. 21897 * SurfaceView is always considered transparent, but its children are not, 21898 * therefore all View objects remove themselves from the global transparent 21899 * region (passed as a parameter to this function). 21900 * 21901 * @param region The transparent region for this ViewAncestor (window). 21902 * 21903 * @return Returns true if the effective visibility of the view at this 21904 * point is opaque, regardless of the transparent region; returns false 21905 * if it is possible for underlying windows to be seen behind the view. 21906 * 21907 * {@hide} 21908 */ 21909 public boolean gatherTransparentRegion(Region region) { 21910 final AttachInfo attachInfo = mAttachInfo; 21911 if (region != null && attachInfo != null) { 21912 final int pflags = mPrivateFlags; 21913 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 21914 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 21915 // remove it from the transparent region. 21916 final int[] location = attachInfo.mTransparentLocation; 21917 getLocationInWindow(location); 21918 // When a view has Z value, then it will be better to leave some area below the view 21919 // for drawing shadow. The shadow outset is proportional to the Z value. Note that 21920 // the bottom part needs more offset than the left, top and right parts due to the 21921 // spot light effects. 21922 int shadowOffset = getZ() > 0 ? (int) getZ() : 0; 21923 region.op(location[0] - shadowOffset, location[1] - shadowOffset, 21924 location[0] + mRight - mLeft + shadowOffset, 21925 location[1] + mBottom - mTop + (shadowOffset * 3), Region.Op.DIFFERENCE); 21926 } else { 21927 if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 21928 // The SKIP_DRAW flag IS set and the background drawable exists, we remove 21929 // the background drawable's non-transparent parts from this transparent region. 21930 applyDrawableToTransparentRegion(mBackground, region); 21931 } 21932 if (mForegroundInfo != null && mForegroundInfo.mDrawable != null 21933 && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { 21934 // Similarly, we remove the foreground drawable's non-transparent parts. 21935 applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); 21936 } 21937 if (mDefaultFocusHighlight != null 21938 && mDefaultFocusHighlight.getOpacity() != PixelFormat.TRANSPARENT) { 21939 // Similarly, we remove the default focus highlight's non-transparent parts. 21940 applyDrawableToTransparentRegion(mDefaultFocusHighlight, region); 21941 } 21942 } 21943 } 21944 return true; 21945 } 21946 21947 /** 21948 * Play a sound effect for this view. 21949 * 21950 * <p>The framework will play sound effects for some built in actions, such as 21951 * clicking, but you may wish to play these effects in your widget, 21952 * for instance, for internal navigation. 21953 * 21954 * <p>The sound effect will only be played if sound effects are enabled by the user, and 21955 * {@link #isSoundEffectsEnabled()} is true. 21956 * 21957 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 21958 */ 21959 public void playSoundEffect(int soundConstant) { 21960 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 21961 return; 21962 } 21963 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 21964 } 21965 21966 /** 21967 * BZZZTT!!1! 21968 * 21969 * <p>Provide haptic feedback to the user for this view. 21970 * 21971 * <p>The framework will provide haptic feedback for some built in actions, 21972 * such as long presses, but you may wish to provide feedback for your 21973 * own widget. 21974 * 21975 * <p>The feedback will only be performed if 21976 * {@link #isHapticFeedbackEnabled()} is true. 21977 * 21978 * @param feedbackConstant One of the constants defined in 21979 * {@link HapticFeedbackConstants} 21980 */ 21981 public boolean performHapticFeedback(int feedbackConstant) { 21982 return performHapticFeedback(feedbackConstant, 0); 21983 } 21984 21985 /** 21986 * BZZZTT!!1! 21987 * 21988 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 21989 * 21990 * @param feedbackConstant One of the constants defined in 21991 * {@link HapticFeedbackConstants} 21992 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 21993 */ 21994 public boolean performHapticFeedback(int feedbackConstant, int flags) { 21995 if (mAttachInfo == null) { 21996 return false; 21997 } 21998 //noinspection SimplifiableIfStatement 21999 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 22000 && !isHapticFeedbackEnabled()) { 22001 return false; 22002 } 22003 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 22004 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 22005 } 22006 22007 /** 22008 * Request that the visibility of the status bar or other screen/window 22009 * decorations be changed. 22010 * 22011 * <p>This method is used to put the over device UI into temporary modes 22012 * where the user's attention is focused more on the application content, 22013 * by dimming or hiding surrounding system affordances. This is typically 22014 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 22015 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 22016 * to be placed behind the action bar (and with these flags other system 22017 * affordances) so that smooth transitions between hiding and showing them 22018 * can be done. 22019 * 22020 * <p>Two representative examples of the use of system UI visibility is 22021 * implementing a content browsing application (like a magazine reader) 22022 * and a video playing application. 22023 * 22024 * <p>The first code shows a typical implementation of a View in a content 22025 * browsing application. In this implementation, the application goes 22026 * into a content-oriented mode by hiding the status bar and action bar, 22027 * and putting the navigation elements into lights out mode. The user can 22028 * then interact with content while in this mode. Such an application should 22029 * provide an easy way for the user to toggle out of the mode (such as to 22030 * check information in the status bar or access notifications). In the 22031 * implementation here, this is done simply by tapping on the content. 22032 * 22033 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 22034 * content} 22035 * 22036 * <p>This second code sample shows a typical implementation of a View 22037 * in a video playing application. In this situation, while the video is 22038 * playing the application would like to go into a complete full-screen mode, 22039 * to use as much of the display as possible for the video. When in this state 22040 * the user can not interact with the application; the system intercepts 22041 * touching on the screen to pop the UI out of full screen mode. See 22042 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 22043 * 22044 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 22045 * content} 22046 * 22047 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22048 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 22049 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 22050 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 22051 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 22052 */ 22053 public void setSystemUiVisibility(int visibility) { 22054 if (visibility != mSystemUiVisibility) { 22055 mSystemUiVisibility = visibility; 22056 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 22057 mParent.recomputeViewAttributes(this); 22058 } 22059 } 22060 } 22061 22062 /** 22063 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 22064 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 22065 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 22066 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 22067 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 22068 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 22069 */ 22070 public int getSystemUiVisibility() { 22071 return mSystemUiVisibility; 22072 } 22073 22074 /** 22075 * Returns the current system UI visibility that is currently set for 22076 * the entire window. This is the combination of the 22077 * {@link #setSystemUiVisibility(int)} values supplied by all of the 22078 * views in the window. 22079 */ 22080 public int getWindowSystemUiVisibility() { 22081 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 22082 } 22083 22084 /** 22085 * Override to find out when the window's requested system UI visibility 22086 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 22087 * This is different from the callbacks received through 22088 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 22089 * in that this is only telling you about the local request of the window, 22090 * not the actual values applied by the system. 22091 */ 22092 public void onWindowSystemUiVisibilityChanged(int visible) { 22093 } 22094 22095 /** 22096 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 22097 * the view hierarchy. 22098 */ 22099 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 22100 onWindowSystemUiVisibilityChanged(visible); 22101 } 22102 22103 /** 22104 * Set a listener to receive callbacks when the visibility of the system bar changes. 22105 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 22106 */ 22107 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 22108 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 22109 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 22110 mParent.recomputeViewAttributes(this); 22111 } 22112 } 22113 22114 /** 22115 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 22116 * the view hierarchy. 22117 */ 22118 public void dispatchSystemUiVisibilityChanged(int visibility) { 22119 ListenerInfo li = mListenerInfo; 22120 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 22121 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 22122 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 22123 } 22124 } 22125 22126 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 22127 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 22128 if (val != mSystemUiVisibility) { 22129 setSystemUiVisibility(val); 22130 return true; 22131 } 22132 return false; 22133 } 22134 22135 /** @hide */ 22136 public void setDisabledSystemUiVisibility(int flags) { 22137 if (mAttachInfo != null) { 22138 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 22139 mAttachInfo.mDisabledSystemUiVisibility = flags; 22140 if (mParent != null) { 22141 mParent.recomputeViewAttributes(this); 22142 } 22143 } 22144 } 22145 } 22146 22147 /** 22148 * Creates an image that the system displays during the drag and drop 22149 * operation. This is called a "drag shadow". The default implementation 22150 * for a DragShadowBuilder based on a View returns an image that has exactly the same 22151 * appearance as the given View. The default also positions the center of the drag shadow 22152 * directly under the touch point. If no View is provided (the constructor with no parameters 22153 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 22154 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overridden, then the 22155 * default is an invisible drag shadow. 22156 * <p> 22157 * You are not required to use the View you provide to the constructor as the basis of the 22158 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 22159 * anything you want as the drag shadow. 22160 * </p> 22161 * <p> 22162 * You pass a DragShadowBuilder object to the system when you start the drag. The system 22163 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 22164 * size and position of the drag shadow. It uses this data to construct a 22165 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 22166 * so that your application can draw the shadow image in the Canvas. 22167 * </p> 22168 * 22169 * <div class="special reference"> 22170 * <h3>Developer Guides</h3> 22171 * <p>For a guide to implementing drag and drop features, read the 22172 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 22173 * </div> 22174 */ 22175 public static class DragShadowBuilder { 22176 private final WeakReference<View> mView; 22177 22178 /** 22179 * Constructs a shadow image builder based on a View. By default, the resulting drag 22180 * shadow will have the same appearance and dimensions as the View, with the touch point 22181 * over the center of the View. 22182 * @param view A View. Any View in scope can be used. 22183 */ 22184 public DragShadowBuilder(View view) { 22185 mView = new WeakReference<View>(view); 22186 } 22187 22188 /** 22189 * Construct a shadow builder object with no associated View. This 22190 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 22191 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 22192 * to supply the drag shadow's dimensions and appearance without 22193 * reference to any View object. If they are not overridden, then the result is an 22194 * invisible drag shadow. 22195 */ 22196 public DragShadowBuilder() { 22197 mView = new WeakReference<View>(null); 22198 } 22199 22200 /** 22201 * Returns the View object that had been passed to the 22202 * {@link #View.DragShadowBuilder(View)} 22203 * constructor. If that View parameter was {@code null} or if the 22204 * {@link #View.DragShadowBuilder()} 22205 * constructor was used to instantiate the builder object, this method will return 22206 * null. 22207 * 22208 * @return The View object associate with this builder object. 22209 */ 22210 @SuppressWarnings({"JavadocReference"}) 22211 final public View getView() { 22212 return mView.get(); 22213 } 22214 22215 /** 22216 * Provides the metrics for the shadow image. These include the dimensions of 22217 * the shadow image, and the point within that shadow that should 22218 * be centered under the touch location while dragging. 22219 * <p> 22220 * The default implementation sets the dimensions of the shadow to be the 22221 * same as the dimensions of the View itself and centers the shadow under 22222 * the touch point. 22223 * </p> 22224 * 22225 * @param outShadowSize A {@link android.graphics.Point} containing the width and height 22226 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 22227 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 22228 * image. 22229 * 22230 * @param outShadowTouchPoint A {@link android.graphics.Point} for the position within the 22231 * shadow image that should be underneath the touch point during the drag and drop 22232 * operation. Your application must set {@link android.graphics.Point#x} to the 22233 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 22234 */ 22235 public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) { 22236 final View view = mView.get(); 22237 if (view != null) { 22238 outShadowSize.set(view.getWidth(), view.getHeight()); 22239 outShadowTouchPoint.set(outShadowSize.x / 2, outShadowSize.y / 2); 22240 } else { 22241 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 22242 } 22243 } 22244 22245 /** 22246 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 22247 * based on the dimensions it received from the 22248 * {@link #onProvideShadowMetrics(Point, Point)} callback. 22249 * 22250 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 22251 */ 22252 public void onDrawShadow(Canvas canvas) { 22253 final View view = mView.get(); 22254 if (view != null) { 22255 view.draw(canvas); 22256 } else { 22257 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 22258 } 22259 } 22260 } 22261 22262 /** 22263 * @deprecated Use {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) 22264 * startDragAndDrop()} for newer platform versions. 22265 */ 22266 @Deprecated 22267 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 22268 Object myLocalState, int flags) { 22269 return startDragAndDrop(data, shadowBuilder, myLocalState, flags); 22270 } 22271 22272 /** 22273 * Starts a drag and drop operation. When your application calls this method, it passes a 22274 * {@link android.view.View.DragShadowBuilder} object to the system. The 22275 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 22276 * to get metrics for the drag shadow, and then calls the object's 22277 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 22278 * <p> 22279 * Once the system has the drag shadow, it begins the drag and drop operation by sending 22280 * drag events to all the View objects in your application that are currently visible. It does 22281 * this either by calling the View object's drag listener (an implementation of 22282 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 22283 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 22284 * Both are passed a {@link android.view.DragEvent} object that has a 22285 * {@link android.view.DragEvent#getAction()} value of 22286 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 22287 * </p> 22288 * <p> 22289 * Your application can invoke {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, 22290 * int) startDragAndDrop()} on any attached View object. The View object does not need to be 22291 * the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to be related 22292 * to the View the user selected for dragging. 22293 * </p> 22294 * @param data A {@link android.content.ClipData} object pointing to the data to be 22295 * transferred by the drag and drop operation. 22296 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 22297 * drag shadow. 22298 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 22299 * drop operation. When dispatching drag events to views in the same activity this object 22300 * will be available through {@link android.view.DragEvent#getLocalState()}. Views in other 22301 * activities will not have access to this data ({@link android.view.DragEvent#getLocalState()} 22302 * will return null). 22303 * <p> 22304 * myLocalState is a lightweight mechanism for the sending information from the dragged View 22305 * to the target Views. For example, it can contain flags that differentiate between a 22306 * a copy operation and a move operation. 22307 * </p> 22308 * @param flags Flags that control the drag and drop operation. This can be set to 0 for no 22309 * flags, or any combination of the following: 22310 * <ul> 22311 * <li>{@link #DRAG_FLAG_GLOBAL}</li> 22312 * <li>{@link #DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION}</li> 22313 * <li>{@link #DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION}</li> 22314 * <li>{@link #DRAG_FLAG_GLOBAL_URI_READ}</li> 22315 * <li>{@link #DRAG_FLAG_GLOBAL_URI_WRITE}</li> 22316 * <li>{@link #DRAG_FLAG_OPAQUE}</li> 22317 * </ul> 22318 * @return {@code true} if the method completes successfully, or 22319 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 22320 * do a drag, and so no drag operation is in progress. 22321 */ 22322 public final boolean startDragAndDrop(ClipData data, DragShadowBuilder shadowBuilder, 22323 Object myLocalState, int flags) { 22324 if (ViewDebug.DEBUG_DRAG) { 22325 Log.d(VIEW_LOG_TAG, "startDragAndDrop: data=" + data + " flags=" + flags); 22326 } 22327 if (mAttachInfo == null) { 22328 Log.w(VIEW_LOG_TAG, "startDragAndDrop called on a detached view."); 22329 return false; 22330 } 22331 22332 if (data != null) { 22333 data.prepareToLeaveProcess((flags & View.DRAG_FLAG_GLOBAL) != 0); 22334 } 22335 22336 boolean okay = false; 22337 22338 Point shadowSize = new Point(); 22339 Point shadowTouchPoint = new Point(); 22340 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 22341 22342 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 22343 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 22344 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 22345 } 22346 22347 if (ViewDebug.DEBUG_DRAG) { 22348 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 22349 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 22350 } 22351 if (mAttachInfo.mDragSurface != null) { 22352 mAttachInfo.mDragSurface.release(); 22353 } 22354 mAttachInfo.mDragSurface = new Surface(); 22355 try { 22356 mAttachInfo.mDragToken = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 22357 flags, shadowSize.x, shadowSize.y, mAttachInfo.mDragSurface); 22358 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" 22359 + mAttachInfo.mDragToken + " surface=" + mAttachInfo.mDragSurface); 22360 if (mAttachInfo.mDragToken != null) { 22361 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 22362 try { 22363 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 22364 shadowBuilder.onDrawShadow(canvas); 22365 } finally { 22366 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 22367 } 22368 22369 final ViewRootImpl root = getViewRootImpl(); 22370 22371 // Cache the local state object for delivery with DragEvents 22372 root.setLocalDragState(myLocalState); 22373 22374 // repurpose 'shadowSize' for the last touch point 22375 root.getLastTouchPoint(shadowSize); 22376 22377 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, mAttachInfo.mDragToken, 22378 root.getLastTouchSource(), shadowSize.x, shadowSize.y, 22379 shadowTouchPoint.x, shadowTouchPoint.y, data); 22380 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 22381 } 22382 } catch (Exception e) { 22383 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 22384 mAttachInfo.mDragSurface.destroy(); 22385 mAttachInfo.mDragSurface = null; 22386 } 22387 22388 return okay; 22389 } 22390 22391 /** 22392 * Cancels an ongoing drag and drop operation. 22393 * <p> 22394 * A {@link android.view.DragEvent} object with 22395 * {@link android.view.DragEvent#getAction()} value of 22396 * {@link android.view.DragEvent#ACTION_DRAG_ENDED} and 22397 * {@link android.view.DragEvent#getResult()} value of {@code false} 22398 * will be sent to every 22399 * View that received {@link android.view.DragEvent#ACTION_DRAG_STARTED} 22400 * even if they are not currently visible. 22401 * </p> 22402 * <p> 22403 * This method can be called on any View in the same window as the View on which 22404 * {@link #startDragAndDrop(ClipData, DragShadowBuilder, Object, int) startDragAndDrop} 22405 * was called. 22406 * </p> 22407 */ 22408 public final void cancelDragAndDrop() { 22409 if (ViewDebug.DEBUG_DRAG) { 22410 Log.d(VIEW_LOG_TAG, "cancelDragAndDrop"); 22411 } 22412 if (mAttachInfo == null) { 22413 Log.w(VIEW_LOG_TAG, "cancelDragAndDrop called on a detached view."); 22414 return; 22415 } 22416 if (mAttachInfo.mDragToken != null) { 22417 try { 22418 mAttachInfo.mSession.cancelDragAndDrop(mAttachInfo.mDragToken); 22419 } catch (Exception e) { 22420 Log.e(VIEW_LOG_TAG, "Unable to cancel drag", e); 22421 } 22422 mAttachInfo.mDragToken = null; 22423 } else { 22424 Log.e(VIEW_LOG_TAG, "No active drag to cancel"); 22425 } 22426 } 22427 22428 /** 22429 * Updates the drag shadow for the ongoing drag and drop operation. 22430 * 22431 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 22432 * new drag shadow. 22433 */ 22434 public final void updateDragShadow(DragShadowBuilder shadowBuilder) { 22435 if (ViewDebug.DEBUG_DRAG) { 22436 Log.d(VIEW_LOG_TAG, "updateDragShadow"); 22437 } 22438 if (mAttachInfo == null) { 22439 Log.w(VIEW_LOG_TAG, "updateDragShadow called on a detached view."); 22440 return; 22441 } 22442 if (mAttachInfo.mDragToken != null) { 22443 try { 22444 Canvas canvas = mAttachInfo.mDragSurface.lockCanvas(null); 22445 try { 22446 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 22447 shadowBuilder.onDrawShadow(canvas); 22448 } finally { 22449 mAttachInfo.mDragSurface.unlockCanvasAndPost(canvas); 22450 } 22451 } catch (Exception e) { 22452 Log.e(VIEW_LOG_TAG, "Unable to update drag shadow", e); 22453 } 22454 } else { 22455 Log.e(VIEW_LOG_TAG, "No active drag"); 22456 } 22457 } 22458 22459 /** 22460 * Starts a move from {startX, startY}, the amount of the movement will be the offset 22461 * between {startX, startY} and the new cursor positon. 22462 * @param startX horizontal coordinate where the move started. 22463 * @param startY vertical coordinate where the move started. 22464 * @return whether moving was started successfully. 22465 * @hide 22466 */ 22467 public final boolean startMovingTask(float startX, float startY) { 22468 if (ViewDebug.DEBUG_POSITIONING) { 22469 Log.d(VIEW_LOG_TAG, "startMovingTask: {" + startX + "," + startY + "}"); 22470 } 22471 try { 22472 return mAttachInfo.mSession.startMovingTask(mAttachInfo.mWindow, startX, startY); 22473 } catch (RemoteException e) { 22474 Log.e(VIEW_LOG_TAG, "Unable to start moving", e); 22475 } 22476 return false; 22477 } 22478 22479 /** 22480 * Handles drag events sent by the system following a call to 22481 * {@link android.view.View#startDragAndDrop(ClipData,DragShadowBuilder,Object,int) 22482 * startDragAndDrop()}. 22483 *<p> 22484 * When the system calls this method, it passes a 22485 * {@link android.view.DragEvent} object. A call to 22486 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 22487 * in DragEvent. The method uses these to determine what is happening in the drag and drop 22488 * operation. 22489 * @param event The {@link android.view.DragEvent} sent by the system. 22490 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 22491 * in DragEvent, indicating the type of drag event represented by this object. 22492 * @return {@code true} if the method was successful, otherwise {@code false}. 22493 * <p> 22494 * The method should return {@code true} in response to an action type of 22495 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 22496 * operation. 22497 * </p> 22498 * <p> 22499 * The method should also return {@code true} in response to an action type of 22500 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 22501 * {@code false} if it didn't. 22502 * </p> 22503 * <p> 22504 * For all other events, the return value is ignored. 22505 * </p> 22506 */ 22507 public boolean onDragEvent(DragEvent event) { 22508 return false; 22509 } 22510 22511 // Dispatches ACTION_DRAG_ENTERED and ACTION_DRAG_EXITED events for pre-Nougat apps. 22512 boolean dispatchDragEnterExitInPreN(DragEvent event) { 22513 return callDragEventHandler(event); 22514 } 22515 22516 /** 22517 * Detects if this View is enabled and has a drag event listener. 22518 * If both are true, then it calls the drag event listener with the 22519 * {@link android.view.DragEvent} it received. If the drag event listener returns 22520 * {@code true}, then dispatchDragEvent() returns {@code true}. 22521 * <p> 22522 * For all other cases, the method calls the 22523 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 22524 * method and returns its result. 22525 * </p> 22526 * <p> 22527 * This ensures that a drag event is always consumed, even if the View does not have a drag 22528 * event listener. However, if the View has a listener and the listener returns true, then 22529 * onDragEvent() is not called. 22530 * </p> 22531 */ 22532 public boolean dispatchDragEvent(DragEvent event) { 22533 event.mEventHandlerWasCalled = true; 22534 if (event.mAction == DragEvent.ACTION_DRAG_LOCATION || 22535 event.mAction == DragEvent.ACTION_DROP) { 22536 // About to deliver an event with coordinates to this view. Notify that now this view 22537 // has drag focus. This will send exit/enter events as needed. 22538 getViewRootImpl().setDragFocus(this, event); 22539 } 22540 return callDragEventHandler(event); 22541 } 22542 22543 final boolean callDragEventHandler(DragEvent event) { 22544 final boolean result; 22545 22546 ListenerInfo li = mListenerInfo; 22547 //noinspection SimplifiableIfStatement 22548 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 22549 && li.mOnDragListener.onDrag(this, event)) { 22550 result = true; 22551 } else { 22552 result = onDragEvent(event); 22553 } 22554 22555 switch (event.mAction) { 22556 case DragEvent.ACTION_DRAG_ENTERED: { 22557 mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED; 22558 refreshDrawableState(); 22559 } break; 22560 case DragEvent.ACTION_DRAG_EXITED: { 22561 mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED; 22562 refreshDrawableState(); 22563 } break; 22564 case DragEvent.ACTION_DRAG_ENDED: { 22565 mPrivateFlags2 &= ~View.DRAG_MASK; 22566 refreshDrawableState(); 22567 } break; 22568 } 22569 22570 return result; 22571 } 22572 22573 boolean canAcceptDrag() { 22574 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 22575 } 22576 22577 /** 22578 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 22579 * it is ever exposed at all. 22580 * @hide 22581 */ 22582 public void onCloseSystemDialogs(String reason) { 22583 } 22584 22585 /** 22586 * Given a Drawable whose bounds have been set to draw into this view, 22587 * update a Region being computed for 22588 * {@link #gatherTransparentRegion(android.graphics.Region)} so 22589 * that any non-transparent parts of the Drawable are removed from the 22590 * given transparent region. 22591 * 22592 * @param dr The Drawable whose transparency is to be applied to the region. 22593 * @param region A Region holding the current transparency information, 22594 * where any parts of the region that are set are considered to be 22595 * transparent. On return, this region will be modified to have the 22596 * transparency information reduced by the corresponding parts of the 22597 * Drawable that are not transparent. 22598 * {@hide} 22599 */ 22600 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 22601 if (DBG) { 22602 Log.i("View", "Getting transparent region for: " + this); 22603 } 22604 final Region r = dr.getTransparentRegion(); 22605 final Rect db = dr.getBounds(); 22606 final AttachInfo attachInfo = mAttachInfo; 22607 if (r != null && attachInfo != null) { 22608 final int w = getRight()-getLeft(); 22609 final int h = getBottom()-getTop(); 22610 if (db.left > 0) { 22611 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 22612 r.op(0, 0, db.left, h, Region.Op.UNION); 22613 } 22614 if (db.right < w) { 22615 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 22616 r.op(db.right, 0, w, h, Region.Op.UNION); 22617 } 22618 if (db.top > 0) { 22619 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 22620 r.op(0, 0, w, db.top, Region.Op.UNION); 22621 } 22622 if (db.bottom < h) { 22623 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 22624 r.op(0, db.bottom, w, h, Region.Op.UNION); 22625 } 22626 final int[] location = attachInfo.mTransparentLocation; 22627 getLocationInWindow(location); 22628 r.translate(location[0], location[1]); 22629 region.op(r, Region.Op.INTERSECT); 22630 } else { 22631 region.op(db, Region.Op.DIFFERENCE); 22632 } 22633 } 22634 22635 private void checkForLongClick(int delayOffset, float x, float y) { 22636 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE || (mViewFlags & TOOLTIP) == TOOLTIP) { 22637 mHasPerformedLongPress = false; 22638 22639 if (mPendingCheckForLongPress == null) { 22640 mPendingCheckForLongPress = new CheckForLongPress(); 22641 } 22642 mPendingCheckForLongPress.setAnchor(x, y); 22643 mPendingCheckForLongPress.rememberWindowAttachCount(); 22644 mPendingCheckForLongPress.rememberPressedState(); 22645 postDelayed(mPendingCheckForLongPress, 22646 ViewConfiguration.getLongPressTimeout() - delayOffset); 22647 } 22648 } 22649 22650 /** 22651 * Inflate a view from an XML resource. This convenience method wraps the {@link 22652 * LayoutInflater} class, which provides a full range of options for view inflation. 22653 * 22654 * @param context The Context object for your activity or application. 22655 * @param resource The resource ID to inflate 22656 * @param root A view group that will be the parent. Used to properly inflate the 22657 * layout_* parameters. 22658 * @see LayoutInflater 22659 */ 22660 public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 22661 LayoutInflater factory = LayoutInflater.from(context); 22662 return factory.inflate(resource, root); 22663 } 22664 22665 /** 22666 * Scroll the view with standard behavior for scrolling beyond the normal 22667 * content boundaries. Views that call this method should override 22668 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 22669 * results of an over-scroll operation. 22670 * 22671 * Views can use this method to handle any touch or fling-based scrolling. 22672 * 22673 * @param deltaX Change in X in pixels 22674 * @param deltaY Change in Y in pixels 22675 * @param scrollX Current X scroll value in pixels before applying deltaX 22676 * @param scrollY Current Y scroll value in pixels before applying deltaY 22677 * @param scrollRangeX Maximum content scroll range along the X axis 22678 * @param scrollRangeY Maximum content scroll range along the Y axis 22679 * @param maxOverScrollX Number of pixels to overscroll by in either direction 22680 * along the X axis. 22681 * @param maxOverScrollY Number of pixels to overscroll by in either direction 22682 * along the Y axis. 22683 * @param isTouchEvent true if this scroll operation is the result of a touch event. 22684 * @return true if scrolling was clamped to an over-scroll boundary along either 22685 * axis, false otherwise. 22686 */ 22687 @SuppressWarnings({"UnusedParameters"}) 22688 protected boolean overScrollBy(int deltaX, int deltaY, 22689 int scrollX, int scrollY, 22690 int scrollRangeX, int scrollRangeY, 22691 int maxOverScrollX, int maxOverScrollY, 22692 boolean isTouchEvent) { 22693 final int overScrollMode = mOverScrollMode; 22694 final boolean canScrollHorizontal = 22695 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 22696 final boolean canScrollVertical = 22697 computeVerticalScrollRange() > computeVerticalScrollExtent(); 22698 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 22699 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 22700 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 22701 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 22702 22703 int newScrollX = scrollX + deltaX; 22704 if (!overScrollHorizontal) { 22705 maxOverScrollX = 0; 22706 } 22707 22708 int newScrollY = scrollY + deltaY; 22709 if (!overScrollVertical) { 22710 maxOverScrollY = 0; 22711 } 22712 22713 // Clamp values if at the limits and record 22714 final int left = -maxOverScrollX; 22715 final int right = maxOverScrollX + scrollRangeX; 22716 final int top = -maxOverScrollY; 22717 final int bottom = maxOverScrollY + scrollRangeY; 22718 22719 boolean clampedX = false; 22720 if (newScrollX > right) { 22721 newScrollX = right; 22722 clampedX = true; 22723 } else if (newScrollX < left) { 22724 newScrollX = left; 22725 clampedX = true; 22726 } 22727 22728 boolean clampedY = false; 22729 if (newScrollY > bottom) { 22730 newScrollY = bottom; 22731 clampedY = true; 22732 } else if (newScrollY < top) { 22733 newScrollY = top; 22734 clampedY = true; 22735 } 22736 22737 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 22738 22739 return clampedX || clampedY; 22740 } 22741 22742 /** 22743 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 22744 * respond to the results of an over-scroll operation. 22745 * 22746 * @param scrollX New X scroll value in pixels 22747 * @param scrollY New Y scroll value in pixels 22748 * @param clampedX True if scrollX was clamped to an over-scroll boundary 22749 * @param clampedY True if scrollY was clamped to an over-scroll boundary 22750 */ 22751 protected void onOverScrolled(int scrollX, int scrollY, 22752 boolean clampedX, boolean clampedY) { 22753 // Intentionally empty. 22754 } 22755 22756 /** 22757 * Returns the over-scroll mode for this view. The result will be 22758 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 22759 * (allow over-scrolling only if the view content is larger than the container), 22760 * or {@link #OVER_SCROLL_NEVER}. 22761 * 22762 * @return This view's over-scroll mode. 22763 */ 22764 public int getOverScrollMode() { 22765 return mOverScrollMode; 22766 } 22767 22768 /** 22769 * Set the over-scroll mode for this view. Valid over-scroll modes are 22770 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 22771 * (allow over-scrolling only if the view content is larger than the container), 22772 * or {@link #OVER_SCROLL_NEVER}. 22773 * 22774 * Setting the over-scroll mode of a view will have an effect only if the 22775 * view is capable of scrolling. 22776 * 22777 * @param overScrollMode The new over-scroll mode for this view. 22778 */ 22779 public void setOverScrollMode(int overScrollMode) { 22780 if (overScrollMode != OVER_SCROLL_ALWAYS && 22781 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 22782 overScrollMode != OVER_SCROLL_NEVER) { 22783 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 22784 } 22785 mOverScrollMode = overScrollMode; 22786 } 22787 22788 /** 22789 * Enable or disable nested scrolling for this view. 22790 * 22791 * <p>If this property is set to true the view will be permitted to initiate nested 22792 * scrolling operations with a compatible parent view in the current hierarchy. If this 22793 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 22794 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 22795 * the nested scroll.</p> 22796 * 22797 * @param enabled true to enable nested scrolling, false to disable 22798 * 22799 * @see #isNestedScrollingEnabled() 22800 */ 22801 public void setNestedScrollingEnabled(boolean enabled) { 22802 if (enabled) { 22803 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 22804 } else { 22805 stopNestedScroll(); 22806 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 22807 } 22808 } 22809 22810 /** 22811 * Returns true if nested scrolling is enabled for this view. 22812 * 22813 * <p>If nested scrolling is enabled and this View class implementation supports it, 22814 * this view will act as a nested scrolling child view when applicable, forwarding data 22815 * about the scroll operation in progress to a compatible and cooperating nested scrolling 22816 * parent.</p> 22817 * 22818 * @return true if nested scrolling is enabled 22819 * 22820 * @see #setNestedScrollingEnabled(boolean) 22821 */ 22822 public boolean isNestedScrollingEnabled() { 22823 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 22824 PFLAG3_NESTED_SCROLLING_ENABLED; 22825 } 22826 22827 /** 22828 * Begin a nestable scroll operation along the given axes. 22829 * 22830 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 22831 * 22832 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 22833 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 22834 * In the case of touch scrolling the nested scroll will be terminated automatically in 22835 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 22836 * In the event of programmatic scrolling the caller must explicitly call 22837 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 22838 * 22839 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 22840 * If it returns false the caller may ignore the rest of this contract until the next scroll. 22841 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 22842 * 22843 * <p>At each incremental step of the scroll the caller should invoke 22844 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 22845 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 22846 * parent at least partially consumed the scroll and the caller should adjust the amount it 22847 * scrolls by.</p> 22848 * 22849 * <p>After applying the remainder of the scroll delta the caller should invoke 22850 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 22851 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 22852 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 22853 * </p> 22854 * 22855 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 22856 * {@link #SCROLL_AXIS_VERTICAL}. 22857 * @return true if a cooperative parent was found and nested scrolling has been enabled for 22858 * the current gesture. 22859 * 22860 * @see #stopNestedScroll() 22861 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 22862 * @see #dispatchNestedScroll(int, int, int, int, int[]) 22863 */ 22864 public boolean startNestedScroll(int axes) { 22865 if (hasNestedScrollingParent()) { 22866 // Already in progress 22867 return true; 22868 } 22869 if (isNestedScrollingEnabled()) { 22870 ViewParent p = getParent(); 22871 View child = this; 22872 while (p != null) { 22873 try { 22874 if (p.onStartNestedScroll(child, this, axes)) { 22875 mNestedScrollingParent = p; 22876 p.onNestedScrollAccepted(child, this, axes); 22877 return true; 22878 } 22879 } catch (AbstractMethodError e) { 22880 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 22881 "method onStartNestedScroll", e); 22882 // Allow the search upward to continue 22883 } 22884 if (p instanceof View) { 22885 child = (View) p; 22886 } 22887 p = p.getParent(); 22888 } 22889 } 22890 return false; 22891 } 22892 22893 /** 22894 * Stop a nested scroll in progress. 22895 * 22896 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 22897 * 22898 * @see #startNestedScroll(int) 22899 */ 22900 public void stopNestedScroll() { 22901 if (mNestedScrollingParent != null) { 22902 mNestedScrollingParent.onStopNestedScroll(this); 22903 mNestedScrollingParent = null; 22904 } 22905 } 22906 22907 /** 22908 * Returns true if this view has a nested scrolling parent. 22909 * 22910 * <p>The presence of a nested scrolling parent indicates that this view has initiated 22911 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 22912 * 22913 * @return whether this view has a nested scrolling parent 22914 */ 22915 public boolean hasNestedScrollingParent() { 22916 return mNestedScrollingParent != null; 22917 } 22918 22919 /** 22920 * Dispatch one step of a nested scroll in progress. 22921 * 22922 * <p>Implementations of views that support nested scrolling should call this to report 22923 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 22924 * is not currently in progress or nested scrolling is not 22925 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 22926 * 22927 * <p>Compatible View implementations should also call 22928 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 22929 * consuming a component of the scroll event themselves.</p> 22930 * 22931 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 22932 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 22933 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 22934 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 22935 * @param offsetInWindow Optional. If not null, on return this will contain the offset 22936 * in local view coordinates of this view from before this operation 22937 * to after it completes. View implementations may use this to adjust 22938 * expected input coordinate tracking. 22939 * @return true if the event was dispatched, false if it could not be dispatched. 22940 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 22941 */ 22942 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 22943 int dxUnconsumed, int dyUnconsumed, @Nullable @Size(2) int[] offsetInWindow) { 22944 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 22945 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 22946 int startX = 0; 22947 int startY = 0; 22948 if (offsetInWindow != null) { 22949 getLocationInWindow(offsetInWindow); 22950 startX = offsetInWindow[0]; 22951 startY = offsetInWindow[1]; 22952 } 22953 22954 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 22955 dxUnconsumed, dyUnconsumed); 22956 22957 if (offsetInWindow != null) { 22958 getLocationInWindow(offsetInWindow); 22959 offsetInWindow[0] -= startX; 22960 offsetInWindow[1] -= startY; 22961 } 22962 return true; 22963 } else if (offsetInWindow != null) { 22964 // No motion, no dispatch. Keep offsetInWindow up to date. 22965 offsetInWindow[0] = 0; 22966 offsetInWindow[1] = 0; 22967 } 22968 } 22969 return false; 22970 } 22971 22972 /** 22973 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 22974 * 22975 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 22976 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 22977 * scrolling operation to consume some or all of the scroll operation before the child view 22978 * consumes it.</p> 22979 * 22980 * @param dx Horizontal scroll distance in pixels 22981 * @param dy Vertical scroll distance in pixels 22982 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 22983 * and consumed[1] the consumed dy. 22984 * @param offsetInWindow Optional. If not null, on return this will contain the offset 22985 * in local view coordinates of this view from before this operation 22986 * to after it completes. View implementations may use this to adjust 22987 * expected input coordinate tracking. 22988 * @return true if the parent consumed some or all of the scroll delta 22989 * @see #dispatchNestedScroll(int, int, int, int, int[]) 22990 */ 22991 public boolean dispatchNestedPreScroll(int dx, int dy, 22992 @Nullable @Size(2) int[] consumed, @Nullable @Size(2) int[] offsetInWindow) { 22993 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 22994 if (dx != 0 || dy != 0) { 22995 int startX = 0; 22996 int startY = 0; 22997 if (offsetInWindow != null) { 22998 getLocationInWindow(offsetInWindow); 22999 startX = offsetInWindow[0]; 23000 startY = offsetInWindow[1]; 23001 } 23002 23003 if (consumed == null) { 23004 if (mTempNestedScrollConsumed == null) { 23005 mTempNestedScrollConsumed = new int[2]; 23006 } 23007 consumed = mTempNestedScrollConsumed; 23008 } 23009 consumed[0] = 0; 23010 consumed[1] = 0; 23011 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 23012 23013 if (offsetInWindow != null) { 23014 getLocationInWindow(offsetInWindow); 23015 offsetInWindow[0] -= startX; 23016 offsetInWindow[1] -= startY; 23017 } 23018 return consumed[0] != 0 || consumed[1] != 0; 23019 } else if (offsetInWindow != null) { 23020 offsetInWindow[0] = 0; 23021 offsetInWindow[1] = 0; 23022 } 23023 } 23024 return false; 23025 } 23026 23027 /** 23028 * Dispatch a fling to a nested scrolling parent. 23029 * 23030 * <p>This method should be used to indicate that a nested scrolling child has detected 23031 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 23032 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 23033 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 23034 * along a scrollable axis.</p> 23035 * 23036 * <p>If a nested scrolling child view would normally fling but it is at the edge of 23037 * its own content, it can use this method to delegate the fling to its nested scrolling 23038 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 23039 * 23040 * @param velocityX Horizontal fling velocity in pixels per second 23041 * @param velocityY Vertical fling velocity in pixels per second 23042 * @param consumed true if the child consumed the fling, false otherwise 23043 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 23044 */ 23045 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 23046 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23047 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 23048 } 23049 return false; 23050 } 23051 23052 /** 23053 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 23054 * 23055 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 23056 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 23057 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 23058 * before the child view consumes it. If this method returns <code>true</code>, a nested 23059 * parent view consumed the fling and this view should not scroll as a result.</p> 23060 * 23061 * <p>For a better user experience, only one view in a nested scrolling chain should consume 23062 * the fling at a time. If a parent view consumed the fling this method will return false. 23063 * Custom view implementations should account for this in two ways:</p> 23064 * 23065 * <ul> 23066 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 23067 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 23068 * position regardless.</li> 23069 * <li>If a nested parent does consume the fling, this view should not scroll at all, 23070 * even to settle back to a valid idle position.</li> 23071 * </ul> 23072 * 23073 * <p>Views should also not offer fling velocities to nested parent views along an axis 23074 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 23075 * should not offer a horizontal fling velocity to its parents since scrolling along that 23076 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 23077 * 23078 * @param velocityX Horizontal fling velocity in pixels per second 23079 * @param velocityY Vertical fling velocity in pixels per second 23080 * @return true if a nested scrolling parent consumed the fling 23081 */ 23082 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 23083 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 23084 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 23085 } 23086 return false; 23087 } 23088 23089 /** 23090 * Gets a scale factor that determines the distance the view should scroll 23091 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 23092 * @return The vertical scroll scale factor. 23093 * @hide 23094 */ 23095 protected float getVerticalScrollFactor() { 23096 if (mVerticalScrollFactor == 0) { 23097 TypedValue outValue = new TypedValue(); 23098 if (!mContext.getTheme().resolveAttribute( 23099 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 23100 throw new IllegalStateException( 23101 "Expected theme to define listPreferredItemHeight."); 23102 } 23103 mVerticalScrollFactor = outValue.getDimension( 23104 mContext.getResources().getDisplayMetrics()); 23105 } 23106 return mVerticalScrollFactor; 23107 } 23108 23109 /** 23110 * Gets a scale factor that determines the distance the view should scroll 23111 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 23112 * @return The horizontal scroll scale factor. 23113 * @hide 23114 */ 23115 protected float getHorizontalScrollFactor() { 23116 // TODO: Should use something else. 23117 return getVerticalScrollFactor(); 23118 } 23119 23120 /** 23121 * Return the value specifying the text direction or policy that was set with 23122 * {@link #setTextDirection(int)}. 23123 * 23124 * @return the defined text direction. It can be one of: 23125 * 23126 * {@link #TEXT_DIRECTION_INHERIT}, 23127 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23128 * {@link #TEXT_DIRECTION_ANY_RTL}, 23129 * {@link #TEXT_DIRECTION_LTR}, 23130 * {@link #TEXT_DIRECTION_RTL}, 23131 * {@link #TEXT_DIRECTION_LOCALE}, 23132 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23133 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 23134 * 23135 * @attr ref android.R.styleable#View_textDirection 23136 * 23137 * @hide 23138 */ 23139 @ViewDebug.ExportedProperty(category = "text", mapping = { 23140 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 23141 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 23142 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 23143 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 23144 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 23145 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 23146 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 23147 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 23148 }) 23149 public int getRawTextDirection() { 23150 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 23151 } 23152 23153 /** 23154 * Set the text direction. 23155 * 23156 * @param textDirection the direction to set. Should be one of: 23157 * 23158 * {@link #TEXT_DIRECTION_INHERIT}, 23159 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23160 * {@link #TEXT_DIRECTION_ANY_RTL}, 23161 * {@link #TEXT_DIRECTION_LTR}, 23162 * {@link #TEXT_DIRECTION_RTL}, 23163 * {@link #TEXT_DIRECTION_LOCALE} 23164 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23165 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL}, 23166 * 23167 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 23168 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 23169 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 23170 * 23171 * @attr ref android.R.styleable#View_textDirection 23172 */ 23173 public void setTextDirection(int textDirection) { 23174 if (getRawTextDirection() != textDirection) { 23175 // Reset the current text direction and the resolved one 23176 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 23177 resetResolvedTextDirection(); 23178 // Set the new text direction 23179 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 23180 // Do resolution 23181 resolveTextDirection(); 23182 // Notify change 23183 onRtlPropertiesChanged(getLayoutDirection()); 23184 // Refresh 23185 requestLayout(); 23186 invalidate(true); 23187 } 23188 } 23189 23190 /** 23191 * Return the resolved text direction. 23192 * 23193 * @return the resolved text direction. Returns one of: 23194 * 23195 * {@link #TEXT_DIRECTION_FIRST_STRONG}, 23196 * {@link #TEXT_DIRECTION_ANY_RTL}, 23197 * {@link #TEXT_DIRECTION_LTR}, 23198 * {@link #TEXT_DIRECTION_RTL}, 23199 * {@link #TEXT_DIRECTION_LOCALE}, 23200 * {@link #TEXT_DIRECTION_FIRST_STRONG_LTR}, 23201 * {@link #TEXT_DIRECTION_FIRST_STRONG_RTL} 23202 * 23203 * @attr ref android.R.styleable#View_textDirection 23204 */ 23205 @ViewDebug.ExportedProperty(category = "text", mapping = { 23206 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 23207 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 23208 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 23209 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 23210 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 23211 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE"), 23212 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_LTR, to = "FIRST_STRONG_LTR"), 23213 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG_RTL, to = "FIRST_STRONG_RTL") 23214 }) 23215 public int getTextDirection() { 23216 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 23217 } 23218 23219 /** 23220 * Resolve the text direction. 23221 * 23222 * @return true if resolution has been done, false otherwise. 23223 * 23224 * @hide 23225 */ 23226 public boolean resolveTextDirection() { 23227 // Reset any previous text direction resolution 23228 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 23229 23230 if (hasRtlSupport()) { 23231 // Set resolved text direction flag depending on text direction flag 23232 final int textDirection = getRawTextDirection(); 23233 switch(textDirection) { 23234 case TEXT_DIRECTION_INHERIT: 23235 if (!canResolveTextDirection()) { 23236 // We cannot do the resolution if there is no parent, so use the default one 23237 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23238 // Resolution will need to happen again later 23239 return false; 23240 } 23241 23242 // Parent has not yet resolved, so we still return the default 23243 try { 23244 if (!mParent.isTextDirectionResolved()) { 23245 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23246 // Resolution will need to happen again later 23247 return false; 23248 } 23249 } catch (AbstractMethodError e) { 23250 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23251 " does not fully implement ViewParent", e); 23252 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 23253 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23254 return true; 23255 } 23256 23257 // Set current resolved direction to the same value as the parent's one 23258 int parentResolvedDirection; 23259 try { 23260 parentResolvedDirection = mParent.getTextDirection(); 23261 } catch (AbstractMethodError e) { 23262 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23263 " does not fully implement ViewParent", e); 23264 parentResolvedDirection = TEXT_DIRECTION_LTR; 23265 } 23266 switch (parentResolvedDirection) { 23267 case TEXT_DIRECTION_FIRST_STRONG: 23268 case TEXT_DIRECTION_ANY_RTL: 23269 case TEXT_DIRECTION_LTR: 23270 case TEXT_DIRECTION_RTL: 23271 case TEXT_DIRECTION_LOCALE: 23272 case TEXT_DIRECTION_FIRST_STRONG_LTR: 23273 case TEXT_DIRECTION_FIRST_STRONG_RTL: 23274 mPrivateFlags2 |= 23275 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 23276 break; 23277 default: 23278 // Default resolved direction is "first strong" heuristic 23279 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23280 } 23281 break; 23282 case TEXT_DIRECTION_FIRST_STRONG: 23283 case TEXT_DIRECTION_ANY_RTL: 23284 case TEXT_DIRECTION_LTR: 23285 case TEXT_DIRECTION_RTL: 23286 case TEXT_DIRECTION_LOCALE: 23287 case TEXT_DIRECTION_FIRST_STRONG_LTR: 23288 case TEXT_DIRECTION_FIRST_STRONG_RTL: 23289 // Resolved direction is the same as text direction 23290 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 23291 break; 23292 default: 23293 // Default resolved direction is "first strong" heuristic 23294 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23295 } 23296 } else { 23297 // Default resolved direction is "first strong" heuristic 23298 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23299 } 23300 23301 // Set to resolved 23302 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 23303 return true; 23304 } 23305 23306 /** 23307 * Check if text direction resolution can be done. 23308 * 23309 * @return true if text direction resolution can be done otherwise return false. 23310 */ 23311 public boolean canResolveTextDirection() { 23312 switch (getRawTextDirection()) { 23313 case TEXT_DIRECTION_INHERIT: 23314 if (mParent != null) { 23315 try { 23316 return mParent.canResolveTextDirection(); 23317 } catch (AbstractMethodError e) { 23318 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23319 " does not fully implement ViewParent", e); 23320 } 23321 } 23322 return false; 23323 23324 default: 23325 return true; 23326 } 23327 } 23328 23329 /** 23330 * Reset resolved text direction. Text direction will be resolved during a call to 23331 * {@link #onMeasure(int, int)}. 23332 * 23333 * @hide 23334 */ 23335 public void resetResolvedTextDirection() { 23336 // Reset any previous text direction resolution 23337 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 23338 // Set to default value 23339 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 23340 } 23341 23342 /** 23343 * @return true if text direction is inherited. 23344 * 23345 * @hide 23346 */ 23347 public boolean isTextDirectionInherited() { 23348 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 23349 } 23350 23351 /** 23352 * @return true if text direction is resolved. 23353 */ 23354 public boolean isTextDirectionResolved() { 23355 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 23356 } 23357 23358 /** 23359 * Return the value specifying the text alignment or policy that was set with 23360 * {@link #setTextAlignment(int)}. 23361 * 23362 * @return the defined text alignment. It can be one of: 23363 * 23364 * {@link #TEXT_ALIGNMENT_INHERIT}, 23365 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23366 * {@link #TEXT_ALIGNMENT_CENTER}, 23367 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23368 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23369 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23370 * {@link #TEXT_ALIGNMENT_VIEW_END} 23371 * 23372 * @attr ref android.R.styleable#View_textAlignment 23373 * 23374 * @hide 23375 */ 23376 @ViewDebug.ExportedProperty(category = "text", mapping = { 23377 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 23378 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 23379 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 23380 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 23381 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 23382 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 23383 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 23384 }) 23385 @TextAlignment 23386 public int getRawTextAlignment() { 23387 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 23388 } 23389 23390 /** 23391 * Set the text alignment. 23392 * 23393 * @param textAlignment The text alignment to set. Should be one of 23394 * 23395 * {@link #TEXT_ALIGNMENT_INHERIT}, 23396 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23397 * {@link #TEXT_ALIGNMENT_CENTER}, 23398 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23399 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23400 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23401 * {@link #TEXT_ALIGNMENT_VIEW_END} 23402 * 23403 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 23404 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 23405 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 23406 * 23407 * @attr ref android.R.styleable#View_textAlignment 23408 */ 23409 public void setTextAlignment(@TextAlignment int textAlignment) { 23410 if (textAlignment != getRawTextAlignment()) { 23411 // Reset the current and resolved text alignment 23412 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 23413 resetResolvedTextAlignment(); 23414 // Set the new text alignment 23415 mPrivateFlags2 |= 23416 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 23417 // Do resolution 23418 resolveTextAlignment(); 23419 // Notify change 23420 onRtlPropertiesChanged(getLayoutDirection()); 23421 // Refresh 23422 requestLayout(); 23423 invalidate(true); 23424 } 23425 } 23426 23427 /** 23428 * Return the resolved text alignment. 23429 * 23430 * @return the resolved text alignment. Returns one of: 23431 * 23432 * {@link #TEXT_ALIGNMENT_GRAVITY}, 23433 * {@link #TEXT_ALIGNMENT_CENTER}, 23434 * {@link #TEXT_ALIGNMENT_TEXT_START}, 23435 * {@link #TEXT_ALIGNMENT_TEXT_END}, 23436 * {@link #TEXT_ALIGNMENT_VIEW_START}, 23437 * {@link #TEXT_ALIGNMENT_VIEW_END} 23438 * 23439 * @attr ref android.R.styleable#View_textAlignment 23440 */ 23441 @ViewDebug.ExportedProperty(category = "text", mapping = { 23442 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 23443 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 23444 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 23445 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 23446 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 23447 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 23448 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 23449 }) 23450 @TextAlignment 23451 public int getTextAlignment() { 23452 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 23453 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 23454 } 23455 23456 /** 23457 * Resolve the text alignment. 23458 * 23459 * @return true if resolution has been done, false otherwise. 23460 * 23461 * @hide 23462 */ 23463 public boolean resolveTextAlignment() { 23464 // Reset any previous text alignment resolution 23465 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 23466 23467 if (hasRtlSupport()) { 23468 // Set resolved text alignment flag depending on text alignment flag 23469 final int textAlignment = getRawTextAlignment(); 23470 switch (textAlignment) { 23471 case TEXT_ALIGNMENT_INHERIT: 23472 // Check if we can resolve the text alignment 23473 if (!canResolveTextAlignment()) { 23474 // We cannot do the resolution if there is no parent so use the default 23475 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23476 // Resolution will need to happen again later 23477 return false; 23478 } 23479 23480 // Parent has not yet resolved, so we still return the default 23481 try { 23482 if (!mParent.isTextAlignmentResolved()) { 23483 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23484 // Resolution will need to happen again later 23485 return false; 23486 } 23487 } catch (AbstractMethodError e) { 23488 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23489 " does not fully implement ViewParent", e); 23490 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 23491 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23492 return true; 23493 } 23494 23495 int parentResolvedTextAlignment; 23496 try { 23497 parentResolvedTextAlignment = mParent.getTextAlignment(); 23498 } catch (AbstractMethodError e) { 23499 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23500 " does not fully implement ViewParent", e); 23501 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 23502 } 23503 switch (parentResolvedTextAlignment) { 23504 case TEXT_ALIGNMENT_GRAVITY: 23505 case TEXT_ALIGNMENT_TEXT_START: 23506 case TEXT_ALIGNMENT_TEXT_END: 23507 case TEXT_ALIGNMENT_CENTER: 23508 case TEXT_ALIGNMENT_VIEW_START: 23509 case TEXT_ALIGNMENT_VIEW_END: 23510 // Resolved text alignment is the same as the parent resolved 23511 // text alignment 23512 mPrivateFlags2 |= 23513 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 23514 break; 23515 default: 23516 // Use default resolved text alignment 23517 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23518 } 23519 break; 23520 case TEXT_ALIGNMENT_GRAVITY: 23521 case TEXT_ALIGNMENT_TEXT_START: 23522 case TEXT_ALIGNMENT_TEXT_END: 23523 case TEXT_ALIGNMENT_CENTER: 23524 case TEXT_ALIGNMENT_VIEW_START: 23525 case TEXT_ALIGNMENT_VIEW_END: 23526 // Resolved text alignment is the same as text alignment 23527 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 23528 break; 23529 default: 23530 // Use default resolved text alignment 23531 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23532 } 23533 } else { 23534 // Use default resolved text alignment 23535 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23536 } 23537 23538 // Set the resolved 23539 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 23540 return true; 23541 } 23542 23543 /** 23544 * Check if text alignment resolution can be done. 23545 * 23546 * @return true if text alignment resolution can be done otherwise return false. 23547 */ 23548 public boolean canResolveTextAlignment() { 23549 switch (getRawTextAlignment()) { 23550 case TEXT_DIRECTION_INHERIT: 23551 if (mParent != null) { 23552 try { 23553 return mParent.canResolveTextAlignment(); 23554 } catch (AbstractMethodError e) { 23555 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 23556 " does not fully implement ViewParent", e); 23557 } 23558 } 23559 return false; 23560 23561 default: 23562 return true; 23563 } 23564 } 23565 23566 /** 23567 * Reset resolved text alignment. Text alignment will be resolved during a call to 23568 * {@link #onMeasure(int, int)}. 23569 * 23570 * @hide 23571 */ 23572 public void resetResolvedTextAlignment() { 23573 // Reset any previous text alignment resolution 23574 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 23575 // Set to default 23576 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 23577 } 23578 23579 /** 23580 * @return true if text alignment is inherited. 23581 * 23582 * @hide 23583 */ 23584 public boolean isTextAlignmentInherited() { 23585 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 23586 } 23587 23588 /** 23589 * @return true if text alignment is resolved. 23590 */ 23591 public boolean isTextAlignmentResolved() { 23592 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 23593 } 23594 23595 /** 23596 * Generate a value suitable for use in {@link #setId(int)}. 23597 * This value will not collide with ID values generated at build time by aapt for R.id. 23598 * 23599 * @return a generated ID value 23600 */ 23601 public static int generateViewId() { 23602 for (;;) { 23603 final int result = sNextGeneratedId.get(); 23604 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 23605 int newValue = result + 1; 23606 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 23607 if (sNextGeneratedId.compareAndSet(result, newValue)) { 23608 return result; 23609 } 23610 } 23611 } 23612 23613 private static boolean isViewIdGenerated(int id) { 23614 return (id & 0xFF000000) == 0 && (id & 0x00FFFFFF) != 0; 23615 } 23616 23617 /** 23618 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 23619 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 23620 * a normal View or a ViewGroup with 23621 * {@link android.view.ViewGroup#isTransitionGroup()} true. 23622 * @hide 23623 */ 23624 public void captureTransitioningViews(List<View> transitioningViews) { 23625 if (getVisibility() == View.VISIBLE) { 23626 transitioningViews.add(this); 23627 } 23628 } 23629 23630 /** 23631 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 23632 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 23633 * @hide 23634 */ 23635 public void findNamedViews(Map<String, View> namedElements) { 23636 if (getVisibility() == VISIBLE || mGhostView != null) { 23637 String transitionName = getTransitionName(); 23638 if (transitionName != null) { 23639 namedElements.put(transitionName, this); 23640 } 23641 } 23642 } 23643 23644 /** 23645 * Returns the pointer icon for the motion event, or null if it doesn't specify the icon. 23646 * The default implementation does not care the location or event types, but some subclasses 23647 * may use it (such as WebViews). 23648 * @param event The MotionEvent from a mouse 23649 * @param pointerIndex The index of the pointer for which to retrieve the {@link PointerIcon}. 23650 * This will be between 0 and {@link MotionEvent#getPointerCount()}. 23651 * @see PointerIcon 23652 */ 23653 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 23654 final float x = event.getX(pointerIndex); 23655 final float y = event.getY(pointerIndex); 23656 if (isDraggingScrollBar() || isOnScrollbarThumb(x, y)) { 23657 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_ARROW); 23658 } 23659 return mPointerIcon; 23660 } 23661 23662 /** 23663 * Set the pointer icon for the current view. 23664 * Passing {@code null} will restore the pointer icon to its default value. 23665 * @param pointerIcon A PointerIcon instance which will be shown when the mouse hovers. 23666 */ 23667 public void setPointerIcon(PointerIcon pointerIcon) { 23668 mPointerIcon = pointerIcon; 23669 if (mAttachInfo == null || mAttachInfo.mHandlingPointerEvent) { 23670 return; 23671 } 23672 try { 23673 mAttachInfo.mSession.updatePointerIcon(mAttachInfo.mWindow); 23674 } catch (RemoteException e) { 23675 } 23676 } 23677 23678 /** 23679 * Gets the pointer icon for the current view. 23680 */ 23681 public PointerIcon getPointerIcon() { 23682 return mPointerIcon; 23683 } 23684 23685 /** 23686 * Checks pointer capture status. 23687 * 23688 * @return true if the view has pointer capture. 23689 * @see #requestPointerCapture() 23690 * @see #hasPointerCapture() 23691 */ 23692 public boolean hasPointerCapture() { 23693 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23694 if (viewRootImpl == null) { 23695 return false; 23696 } 23697 return viewRootImpl.hasPointerCapture(); 23698 } 23699 23700 /** 23701 * Requests pointer capture mode. 23702 * <p> 23703 * When the window has pointer capture, the mouse pointer icon will disappear and will not 23704 * change its position. Further mouse will be dispatched with the source 23705 * {@link InputDevice#SOURCE_MOUSE_RELATIVE}, and relative position changes will be available 23706 * through {@link MotionEvent#getX} and {@link MotionEvent#getY}. Non-mouse events 23707 * (touchscreens, or stylus) will not be affected. 23708 * <p> 23709 * If the window already has pointer capture, this call does nothing. 23710 * <p> 23711 * The capture may be released through {@link #releasePointerCapture()}, or will be lost 23712 * automatically when the window loses focus. 23713 * 23714 * @see #releasePointerCapture() 23715 * @see #hasPointerCapture() 23716 */ 23717 public void requestPointerCapture() { 23718 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23719 if (viewRootImpl != null) { 23720 viewRootImpl.requestPointerCapture(true); 23721 } 23722 } 23723 23724 23725 /** 23726 * Releases the pointer capture. 23727 * <p> 23728 * If the window does not have pointer capture, this call will do nothing. 23729 * @see #requestPointerCapture() 23730 * @see #hasPointerCapture() 23731 */ 23732 public void releasePointerCapture() { 23733 final ViewRootImpl viewRootImpl = getViewRootImpl(); 23734 if (viewRootImpl != null) { 23735 viewRootImpl.requestPointerCapture(false); 23736 } 23737 } 23738 23739 /** 23740 * Called when the window has just acquired or lost pointer capture. 23741 * 23742 * @param hasCapture True if the view now has pointerCapture, false otherwise. 23743 */ 23744 @CallSuper 23745 public void onPointerCaptureChange(boolean hasCapture) { 23746 } 23747 23748 /** 23749 * @see #onPointerCaptureChange 23750 */ 23751 public void dispatchPointerCaptureChanged(boolean hasCapture) { 23752 onPointerCaptureChange(hasCapture); 23753 } 23754 23755 /** 23756 * Implement this method to handle captured pointer events 23757 * 23758 * @param event The captured pointer event. 23759 * @return True if the event was handled, false otherwise. 23760 * @see #requestPointerCapture() 23761 */ 23762 public boolean onCapturedPointerEvent(MotionEvent event) { 23763 return false; 23764 } 23765 23766 /** 23767 * Interface definition for a callback to be invoked when a captured pointer event 23768 * is being dispatched this view. The callback will be invoked before the event is 23769 * given to the view. 23770 */ 23771 public interface OnCapturedPointerListener { 23772 /** 23773 * Called when a captured pointer event is dispatched to a view. 23774 * @param view The view this event has been dispatched to. 23775 * @param event The captured event. 23776 * @return True if the listener has consumed the event, false otherwise. 23777 */ 23778 boolean onCapturedPointer(View view, MotionEvent event); 23779 } 23780 23781 /** 23782 * Set a listener to receive callbacks when the pointer capture state of a view changes. 23783 * @param l The {@link OnCapturedPointerListener} to receive callbacks. 23784 */ 23785 public void setOnCapturedPointerListener(OnCapturedPointerListener l) { 23786 getListenerInfo().mOnCapturedPointerListener = l; 23787 } 23788 23789 // Properties 23790 // 23791 /** 23792 * A Property wrapper around the <code>alpha</code> functionality handled by the 23793 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 23794 */ 23795 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 23796 @Override 23797 public void setValue(View object, float value) { 23798 object.setAlpha(value); 23799 } 23800 23801 @Override 23802 public Float get(View object) { 23803 return object.getAlpha(); 23804 } 23805 }; 23806 23807 /** 23808 * A Property wrapper around the <code>translationX</code> functionality handled by the 23809 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 23810 */ 23811 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 23812 @Override 23813 public void setValue(View object, float value) { 23814 object.setTranslationX(value); 23815 } 23816 23817 @Override 23818 public Float get(View object) { 23819 return object.getTranslationX(); 23820 } 23821 }; 23822 23823 /** 23824 * A Property wrapper around the <code>translationY</code> functionality handled by the 23825 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 23826 */ 23827 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 23828 @Override 23829 public void setValue(View object, float value) { 23830 object.setTranslationY(value); 23831 } 23832 23833 @Override 23834 public Float get(View object) { 23835 return object.getTranslationY(); 23836 } 23837 }; 23838 23839 /** 23840 * A Property wrapper around the <code>translationZ</code> functionality handled by the 23841 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 23842 */ 23843 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 23844 @Override 23845 public void setValue(View object, float value) { 23846 object.setTranslationZ(value); 23847 } 23848 23849 @Override 23850 public Float get(View object) { 23851 return object.getTranslationZ(); 23852 } 23853 }; 23854 23855 /** 23856 * A Property wrapper around the <code>x</code> functionality handled by the 23857 * {@link View#setX(float)} and {@link View#getX()} methods. 23858 */ 23859 public static final Property<View, Float> X = new FloatProperty<View>("x") { 23860 @Override 23861 public void setValue(View object, float value) { 23862 object.setX(value); 23863 } 23864 23865 @Override 23866 public Float get(View object) { 23867 return object.getX(); 23868 } 23869 }; 23870 23871 /** 23872 * A Property wrapper around the <code>y</code> functionality handled by the 23873 * {@link View#setY(float)} and {@link View#getY()} methods. 23874 */ 23875 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 23876 @Override 23877 public void setValue(View object, float value) { 23878 object.setY(value); 23879 } 23880 23881 @Override 23882 public Float get(View object) { 23883 return object.getY(); 23884 } 23885 }; 23886 23887 /** 23888 * A Property wrapper around the <code>z</code> functionality handled by the 23889 * {@link View#setZ(float)} and {@link View#getZ()} methods. 23890 */ 23891 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 23892 @Override 23893 public void setValue(View object, float value) { 23894 object.setZ(value); 23895 } 23896 23897 @Override 23898 public Float get(View object) { 23899 return object.getZ(); 23900 } 23901 }; 23902 23903 /** 23904 * A Property wrapper around the <code>rotation</code> functionality handled by the 23905 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 23906 */ 23907 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 23908 @Override 23909 public void setValue(View object, float value) { 23910 object.setRotation(value); 23911 } 23912 23913 @Override 23914 public Float get(View object) { 23915 return object.getRotation(); 23916 } 23917 }; 23918 23919 /** 23920 * A Property wrapper around the <code>rotationX</code> functionality handled by the 23921 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 23922 */ 23923 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 23924 @Override 23925 public void setValue(View object, float value) { 23926 object.setRotationX(value); 23927 } 23928 23929 @Override 23930 public Float get(View object) { 23931 return object.getRotationX(); 23932 } 23933 }; 23934 23935 /** 23936 * A Property wrapper around the <code>rotationY</code> functionality handled by the 23937 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 23938 */ 23939 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 23940 @Override 23941 public void setValue(View object, float value) { 23942 object.setRotationY(value); 23943 } 23944 23945 @Override 23946 public Float get(View object) { 23947 return object.getRotationY(); 23948 } 23949 }; 23950 23951 /** 23952 * A Property wrapper around the <code>scaleX</code> functionality handled by the 23953 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 23954 */ 23955 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 23956 @Override 23957 public void setValue(View object, float value) { 23958 object.setScaleX(value); 23959 } 23960 23961 @Override 23962 public Float get(View object) { 23963 return object.getScaleX(); 23964 } 23965 }; 23966 23967 /** 23968 * A Property wrapper around the <code>scaleY</code> functionality handled by the 23969 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 23970 */ 23971 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 23972 @Override 23973 public void setValue(View object, float value) { 23974 object.setScaleY(value); 23975 } 23976 23977 @Override 23978 public Float get(View object) { 23979 return object.getScaleY(); 23980 } 23981 }; 23982 23983 /** 23984 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 23985 * Each MeasureSpec represents a requirement for either the width or the height. 23986 * A MeasureSpec is comprised of a size and a mode. There are three possible 23987 * modes: 23988 * <dl> 23989 * <dt>UNSPECIFIED</dt> 23990 * <dd> 23991 * The parent has not imposed any constraint on the child. It can be whatever size 23992 * it wants. 23993 * </dd> 23994 * 23995 * <dt>EXACTLY</dt> 23996 * <dd> 23997 * The parent has determined an exact size for the child. The child is going to be 23998 * given those bounds regardless of how big it wants to be. 23999 * </dd> 24000 * 24001 * <dt>AT_MOST</dt> 24002 * <dd> 24003 * The child can be as large as it wants up to the specified size. 24004 * </dd> 24005 * </dl> 24006 * 24007 * MeasureSpecs are implemented as ints to reduce object allocation. This class 24008 * is provided to pack and unpack the <size, mode> tuple into the int. 24009 */ 24010 public static class MeasureSpec { 24011 private static final int MODE_SHIFT = 30; 24012 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 24013 24014 /** @hide */ 24015 @IntDef({UNSPECIFIED, EXACTLY, AT_MOST}) 24016 @Retention(RetentionPolicy.SOURCE) 24017 public @interface MeasureSpecMode {} 24018 24019 /** 24020 * Measure specification mode: The parent has not imposed any constraint 24021 * on the child. It can be whatever size it wants. 24022 */ 24023 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 24024 24025 /** 24026 * Measure specification mode: The parent has determined an exact size 24027 * for the child. The child is going to be given those bounds regardless 24028 * of how big it wants to be. 24029 */ 24030 public static final int EXACTLY = 1 << MODE_SHIFT; 24031 24032 /** 24033 * Measure specification mode: The child can be as large as it wants up 24034 * to the specified size. 24035 */ 24036 public static final int AT_MOST = 2 << MODE_SHIFT; 24037 24038 /** 24039 * Creates a measure specification based on the supplied size and mode. 24040 * 24041 * The mode must always be one of the following: 24042 * <ul> 24043 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 24044 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 24045 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 24046 * </ul> 24047 * 24048 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 24049 * implementation was such that the order of arguments did not matter 24050 * and overflow in either value could impact the resulting MeasureSpec. 24051 * {@link android.widget.RelativeLayout} was affected by this bug. 24052 * Apps targeting API levels greater than 17 will get the fixed, more strict 24053 * behavior.</p> 24054 * 24055 * @param size the size of the measure specification 24056 * @param mode the mode of the measure specification 24057 * @return the measure specification based on size and mode 24058 */ 24059 public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size, 24060 @MeasureSpecMode int mode) { 24061 if (sUseBrokenMakeMeasureSpec) { 24062 return size + mode; 24063 } else { 24064 return (size & ~MODE_MASK) | (mode & MODE_MASK); 24065 } 24066 } 24067 24068 /** 24069 * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED 24070 * will automatically get a size of 0. Older apps expect this. 24071 * 24072 * @hide internal use only for compatibility with system widgets and older apps 24073 */ 24074 public static int makeSafeMeasureSpec(int size, int mode) { 24075 if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) { 24076 return 0; 24077 } 24078 return makeMeasureSpec(size, mode); 24079 } 24080 24081 /** 24082 * Extracts the mode from the supplied measure specification. 24083 * 24084 * @param measureSpec the measure specification to extract the mode from 24085 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 24086 * {@link android.view.View.MeasureSpec#AT_MOST} or 24087 * {@link android.view.View.MeasureSpec#EXACTLY} 24088 */ 24089 @MeasureSpecMode 24090 public static int getMode(int measureSpec) { 24091 //noinspection ResourceType 24092 return (measureSpec & MODE_MASK); 24093 } 24094 24095 /** 24096 * Extracts the size from the supplied measure specification. 24097 * 24098 * @param measureSpec the measure specification to extract the size from 24099 * @return the size in pixels defined in the supplied measure specification 24100 */ 24101 public static int getSize(int measureSpec) { 24102 return (measureSpec & ~MODE_MASK); 24103 } 24104 24105 static int adjust(int measureSpec, int delta) { 24106 final int mode = getMode(measureSpec); 24107 int size = getSize(measureSpec); 24108 if (mode == UNSPECIFIED) { 24109 // No need to adjust size for UNSPECIFIED mode. 24110 return makeMeasureSpec(size, UNSPECIFIED); 24111 } 24112 size += delta; 24113 if (size < 0) { 24114 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 24115 ") spec: " + toString(measureSpec) + " delta: " + delta); 24116 size = 0; 24117 } 24118 return makeMeasureSpec(size, mode); 24119 } 24120 24121 /** 24122 * Returns a String representation of the specified measure 24123 * specification. 24124 * 24125 * @param measureSpec the measure specification to convert to a String 24126 * @return a String with the following format: "MeasureSpec: MODE SIZE" 24127 */ 24128 public static String toString(int measureSpec) { 24129 int mode = getMode(measureSpec); 24130 int size = getSize(measureSpec); 24131 24132 StringBuilder sb = new StringBuilder("MeasureSpec: "); 24133 24134 if (mode == UNSPECIFIED) 24135 sb.append("UNSPECIFIED "); 24136 else if (mode == EXACTLY) 24137 sb.append("EXACTLY "); 24138 else if (mode == AT_MOST) 24139 sb.append("AT_MOST "); 24140 else 24141 sb.append(mode).append(" "); 24142 24143 sb.append(size); 24144 return sb.toString(); 24145 } 24146 } 24147 24148 private final class CheckForLongPress implements Runnable { 24149 private int mOriginalWindowAttachCount; 24150 private float mX; 24151 private float mY; 24152 private boolean mOriginalPressedState; 24153 24154 @Override 24155 public void run() { 24156 if ((mOriginalPressedState == isPressed()) && (mParent != null) 24157 && mOriginalWindowAttachCount == mWindowAttachCount) { 24158 if (performLongClick(mX, mY)) { 24159 mHasPerformedLongPress = true; 24160 } 24161 } 24162 } 24163 24164 public void setAnchor(float x, float y) { 24165 mX = x; 24166 mY = y; 24167 } 24168 24169 public void rememberWindowAttachCount() { 24170 mOriginalWindowAttachCount = mWindowAttachCount; 24171 } 24172 24173 public void rememberPressedState() { 24174 mOriginalPressedState = isPressed(); 24175 } 24176 } 24177 24178 private final class CheckForTap implements Runnable { 24179 public float x; 24180 public float y; 24181 24182 @Override 24183 public void run() { 24184 mPrivateFlags &= ~PFLAG_PREPRESSED; 24185 setPressed(true, x, y); 24186 checkForLongClick(ViewConfiguration.getTapTimeout(), x, y); 24187 } 24188 } 24189 24190 private final class PerformClick implements Runnable { 24191 @Override 24192 public void run() { 24193 performClick(); 24194 } 24195 } 24196 24197 /** 24198 * This method returns a ViewPropertyAnimator object, which can be used to animate 24199 * specific properties on this View. 24200 * 24201 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 24202 */ 24203 public ViewPropertyAnimator animate() { 24204 if (mAnimator == null) { 24205 mAnimator = new ViewPropertyAnimator(this); 24206 } 24207 return mAnimator; 24208 } 24209 24210 /** 24211 * Sets the name of the View to be used to identify Views in Transitions. 24212 * Names should be unique in the View hierarchy. 24213 * 24214 * @param transitionName The name of the View to uniquely identify it for Transitions. 24215 */ 24216 public final void setTransitionName(String transitionName) { 24217 mTransitionName = transitionName; 24218 } 24219 24220 /** 24221 * Returns the name of the View to be used to identify Views in Transitions. 24222 * Names should be unique in the View hierarchy. 24223 * 24224 * <p>This returns null if the View has not been given a name.</p> 24225 * 24226 * @return The name used of the View to be used to identify Views in Transitions or null 24227 * if no name has been given. 24228 */ 24229 @ViewDebug.ExportedProperty 24230 public String getTransitionName() { 24231 return mTransitionName; 24232 } 24233 24234 /** 24235 * @hide 24236 */ 24237 public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> data, int deviceId) { 24238 // Do nothing. 24239 } 24240 24241 /** 24242 * Interface definition for a callback to be invoked when a hardware key event is 24243 * dispatched to this view. The callback will be invoked before the key event is 24244 * given to the view. This is only useful for hardware keyboards; a software input 24245 * method has no obligation to trigger this listener. 24246 */ 24247 public interface OnKeyListener { 24248 /** 24249 * Called when a hardware key is dispatched to a view. This allows listeners to 24250 * get a chance to respond before the target view. 24251 * <p>Key presses in software keyboards will generally NOT trigger this method, 24252 * although some may elect to do so in some situations. Do not assume a 24253 * software input method has to be key-based; even if it is, it may use key presses 24254 * in a different way than you expect, so there is no way to reliably catch soft 24255 * input key presses. 24256 * 24257 * @param v The view the key has been dispatched to. 24258 * @param keyCode The code for the physical key that was pressed 24259 * @param event The KeyEvent object containing full information about 24260 * the event. 24261 * @return True if the listener has consumed the event, false otherwise. 24262 */ 24263 boolean onKey(View v, int keyCode, KeyEvent event); 24264 } 24265 24266 /** 24267 * Interface definition for a callback to be invoked when a touch event is 24268 * dispatched to this view. The callback will be invoked before the touch 24269 * event is given to the view. 24270 */ 24271 public interface OnTouchListener { 24272 /** 24273 * Called when a touch event is dispatched to a view. This allows listeners to 24274 * get a chance to respond before the target view. 24275 * 24276 * @param v The view the touch event has been dispatched to. 24277 * @param event The MotionEvent object containing full information about 24278 * the event. 24279 * @return True if the listener has consumed the event, false otherwise. 24280 */ 24281 boolean onTouch(View v, MotionEvent event); 24282 } 24283 24284 /** 24285 * Interface definition for a callback to be invoked when a hover event is 24286 * dispatched to this view. The callback will be invoked before the hover 24287 * event is given to the view. 24288 */ 24289 public interface OnHoverListener { 24290 /** 24291 * Called when a hover event is dispatched to a view. This allows listeners to 24292 * get a chance to respond before the target view. 24293 * 24294 * @param v The view the hover event has been dispatched to. 24295 * @param event The MotionEvent object containing full information about 24296 * the event. 24297 * @return True if the listener has consumed the event, false otherwise. 24298 */ 24299 boolean onHover(View v, MotionEvent event); 24300 } 24301 24302 /** 24303 * Interface definition for a callback to be invoked when a generic motion event is 24304 * dispatched to this view. The callback will be invoked before the generic motion 24305 * event is given to the view. 24306 */ 24307 public interface OnGenericMotionListener { 24308 /** 24309 * Called when a generic motion event is dispatched to a view. This allows listeners to 24310 * get a chance to respond before the target view. 24311 * 24312 * @param v The view the generic motion event has been dispatched to. 24313 * @param event The MotionEvent object containing full information about 24314 * the event. 24315 * @return True if the listener has consumed the event, false otherwise. 24316 */ 24317 boolean onGenericMotion(View v, MotionEvent event); 24318 } 24319 24320 /** 24321 * Interface definition for a callback to be invoked when a view has been clicked and held. 24322 */ 24323 public interface OnLongClickListener { 24324 /** 24325 * Called when a view has been clicked and held. 24326 * 24327 * @param v The view that was clicked and held. 24328 * 24329 * @return true if the callback consumed the long click, false otherwise. 24330 */ 24331 boolean onLongClick(View v); 24332 } 24333 24334 /** 24335 * Interface definition for a callback to be invoked when a drag is being dispatched 24336 * to this view. The callback will be invoked before the hosting view's own 24337 * onDrag(event) method. If the listener wants to fall back to the hosting view's 24338 * onDrag(event) behavior, it should return 'false' from this callback. 24339 * 24340 * <div class="special reference"> 24341 * <h3>Developer Guides</h3> 24342 * <p>For a guide to implementing drag and drop features, read the 24343 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 24344 * </div> 24345 */ 24346 public interface OnDragListener { 24347 /** 24348 * Called when a drag event is dispatched to a view. This allows listeners 24349 * to get a chance to override base View behavior. 24350 * 24351 * @param v The View that received the drag event. 24352 * @param event The {@link android.view.DragEvent} object for the drag event. 24353 * @return {@code true} if the drag event was handled successfully, or {@code false} 24354 * if the drag event was not handled. Note that {@code false} will trigger the View 24355 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 24356 */ 24357 boolean onDrag(View v, DragEvent event); 24358 } 24359 24360 /** 24361 * Interface definition for a callback to be invoked when the focus state of 24362 * a view changed. 24363 */ 24364 public interface OnFocusChangeListener { 24365 /** 24366 * Called when the focus state of a view has changed. 24367 * 24368 * @param v The view whose state has changed. 24369 * @param hasFocus The new focus state of v. 24370 */ 24371 void onFocusChange(View v, boolean hasFocus); 24372 } 24373 24374 /** 24375 * Interface definition for a callback to be invoked when a view is clicked. 24376 */ 24377 public interface OnClickListener { 24378 /** 24379 * Called when a view has been clicked. 24380 * 24381 * @param v The view that was clicked. 24382 */ 24383 void onClick(View v); 24384 } 24385 24386 /** 24387 * Interface definition for a callback to be invoked when a view is context clicked. 24388 */ 24389 public interface OnContextClickListener { 24390 /** 24391 * Called when a view is context clicked. 24392 * 24393 * @param v The view that has been context clicked. 24394 * @return true if the callback consumed the context click, false otherwise. 24395 */ 24396 boolean onContextClick(View v); 24397 } 24398 24399 /** 24400 * Interface definition for a callback to be invoked when the context menu 24401 * for this view is being built. 24402 */ 24403 public interface OnCreateContextMenuListener { 24404 /** 24405 * Called when the context menu for this view is being built. It is not 24406 * safe to hold onto the menu after this method returns. 24407 * 24408 * @param menu The context menu that is being built 24409 * @param v The view for which the context menu is being built 24410 * @param menuInfo Extra information about the item for which the 24411 * context menu should be shown. This information will vary 24412 * depending on the class of v. 24413 */ 24414 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 24415 } 24416 24417 /** 24418 * Interface definition for a callback to be invoked when the status bar changes 24419 * visibility. This reports <strong>global</strong> changes to the system UI 24420 * state, not what the application is requesting. 24421 * 24422 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 24423 */ 24424 public interface OnSystemUiVisibilityChangeListener { 24425 /** 24426 * Called when the status bar changes visibility because of a call to 24427 * {@link View#setSystemUiVisibility(int)}. 24428 * 24429 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 24430 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 24431 * This tells you the <strong>global</strong> state of these UI visibility 24432 * flags, not what your app is currently applying. 24433 */ 24434 public void onSystemUiVisibilityChange(int visibility); 24435 } 24436 24437 /** 24438 * Interface definition for a callback to be invoked when this view is attached 24439 * or detached from its window. 24440 */ 24441 public interface OnAttachStateChangeListener { 24442 /** 24443 * Called when the view is attached to a window. 24444 * @param v The view that was attached 24445 */ 24446 public void onViewAttachedToWindow(View v); 24447 /** 24448 * Called when the view is detached from a window. 24449 * @param v The view that was detached 24450 */ 24451 public void onViewDetachedFromWindow(View v); 24452 } 24453 24454 /** 24455 * Listener for applying window insets on a view in a custom way. 24456 * 24457 * <p>Apps may choose to implement this interface if they want to apply custom policy 24458 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 24459 * is set, its 24460 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 24461 * method will be called instead of the View's own 24462 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 24463 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 24464 * the View's normal behavior as part of its own.</p> 24465 */ 24466 public interface OnApplyWindowInsetsListener { 24467 /** 24468 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 24469 * on a View, this listener method will be called instead of the view's own 24470 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 24471 * 24472 * @param v The view applying window insets 24473 * @param insets The insets to apply 24474 * @return The insets supplied, minus any insets that were consumed 24475 */ 24476 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 24477 } 24478 24479 private final class UnsetPressedState implements Runnable { 24480 @Override 24481 public void run() { 24482 setPressed(false); 24483 } 24484 } 24485 24486 /** 24487 * Base class for derived classes that want to save and restore their own 24488 * state in {@link android.view.View#onSaveInstanceState()}. 24489 */ 24490 public static class BaseSavedState extends AbsSavedState { 24491 String mStartActivityRequestWhoSaved; 24492 24493 /** 24494 * Constructor used when reading from a parcel. Reads the state of the superclass. 24495 * 24496 * @param source parcel to read from 24497 */ 24498 public BaseSavedState(Parcel source) { 24499 this(source, null); 24500 } 24501 24502 /** 24503 * Constructor used when reading from a parcel using a given class loader. 24504 * Reads the state of the superclass. 24505 * 24506 * @param source parcel to read from 24507 * @param loader ClassLoader to use for reading 24508 */ 24509 public BaseSavedState(Parcel source, ClassLoader loader) { 24510 super(source, loader); 24511 mStartActivityRequestWhoSaved = source.readString(); 24512 } 24513 24514 /** 24515 * Constructor called by derived classes when creating their SavedState objects 24516 * 24517 * @param superState The state of the superclass of this view 24518 */ 24519 public BaseSavedState(Parcelable superState) { 24520 super(superState); 24521 } 24522 24523 @Override 24524 public void writeToParcel(Parcel out, int flags) { 24525 super.writeToParcel(out, flags); 24526 out.writeString(mStartActivityRequestWhoSaved); 24527 } 24528 24529 public static final Parcelable.Creator<BaseSavedState> CREATOR 24530 = new Parcelable.ClassLoaderCreator<BaseSavedState>() { 24531 @Override 24532 public BaseSavedState createFromParcel(Parcel in) { 24533 return new BaseSavedState(in); 24534 } 24535 24536 @Override 24537 public BaseSavedState createFromParcel(Parcel in, ClassLoader loader) { 24538 return new BaseSavedState(in, loader); 24539 } 24540 24541 @Override 24542 public BaseSavedState[] newArray(int size) { 24543 return new BaseSavedState[size]; 24544 } 24545 }; 24546 } 24547 24548 /** 24549 * A set of information given to a view when it is attached to its parent 24550 * window. 24551 */ 24552 final static class AttachInfo { 24553 interface Callbacks { 24554 void playSoundEffect(int effectId); 24555 boolean performHapticFeedback(int effectId, boolean always); 24556 } 24557 24558 /** 24559 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 24560 * to a Handler. This class contains the target (View) to invalidate and 24561 * the coordinates of the dirty rectangle. 24562 * 24563 * For performance purposes, this class also implements a pool of up to 24564 * POOL_LIMIT objects that get reused. This reduces memory allocations 24565 * whenever possible. 24566 */ 24567 static class InvalidateInfo { 24568 private static final int POOL_LIMIT = 10; 24569 24570 private static final SynchronizedPool<InvalidateInfo> sPool = 24571 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 24572 24573 View target; 24574 24575 int left; 24576 int top; 24577 int right; 24578 int bottom; 24579 24580 public static InvalidateInfo obtain() { 24581 InvalidateInfo instance = sPool.acquire(); 24582 return (instance != null) ? instance : new InvalidateInfo(); 24583 } 24584 24585 public void recycle() { 24586 target = null; 24587 sPool.release(this); 24588 } 24589 } 24590 24591 final IWindowSession mSession; 24592 24593 final IWindow mWindow; 24594 24595 final IBinder mWindowToken; 24596 24597 Display mDisplay; 24598 24599 final Callbacks mRootCallbacks; 24600 24601 IWindowId mIWindowId; 24602 WindowId mWindowId; 24603 24604 /** 24605 * The top view of the hierarchy. 24606 */ 24607 View mRootView; 24608 24609 IBinder mPanelParentWindowToken; 24610 24611 boolean mHardwareAccelerated; 24612 boolean mHardwareAccelerationRequested; 24613 ThreadedRenderer mThreadedRenderer; 24614 List<RenderNode> mPendingAnimatingRenderNodes; 24615 24616 /** 24617 * The state of the display to which the window is attached, as reported 24618 * by {@link Display#getState()}. Note that the display state constants 24619 * declared by {@link Display} do not exactly line up with the screen state 24620 * constants declared by {@link View} (there are more display states than 24621 * screen states). 24622 */ 24623 int mDisplayState = Display.STATE_UNKNOWN; 24624 24625 /** 24626 * Scale factor used by the compatibility mode 24627 */ 24628 float mApplicationScale; 24629 24630 /** 24631 * Indicates whether the application is in compatibility mode 24632 */ 24633 boolean mScalingRequired; 24634 24635 /** 24636 * Left position of this view's window 24637 */ 24638 int mWindowLeft; 24639 24640 /** 24641 * Top position of this view's window 24642 */ 24643 int mWindowTop; 24644 24645 /** 24646 * Indicates whether views need to use 32-bit drawing caches 24647 */ 24648 boolean mUse32BitDrawingCache; 24649 24650 /** 24651 * For windows that are full-screen but using insets to layout inside 24652 * of the screen areas, these are the current insets to appear inside 24653 * the overscan area of the display. 24654 */ 24655 final Rect mOverscanInsets = new Rect(); 24656 24657 /** 24658 * For windows that are full-screen but using insets to layout inside 24659 * of the screen decorations, these are the current insets for the 24660 * content of the window. 24661 */ 24662 final Rect mContentInsets = new Rect(); 24663 24664 /** 24665 * For windows that are full-screen but using insets to layout inside 24666 * of the screen decorations, these are the current insets for the 24667 * actual visible parts of the window. 24668 */ 24669 final Rect mVisibleInsets = new Rect(); 24670 24671 /** 24672 * For windows that are full-screen but using insets to layout inside 24673 * of the screen decorations, these are the current insets for the 24674 * stable system windows. 24675 */ 24676 final Rect mStableInsets = new Rect(); 24677 24678 /** 24679 * For windows that include areas that are not covered by real surface these are the outsets 24680 * for real surface. 24681 */ 24682 final Rect mOutsets = new Rect(); 24683 24684 /** 24685 * In multi-window we force show the navigation bar. Because we don't want that the surface 24686 * size changes in this mode, we instead have a flag whether the navigation bar size should 24687 * always be consumed, so the app is treated like there is no virtual navigation bar at all. 24688 */ 24689 boolean mAlwaysConsumeNavBar; 24690 24691 /** 24692 * The internal insets given by this window. This value is 24693 * supplied by the client (through 24694 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 24695 * be given to the window manager when changed to be used in laying 24696 * out windows behind it. 24697 */ 24698 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 24699 = new ViewTreeObserver.InternalInsetsInfo(); 24700 24701 /** 24702 * Set to true when mGivenInternalInsets is non-empty. 24703 */ 24704 boolean mHasNonEmptyGivenInternalInsets; 24705 24706 /** 24707 * All views in the window's hierarchy that serve as scroll containers, 24708 * used to determine if the window can be resized or must be panned 24709 * to adjust for a soft input area. 24710 */ 24711 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 24712 24713 final KeyEvent.DispatcherState mKeyDispatchState 24714 = new KeyEvent.DispatcherState(); 24715 24716 /** 24717 * Indicates whether the view's window currently has the focus. 24718 */ 24719 boolean mHasWindowFocus; 24720 24721 /** 24722 * The current visibility of the window. 24723 */ 24724 int mWindowVisibility; 24725 24726 /** 24727 * Indicates the time at which drawing started to occur. 24728 */ 24729 long mDrawingTime; 24730 24731 /** 24732 * Indicates whether or not ignoring the DIRTY_MASK flags. 24733 */ 24734 boolean mIgnoreDirtyState; 24735 24736 /** 24737 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 24738 * to avoid clearing that flag prematurely. 24739 */ 24740 boolean mSetIgnoreDirtyState = false; 24741 24742 /** 24743 * Indicates whether the view's window is currently in touch mode. 24744 */ 24745 boolean mInTouchMode; 24746 24747 /** 24748 * Indicates whether the view has requested unbuffered input dispatching for the current 24749 * event stream. 24750 */ 24751 boolean mUnbufferedDispatchRequested; 24752 24753 /** 24754 * Indicates that ViewAncestor should trigger a global layout change 24755 * the next time it performs a traversal 24756 */ 24757 boolean mRecomputeGlobalAttributes; 24758 24759 /** 24760 * Always report new attributes at next traversal. 24761 */ 24762 boolean mForceReportNewAttributes; 24763 24764 /** 24765 * Set during a traveral if any views want to keep the screen on. 24766 */ 24767 boolean mKeepScreenOn; 24768 24769 /** 24770 * Set during a traveral if the light center needs to be updated. 24771 */ 24772 boolean mNeedsUpdateLightCenter; 24773 24774 /** 24775 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 24776 */ 24777 int mSystemUiVisibility; 24778 24779 /** 24780 * Hack to force certain system UI visibility flags to be cleared. 24781 */ 24782 int mDisabledSystemUiVisibility; 24783 24784 /** 24785 * Last global system UI visibility reported by the window manager. 24786 */ 24787 int mGlobalSystemUiVisibility = -1; 24788 24789 /** 24790 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 24791 * attached. 24792 */ 24793 boolean mHasSystemUiListeners; 24794 24795 /** 24796 * Set if the window has requested to extend into the overscan region 24797 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 24798 */ 24799 boolean mOverscanRequested; 24800 24801 /** 24802 * Set if the visibility of any views has changed. 24803 */ 24804 boolean mViewVisibilityChanged; 24805 24806 /** 24807 * Set to true if a view has been scrolled. 24808 */ 24809 boolean mViewScrollChanged; 24810 24811 /** 24812 * Set to true if high contrast mode enabled 24813 */ 24814 boolean mHighContrastText; 24815 24816 /** 24817 * Set to true if a pointer event is currently being handled. 24818 */ 24819 boolean mHandlingPointerEvent; 24820 24821 /** 24822 * Global to the view hierarchy used as a temporary for dealing with 24823 * x/y points in the transparent region computations. 24824 */ 24825 final int[] mTransparentLocation = new int[2]; 24826 24827 /** 24828 * Global to the view hierarchy used as a temporary for dealing with 24829 * x/y points in the ViewGroup.invalidateChild implementation. 24830 */ 24831 final int[] mInvalidateChildLocation = new int[2]; 24832 24833 /** 24834 * Global to the view hierarchy used as a temporary for dealing with 24835 * computing absolute on-screen location. 24836 */ 24837 final int[] mTmpLocation = new int[2]; 24838 24839 /** 24840 * Global to the view hierarchy used as a temporary for dealing with 24841 * x/y location when view is transformed. 24842 */ 24843 final float[] mTmpTransformLocation = new float[2]; 24844 24845 /** 24846 * The view tree observer used to dispatch global events like 24847 * layout, pre-draw, touch mode change, etc. 24848 */ 24849 final ViewTreeObserver mTreeObserver; 24850 24851 /** 24852 * A Canvas used by the view hierarchy to perform bitmap caching. 24853 */ 24854 Canvas mCanvas; 24855 24856 /** 24857 * The view root impl. 24858 */ 24859 final ViewRootImpl mViewRootImpl; 24860 24861 /** 24862 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 24863 * handler can be used to pump events in the UI events queue. 24864 */ 24865 final Handler mHandler; 24866 24867 /** 24868 * Temporary for use in computing invalidate rectangles while 24869 * calling up the hierarchy. 24870 */ 24871 final Rect mTmpInvalRect = new Rect(); 24872 24873 /** 24874 * Temporary for use in computing hit areas with transformed views 24875 */ 24876 final RectF mTmpTransformRect = new RectF(); 24877 24878 /** 24879 * Temporary for use in computing hit areas with transformed views 24880 */ 24881 final RectF mTmpTransformRect1 = new RectF(); 24882 24883 /** 24884 * Temporary list of rectanges. 24885 */ 24886 final List<RectF> mTmpRectList = new ArrayList<>(); 24887 24888 /** 24889 * Temporary for use in transforming invalidation rect 24890 */ 24891 final Matrix mTmpMatrix = new Matrix(); 24892 24893 /** 24894 * Temporary for use in transforming invalidation rect 24895 */ 24896 final Transformation mTmpTransformation = new Transformation(); 24897 24898 /** 24899 * Temporary for use in querying outlines from OutlineProviders 24900 */ 24901 final Outline mTmpOutline = new Outline(); 24902 24903 /** 24904 * Temporary list for use in collecting focusable descendents of a view. 24905 */ 24906 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 24907 24908 /** 24909 * The id of the window for accessibility purposes. 24910 */ 24911 int mAccessibilityWindowId = AccessibilityWindowInfo.UNDEFINED_WINDOW_ID; 24912 24913 /** 24914 * Flags related to accessibility processing. 24915 * 24916 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 24917 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 24918 */ 24919 int mAccessibilityFetchFlags; 24920 24921 /** 24922 * The drawable for highlighting accessibility focus. 24923 */ 24924 Drawable mAccessibilityFocusDrawable; 24925 24926 /** 24927 * Show where the margins, bounds and layout bounds are for each view. 24928 */ 24929 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 24930 24931 /** 24932 * Point used to compute visible regions. 24933 */ 24934 final Point mPoint = new Point(); 24935 24936 /** 24937 * Used to track which View originated a requestLayout() call, used when 24938 * requestLayout() is called during layout. 24939 */ 24940 View mViewRequestingLayout; 24941 24942 /** 24943 * Used to track views that need (at least) a partial relayout at their current size 24944 * during the next traversal. 24945 */ 24946 List<View> mPartialLayoutViews = new ArrayList<>(); 24947 24948 /** 24949 * Swapped with mPartialLayoutViews during layout to avoid concurrent 24950 * modification. Lazily assigned during ViewRootImpl layout. 24951 */ 24952 List<View> mEmptyPartialLayoutViews; 24953 24954 /** 24955 * Used to track the identity of the current drag operation. 24956 */ 24957 IBinder mDragToken; 24958 24959 /** 24960 * The drag shadow surface for the current drag operation. 24961 */ 24962 public Surface mDragSurface; 24963 24964 24965 /** 24966 * The view that currently has a tooltip displayed. 24967 */ 24968 View mTooltipHost; 24969 24970 /** 24971 * Creates a new set of attachment information with the specified 24972 * events handler and thread. 24973 * 24974 * @param handler the events handler the view must use 24975 */ 24976 AttachInfo(IWindowSession session, IWindow window, Display display, 24977 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer, 24978 Context context) { 24979 mSession = session; 24980 mWindow = window; 24981 mWindowToken = window.asBinder(); 24982 mDisplay = display; 24983 mViewRootImpl = viewRootImpl; 24984 mHandler = handler; 24985 mRootCallbacks = effectPlayer; 24986 mTreeObserver = new ViewTreeObserver(context); 24987 } 24988 } 24989 24990 /** 24991 * <p>ScrollabilityCache holds various fields used by a View when scrolling 24992 * is supported. This avoids keeping too many unused fields in most 24993 * instances of View.</p> 24994 */ 24995 private static class ScrollabilityCache implements Runnable { 24996 24997 /** 24998 * Scrollbars are not visible 24999 */ 25000 public static final int OFF = 0; 25001 25002 /** 25003 * Scrollbars are visible 25004 */ 25005 public static final int ON = 1; 25006 25007 /** 25008 * Scrollbars are fading away 25009 */ 25010 public static final int FADING = 2; 25011 25012 public boolean fadeScrollBars; 25013 25014 public int fadingEdgeLength; 25015 public int scrollBarDefaultDelayBeforeFade; 25016 public int scrollBarFadeDuration; 25017 25018 public int scrollBarSize; 25019 public int scrollBarMinTouchTarget; 25020 public ScrollBarDrawable scrollBar; 25021 public float[] interpolatorValues; 25022 public View host; 25023 25024 public final Paint paint; 25025 public final Matrix matrix; 25026 public Shader shader; 25027 25028 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 25029 25030 private static final float[] OPAQUE = { 255 }; 25031 private static final float[] TRANSPARENT = { 0.0f }; 25032 25033 /** 25034 * When fading should start. This time moves into the future every time 25035 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 25036 */ 25037 public long fadeStartTime; 25038 25039 25040 /** 25041 * The current state of the scrollbars: ON, OFF, or FADING 25042 */ 25043 public int state = OFF; 25044 25045 private int mLastColor; 25046 25047 public final Rect mScrollBarBounds = new Rect(); 25048 public final Rect mScrollBarTouchBounds = new Rect(); 25049 25050 public static final int NOT_DRAGGING = 0; 25051 public static final int DRAGGING_VERTICAL_SCROLL_BAR = 1; 25052 public static final int DRAGGING_HORIZONTAL_SCROLL_BAR = 2; 25053 public int mScrollBarDraggingState = NOT_DRAGGING; 25054 25055 public float mScrollBarDraggingPos = 0; 25056 25057 public ScrollabilityCache(ViewConfiguration configuration, View host) { 25058 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 25059 scrollBarSize = configuration.getScaledScrollBarSize(); 25060 scrollBarMinTouchTarget = configuration.getScaledMinScrollbarTouchTarget(); 25061 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 25062 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 25063 25064 paint = new Paint(); 25065 matrix = new Matrix(); 25066 // use use a height of 1, and then wack the matrix each time we 25067 // actually use it. 25068 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 25069 paint.setShader(shader); 25070 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 25071 25072 this.host = host; 25073 } 25074 25075 public void setFadeColor(int color) { 25076 if (color != mLastColor) { 25077 mLastColor = color; 25078 25079 if (color != 0) { 25080 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 25081 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 25082 paint.setShader(shader); 25083 // Restore the default transfer mode (src_over) 25084 paint.setXfermode(null); 25085 } else { 25086 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 25087 paint.setShader(shader); 25088 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 25089 } 25090 } 25091 } 25092 25093 public void run() { 25094 long now = AnimationUtils.currentAnimationTimeMillis(); 25095 if (now >= fadeStartTime) { 25096 25097 // the animation fades the scrollbars out by changing 25098 // the opacity (alpha) from fully opaque to fully 25099 // transparent 25100 int nextFrame = (int) now; 25101 int framesCount = 0; 25102 25103 Interpolator interpolator = scrollBarInterpolator; 25104 25105 // Start opaque 25106 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 25107 25108 // End transparent 25109 nextFrame += scrollBarFadeDuration; 25110 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 25111 25112 state = FADING; 25113 25114 // Kick off the fade animation 25115 host.invalidate(true); 25116 } 25117 } 25118 } 25119 25120 /** 25121 * Resuable callback for sending 25122 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 25123 */ 25124 private class SendViewScrolledAccessibilityEvent implements Runnable { 25125 public volatile boolean mIsPending; 25126 25127 public void run() { 25128 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 25129 mIsPending = false; 25130 } 25131 } 25132 25133 /** 25134 * <p> 25135 * This class represents a delegate that can be registered in a {@link View} 25136 * to enhance accessibility support via composition rather via inheritance. 25137 * It is specifically targeted to widget developers that extend basic View 25138 * classes i.e. classes in package android.view, that would like their 25139 * applications to be backwards compatible. 25140 * </p> 25141 * <div class="special reference"> 25142 * <h3>Developer Guides</h3> 25143 * <p>For more information about making applications accessible, read the 25144 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 25145 * developer guide.</p> 25146 * </div> 25147 * <p> 25148 * A scenario in which a developer would like to use an accessibility delegate 25149 * is overriding a method introduced in a later API version than the minimal API 25150 * version supported by the application. For example, the method 25151 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 25152 * in API version 4 when the accessibility APIs were first introduced. If a 25153 * developer would like his application to run on API version 4 devices (assuming 25154 * all other APIs used by the application are version 4 or lower) and take advantage 25155 * of this method, instead of overriding the method which would break the application's 25156 * backwards compatibility, he can override the corresponding method in this 25157 * delegate and register the delegate in the target View if the API version of 25158 * the system is high enough, i.e. the API version is the same as or higher than the API 25159 * version that introduced 25160 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 25161 * </p> 25162 * <p> 25163 * Here is an example implementation: 25164 * </p> 25165 * <code><pre><p> 25166 * if (Build.VERSION.SDK_INT >= 14) { 25167 * // If the API version is equal of higher than the version in 25168 * // which onInitializeAccessibilityNodeInfo was introduced we 25169 * // register a delegate with a customized implementation. 25170 * View view = findViewById(R.id.view_id); 25171 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 25172 * public void onInitializeAccessibilityNodeInfo(View host, 25173 * AccessibilityNodeInfo info) { 25174 * // Let the default implementation populate the info. 25175 * super.onInitializeAccessibilityNodeInfo(host, info); 25176 * // Set some other information. 25177 * info.setEnabled(host.isEnabled()); 25178 * } 25179 * }); 25180 * } 25181 * </code></pre></p> 25182 * <p> 25183 * This delegate contains methods that correspond to the accessibility methods 25184 * in View. If a delegate has been specified the implementation in View hands 25185 * off handling to the corresponding method in this delegate. The default 25186 * implementation the delegate methods behaves exactly as the corresponding 25187 * method in View for the case of no accessibility delegate been set. Hence, 25188 * to customize the behavior of a View method, clients can override only the 25189 * corresponding delegate method without altering the behavior of the rest 25190 * accessibility related methods of the host view. 25191 * </p> 25192 * <p> 25193 * <strong>Note:</strong> On platform versions prior to 25194 * {@link android.os.Build.VERSION_CODES#M API 23}, delegate methods on 25195 * views in the {@code android.widget.*} package are called <i>before</i> 25196 * host methods. This prevents certain properties such as class name from 25197 * being modified by overriding 25198 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)}, 25199 * as any changes will be overwritten by the host class. 25200 * <p> 25201 * Starting in {@link android.os.Build.VERSION_CODES#M API 23}, delegate 25202 * methods are called <i>after</i> host methods, which all properties to be 25203 * modified without being overwritten by the host class. 25204 */ 25205 public static class AccessibilityDelegate { 25206 25207 /** 25208 * Sends an accessibility event of the given type. If accessibility is not 25209 * enabled this method has no effect. 25210 * <p> 25211 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 25212 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 25213 * been set. 25214 * </p> 25215 * 25216 * @param host The View hosting the delegate. 25217 * @param eventType The type of the event to send. 25218 * 25219 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 25220 */ 25221 public void sendAccessibilityEvent(View host, int eventType) { 25222 host.sendAccessibilityEventInternal(eventType); 25223 } 25224 25225 /** 25226 * Performs the specified accessibility action on the view. For 25227 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 25228 * <p> 25229 * The default implementation behaves as 25230 * {@link View#performAccessibilityAction(int, Bundle) 25231 * View#performAccessibilityAction(int, Bundle)} for the case of 25232 * no accessibility delegate been set. 25233 * </p> 25234 * 25235 * @param action The action to perform. 25236 * @return Whether the action was performed. 25237 * 25238 * @see View#performAccessibilityAction(int, Bundle) 25239 * View#performAccessibilityAction(int, Bundle) 25240 */ 25241 public boolean performAccessibilityAction(View host, int action, Bundle args) { 25242 return host.performAccessibilityActionInternal(action, args); 25243 } 25244 25245 /** 25246 * Sends an accessibility event. This method behaves exactly as 25247 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 25248 * empty {@link AccessibilityEvent} and does not perform a check whether 25249 * accessibility is enabled. 25250 * <p> 25251 * The default implementation behaves as 25252 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25253 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 25254 * the case of no accessibility delegate been set. 25255 * </p> 25256 * 25257 * @param host The View hosting the delegate. 25258 * @param event The event to send. 25259 * 25260 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25261 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 25262 */ 25263 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 25264 host.sendAccessibilityEventUncheckedInternal(event); 25265 } 25266 25267 /** 25268 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 25269 * to its children for adding their text content to the event. 25270 * <p> 25271 * The default implementation behaves as 25272 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25273 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 25274 * the case of no accessibility delegate been set. 25275 * </p> 25276 * 25277 * @param host The View hosting the delegate. 25278 * @param event The event. 25279 * @return True if the event population was completed. 25280 * 25281 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25282 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 25283 */ 25284 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 25285 return host.dispatchPopulateAccessibilityEventInternal(event); 25286 } 25287 25288 /** 25289 * Gives a chance to the host View to populate the accessibility event with its 25290 * text content. 25291 * <p> 25292 * The default implementation behaves as 25293 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 25294 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 25295 * the case of no accessibility delegate been set. 25296 * </p> 25297 * 25298 * @param host The View hosting the delegate. 25299 * @param event The accessibility event which to populate. 25300 * 25301 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 25302 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 25303 */ 25304 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 25305 host.onPopulateAccessibilityEventInternal(event); 25306 } 25307 25308 /** 25309 * Initializes an {@link AccessibilityEvent} with information about the 25310 * the host View which is the event source. 25311 * <p> 25312 * The default implementation behaves as 25313 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 25314 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 25315 * the case of no accessibility delegate been set. 25316 * </p> 25317 * 25318 * @param host The View hosting the delegate. 25319 * @param event The event to initialize. 25320 * 25321 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 25322 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 25323 */ 25324 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 25325 host.onInitializeAccessibilityEventInternal(event); 25326 } 25327 25328 /** 25329 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 25330 * <p> 25331 * The default implementation behaves as 25332 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25333 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 25334 * the case of no accessibility delegate been set. 25335 * </p> 25336 * 25337 * @param host The View hosting the delegate. 25338 * @param info The instance to initialize. 25339 * 25340 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25341 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 25342 */ 25343 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 25344 host.onInitializeAccessibilityNodeInfoInternal(info); 25345 } 25346 25347 /** 25348 * Adds extra data to an {@link AccessibilityNodeInfo} based on an explicit request for the 25349 * additional data. 25350 * <p> 25351 * This method only needs to be implemented if the View offers to provide additional data. 25352 * </p> 25353 * <p> 25354 * The default implementation behaves as 25355 * {@link View#addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo, int) for 25356 * the case where no accessibility delegate is set. 25357 * </p> 25358 * 25359 * @param host The View hosting the delegate. Never {@code null}. 25360 * @param info The info to which to add the extra data. Never {@code null}. 25361 * @param extraDataKey A key specifying the type of extra data to add to the info. The 25362 * extra data should be added to the {@link Bundle} returned by 25363 * the info's {@link AccessibilityNodeInfo#getExtras} method. Never 25364 * {@code null}. 25365 * @param arguments A {@link Bundle} holding any arguments relevant for this request. 25366 * May be {@code null} if the if the service provided no arguments. 25367 * 25368 * @see AccessibilityNodeInfo#setExtraAvailableData 25369 */ 25370 public void addExtraDataToAccessibilityNodeInfo(@NonNull View host, 25371 @NonNull AccessibilityNodeInfo info, @NonNull String extraDataKey, 25372 @Nullable Bundle arguments) { 25373 host.addExtraDataToAccessibilityNodeInfo(info, extraDataKey, arguments); 25374 } 25375 25376 /** 25377 * Called when a child of the host View has requested sending an 25378 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 25379 * to augment the event. 25380 * <p> 25381 * The default implementation behaves as 25382 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25383 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 25384 * the case of no accessibility delegate been set. 25385 * </p> 25386 * 25387 * @param host The View hosting the delegate. 25388 * @param child The child which requests sending the event. 25389 * @param event The event to be sent. 25390 * @return True if the event should be sent 25391 * 25392 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25393 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 25394 */ 25395 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 25396 AccessibilityEvent event) { 25397 return host.onRequestSendAccessibilityEventInternal(child, event); 25398 } 25399 25400 /** 25401 * Gets the provider for managing a virtual view hierarchy rooted at this View 25402 * and reported to {@link android.accessibilityservice.AccessibilityService}s 25403 * that explore the window content. 25404 * <p> 25405 * The default implementation behaves as 25406 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 25407 * the case of no accessibility delegate been set. 25408 * </p> 25409 * 25410 * @return The provider. 25411 * 25412 * @see AccessibilityNodeProvider 25413 */ 25414 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 25415 return null; 25416 } 25417 25418 /** 25419 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 25420 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 25421 * This method is responsible for obtaining an accessibility node info from a 25422 * pool of reusable instances and calling 25423 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 25424 * view to initialize the former. 25425 * <p> 25426 * <strong>Note:</strong> The client is responsible for recycling the obtained 25427 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 25428 * creation. 25429 * </p> 25430 * <p> 25431 * The default implementation behaves as 25432 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 25433 * the case of no accessibility delegate been set. 25434 * </p> 25435 * @return A populated {@link AccessibilityNodeInfo}. 25436 * 25437 * @see AccessibilityNodeInfo 25438 * 25439 * @hide 25440 */ 25441 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 25442 return host.createAccessibilityNodeInfoInternal(); 25443 } 25444 } 25445 25446 private static class MatchIdPredicate implements Predicate<View> { 25447 public int mId; 25448 25449 @Override 25450 public boolean test(View view) { 25451 return (view.mID == mId); 25452 } 25453 } 25454 25455 private static class MatchLabelForPredicate implements Predicate<View> { 25456 private int mLabeledId; 25457 25458 @Override 25459 public boolean test(View view) { 25460 return (view.mLabelForId == mLabeledId); 25461 } 25462 } 25463 25464 private class SendViewStateChangedAccessibilityEvent implements Runnable { 25465 private int mChangeTypes = 0; 25466 private boolean mPosted; 25467 private boolean mPostedWithDelay; 25468 private long mLastEventTimeMillis; 25469 25470 @Override 25471 public void run() { 25472 mPosted = false; 25473 mPostedWithDelay = false; 25474 mLastEventTimeMillis = SystemClock.uptimeMillis(); 25475 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 25476 final AccessibilityEvent event = AccessibilityEvent.obtain(); 25477 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 25478 event.setContentChangeTypes(mChangeTypes); 25479 sendAccessibilityEventUnchecked(event); 25480 } 25481 mChangeTypes = 0; 25482 } 25483 25484 public void runOrPost(int changeType) { 25485 mChangeTypes |= changeType; 25486 25487 // If this is a live region or the child of a live region, collect 25488 // all events from this frame and send them on the next frame. 25489 if (inLiveRegion()) { 25490 // If we're already posted with a delay, remove that. 25491 if (mPostedWithDelay) { 25492 removeCallbacks(this); 25493 mPostedWithDelay = false; 25494 } 25495 // Only post if we're not already posted. 25496 if (!mPosted) { 25497 post(this); 25498 mPosted = true; 25499 } 25500 return; 25501 } 25502 25503 if (mPosted) { 25504 return; 25505 } 25506 25507 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 25508 final long minEventIntevalMillis = 25509 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 25510 if (timeSinceLastMillis >= minEventIntevalMillis) { 25511 removeCallbacks(this); 25512 run(); 25513 } else { 25514 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 25515 mPostedWithDelay = true; 25516 } 25517 } 25518 } 25519 25520 private boolean inLiveRegion() { 25521 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 25522 return true; 25523 } 25524 25525 ViewParent parent = getParent(); 25526 while (parent instanceof View) { 25527 if (((View) parent).getAccessibilityLiveRegion() 25528 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 25529 return true; 25530 } 25531 parent = parent.getParent(); 25532 } 25533 25534 return false; 25535 } 25536 25537 /** 25538 * Dump all private flags in readable format, useful for documentation and 25539 * sanity checking. 25540 */ 25541 private static void dumpFlags() { 25542 final HashMap<String, String> found = Maps.newHashMap(); 25543 try { 25544 for (Field field : View.class.getDeclaredFields()) { 25545 final int modifiers = field.getModifiers(); 25546 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 25547 if (field.getType().equals(int.class)) { 25548 final int value = field.getInt(null); 25549 dumpFlag(found, field.getName(), value); 25550 } else if (field.getType().equals(int[].class)) { 25551 final int[] values = (int[]) field.get(null); 25552 for (int i = 0; i < values.length; i++) { 25553 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 25554 } 25555 } 25556 } 25557 } 25558 } catch (IllegalAccessException e) { 25559 throw new RuntimeException(e); 25560 } 25561 25562 final ArrayList<String> keys = Lists.newArrayList(); 25563 keys.addAll(found.keySet()); 25564 Collections.sort(keys); 25565 for (String key : keys) { 25566 Log.d(VIEW_LOG_TAG, found.get(key)); 25567 } 25568 } 25569 25570 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 25571 // Sort flags by prefix, then by bits, always keeping unique keys 25572 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 25573 final int prefix = name.indexOf('_'); 25574 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 25575 final String output = bits + " " + name; 25576 found.put(key, output); 25577 } 25578 25579 /** {@hide} */ 25580 public void encode(@NonNull ViewHierarchyEncoder stream) { 25581 stream.beginObject(this); 25582 encodeProperties(stream); 25583 stream.endObject(); 25584 } 25585 25586 /** {@hide} */ 25587 @CallSuper 25588 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 25589 Object resolveId = ViewDebug.resolveId(getContext(), mID); 25590 if (resolveId instanceof String) { 25591 stream.addProperty("id", (String) resolveId); 25592 } else { 25593 stream.addProperty("id", mID); 25594 } 25595 25596 stream.addProperty("misc:transformation.alpha", 25597 mTransformationInfo != null ? mTransformationInfo.mAlpha : 0); 25598 stream.addProperty("misc:transitionName", getTransitionName()); 25599 25600 // layout 25601 stream.addProperty("layout:left", mLeft); 25602 stream.addProperty("layout:right", mRight); 25603 stream.addProperty("layout:top", mTop); 25604 stream.addProperty("layout:bottom", mBottom); 25605 stream.addProperty("layout:width", getWidth()); 25606 stream.addProperty("layout:height", getHeight()); 25607 stream.addProperty("layout:layoutDirection", getLayoutDirection()); 25608 stream.addProperty("layout:layoutRtl", isLayoutRtl()); 25609 stream.addProperty("layout:hasTransientState", hasTransientState()); 25610 stream.addProperty("layout:baseline", getBaseline()); 25611 25612 // layout params 25613 ViewGroup.LayoutParams layoutParams = getLayoutParams(); 25614 if (layoutParams != null) { 25615 stream.addPropertyKey("layoutParams"); 25616 layoutParams.encode(stream); 25617 } 25618 25619 // scrolling 25620 stream.addProperty("scrolling:scrollX", mScrollX); 25621 stream.addProperty("scrolling:scrollY", mScrollY); 25622 25623 // padding 25624 stream.addProperty("padding:paddingLeft", mPaddingLeft); 25625 stream.addProperty("padding:paddingRight", mPaddingRight); 25626 stream.addProperty("padding:paddingTop", mPaddingTop); 25627 stream.addProperty("padding:paddingBottom", mPaddingBottom); 25628 stream.addProperty("padding:userPaddingRight", mUserPaddingRight); 25629 stream.addProperty("padding:userPaddingLeft", mUserPaddingLeft); 25630 stream.addProperty("padding:userPaddingBottom", mUserPaddingBottom); 25631 stream.addProperty("padding:userPaddingStart", mUserPaddingStart); 25632 stream.addProperty("padding:userPaddingEnd", mUserPaddingEnd); 25633 25634 // measurement 25635 stream.addProperty("measurement:minHeight", mMinHeight); 25636 stream.addProperty("measurement:minWidth", mMinWidth); 25637 stream.addProperty("measurement:measuredWidth", mMeasuredWidth); 25638 stream.addProperty("measurement:measuredHeight", mMeasuredHeight); 25639 25640 // drawing 25641 stream.addProperty("drawing:elevation", getElevation()); 25642 stream.addProperty("drawing:translationX", getTranslationX()); 25643 stream.addProperty("drawing:translationY", getTranslationY()); 25644 stream.addProperty("drawing:translationZ", getTranslationZ()); 25645 stream.addProperty("drawing:rotation", getRotation()); 25646 stream.addProperty("drawing:rotationX", getRotationX()); 25647 stream.addProperty("drawing:rotationY", getRotationY()); 25648 stream.addProperty("drawing:scaleX", getScaleX()); 25649 stream.addProperty("drawing:scaleY", getScaleY()); 25650 stream.addProperty("drawing:pivotX", getPivotX()); 25651 stream.addProperty("drawing:pivotY", getPivotY()); 25652 stream.addProperty("drawing:opaque", isOpaque()); 25653 stream.addProperty("drawing:alpha", getAlpha()); 25654 stream.addProperty("drawing:transitionAlpha", getTransitionAlpha()); 25655 stream.addProperty("drawing:shadow", hasShadow()); 25656 stream.addProperty("drawing:solidColor", getSolidColor()); 25657 stream.addProperty("drawing:layerType", mLayerType); 25658 stream.addProperty("drawing:willNotDraw", willNotDraw()); 25659 stream.addProperty("drawing:hardwareAccelerated", isHardwareAccelerated()); 25660 stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing()); 25661 stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled()); 25662 stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering()); 25663 25664 // focus 25665 stream.addProperty("focus:hasFocus", hasFocus()); 25666 stream.addProperty("focus:isFocused", isFocused()); 25667 stream.addProperty("focus:isFocusable", isFocusable()); 25668 stream.addProperty("focus:isFocusableInTouchMode", isFocusableInTouchMode()); 25669 25670 stream.addProperty("misc:clickable", isClickable()); 25671 stream.addProperty("misc:pressed", isPressed()); 25672 stream.addProperty("misc:selected", isSelected()); 25673 stream.addProperty("misc:touchMode", isInTouchMode()); 25674 stream.addProperty("misc:hovered", isHovered()); 25675 stream.addProperty("misc:activated", isActivated()); 25676 25677 stream.addProperty("misc:visibility", getVisibility()); 25678 stream.addProperty("misc:fitsSystemWindows", getFitsSystemWindows()); 25679 stream.addProperty("misc:filterTouchesWhenObscured", getFilterTouchesWhenObscured()); 25680 25681 stream.addProperty("misc:enabled", isEnabled()); 25682 stream.addProperty("misc:soundEffectsEnabled", isSoundEffectsEnabled()); 25683 stream.addProperty("misc:hapticFeedbackEnabled", isHapticFeedbackEnabled()); 25684 25685 // theme attributes 25686 Resources.Theme theme = getContext().getTheme(); 25687 if (theme != null) { 25688 stream.addPropertyKey("theme"); 25689 theme.encode(stream); 25690 } 25691 25692 // view attribute information 25693 int n = mAttributes != null ? mAttributes.length : 0; 25694 stream.addProperty("meta:__attrCount__", n/2); 25695 for (int i = 0; i < n; i += 2) { 25696 stream.addProperty("meta:__attr__" + mAttributes[i], mAttributes[i+1]); 25697 } 25698 25699 stream.addProperty("misc:scrollBarStyle", getScrollBarStyle()); 25700 25701 // text 25702 stream.addProperty("text:textDirection", getTextDirection()); 25703 stream.addProperty("text:textAlignment", getTextAlignment()); 25704 25705 // accessibility 25706 CharSequence contentDescription = getContentDescription(); 25707 stream.addProperty("accessibility:contentDescription", 25708 contentDescription == null ? "" : contentDescription.toString()); 25709 stream.addProperty("accessibility:labelFor", getLabelFor()); 25710 stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); 25711 } 25712 25713 /** 25714 * Determine if this view is rendered on a round wearable device and is the main view 25715 * on the screen. 25716 */ 25717 boolean shouldDrawRoundScrollbar() { 25718 if (!mResources.getConfiguration().isScreenRound() || mAttachInfo == null) { 25719 return false; 25720 } 25721 25722 final View rootView = getRootView(); 25723 final WindowInsets insets = getRootWindowInsets(); 25724 25725 int height = getHeight(); 25726 int width = getWidth(); 25727 int displayHeight = rootView.getHeight(); 25728 int displayWidth = rootView.getWidth(); 25729 25730 if (height != displayHeight || width != displayWidth) { 25731 return false; 25732 } 25733 25734 getLocationInWindow(mAttachInfo.mTmpLocation); 25735 return mAttachInfo.mTmpLocation[0] == insets.getStableInsetLeft() 25736 && mAttachInfo.mTmpLocation[1] == insets.getStableInsetTop(); 25737 } 25738 25739 /** 25740 * Sets the tooltip text which will be displayed in a small popup next to the view. 25741 * <p> 25742 * The tooltip will be displayed: 25743 * <ul> 25744 * <li>On long click, unless it is handled otherwise (by OnLongClickListener or a context 25745 * menu). </li> 25746 * <li>On hover, after a brief delay since the pointer has stopped moving </li> 25747 * </ul> 25748 * <p> 25749 * <strong>Note:</strong> Do not override this method, as it will have no 25750 * effect on the text displayed in the tooltip. 25751 * 25752 * @param tooltipText the tooltip text, or null if no tooltip is required 25753 * @see #getTooltipText() 25754 * @attr ref android.R.styleable#View_tooltipText 25755 */ 25756 public void setTooltipText(@Nullable CharSequence tooltipText) { 25757 if (TextUtils.isEmpty(tooltipText)) { 25758 setFlags(0, TOOLTIP); 25759 hideTooltip(); 25760 mTooltipInfo = null; 25761 } else { 25762 setFlags(TOOLTIP, TOOLTIP); 25763 if (mTooltipInfo == null) { 25764 mTooltipInfo = new TooltipInfo(); 25765 mTooltipInfo.mShowTooltipRunnable = this::showHoverTooltip; 25766 mTooltipInfo.mHideTooltipRunnable = this::hideTooltip; 25767 } 25768 mTooltipInfo.mTooltipText = tooltipText; 25769 if (mTooltipInfo.mTooltipPopup != null && mTooltipInfo.mTooltipPopup.isShowing()) { 25770 mTooltipInfo.mTooltipPopup.updateContent(mTooltipInfo.mTooltipText); 25771 } 25772 } 25773 } 25774 25775 /** 25776 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 25777 */ 25778 public void setTooltip(@Nullable CharSequence tooltipText) { 25779 setTooltipText(tooltipText); 25780 } 25781 25782 /** 25783 * Returns the view's tooltip text. 25784 * 25785 * <strong>Note:</strong> Do not override this method, as it will have no 25786 * effect on the text displayed in the tooltip. You must call 25787 * {@link #setTooltipText(CharSequence)} to modify the tooltip text. 25788 * 25789 * @return the tooltip text 25790 * @see #setTooltipText(CharSequence) 25791 * @attr ref android.R.styleable#View_tooltipText 25792 */ 25793 @Nullable 25794 public CharSequence getTooltipText() { 25795 return mTooltipInfo != null ? mTooltipInfo.mTooltipText : null; 25796 } 25797 25798 /** 25799 * @hide Binary compatibility stub. To be removed when we finalize O APIs. 25800 */ 25801 @Nullable 25802 public CharSequence getTooltip() { 25803 return getTooltipText(); 25804 } 25805 25806 private boolean showTooltip(int x, int y, boolean fromLongClick) { 25807 if (mAttachInfo == null || mTooltipInfo == null) { 25808 return false; 25809 } 25810 if ((mViewFlags & ENABLED_MASK) != ENABLED) { 25811 return false; 25812 } 25813 if (TextUtils.isEmpty(mTooltipInfo.mTooltipText)) { 25814 return false; 25815 } 25816 hideTooltip(); 25817 mTooltipInfo.mTooltipFromLongClick = fromLongClick; 25818 mTooltipInfo.mTooltipPopup = new TooltipPopup(getContext()); 25819 final boolean fromTouch = (mPrivateFlags3 & PFLAG3_FINGER_DOWN) == PFLAG3_FINGER_DOWN; 25820 mTooltipInfo.mTooltipPopup.show(this, x, y, fromTouch, mTooltipInfo.mTooltipText); 25821 mAttachInfo.mTooltipHost = this; 25822 return true; 25823 } 25824 25825 void hideTooltip() { 25826 if (mTooltipInfo == null) { 25827 return; 25828 } 25829 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 25830 if (mTooltipInfo.mTooltipPopup == null) { 25831 return; 25832 } 25833 mTooltipInfo.mTooltipPopup.hide(); 25834 mTooltipInfo.mTooltipPopup = null; 25835 mTooltipInfo.mTooltipFromLongClick = false; 25836 if (mAttachInfo != null) { 25837 mAttachInfo.mTooltipHost = null; 25838 } 25839 } 25840 25841 private boolean showLongClickTooltip(int x, int y) { 25842 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 25843 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 25844 return showTooltip(x, y, true); 25845 } 25846 25847 private void showHoverTooltip() { 25848 showTooltip(mTooltipInfo.mAnchorX, mTooltipInfo.mAnchorY, false); 25849 } 25850 25851 boolean dispatchTooltipHoverEvent(MotionEvent event) { 25852 if (mTooltipInfo == null) { 25853 return false; 25854 } 25855 switch(event.getAction()) { 25856 case MotionEvent.ACTION_HOVER_MOVE: 25857 if ((mViewFlags & TOOLTIP) != TOOLTIP || (mViewFlags & ENABLED_MASK) != ENABLED) { 25858 break; 25859 } 25860 if (!mTooltipInfo.mTooltipFromLongClick) { 25861 if (mTooltipInfo.mTooltipPopup == null) { 25862 // Schedule showing the tooltip after a timeout. 25863 mTooltipInfo.mAnchorX = (int) event.getX(); 25864 mTooltipInfo.mAnchorY = (int) event.getY(); 25865 removeCallbacks(mTooltipInfo.mShowTooltipRunnable); 25866 postDelayed(mTooltipInfo.mShowTooltipRunnable, 25867 ViewConfiguration.getHoverTooltipShowTimeout()); 25868 } 25869 25870 // Hide hover-triggered tooltip after a period of inactivity. 25871 // Match the timeout used by NativeInputManager to hide the mouse pointer 25872 // (depends on SYSTEM_UI_FLAG_LOW_PROFILE being set). 25873 final int timeout; 25874 if ((getWindowSystemUiVisibility() & SYSTEM_UI_FLAG_LOW_PROFILE) 25875 == SYSTEM_UI_FLAG_LOW_PROFILE) { 25876 timeout = ViewConfiguration.getHoverTooltipHideShortTimeout(); 25877 } else { 25878 timeout = ViewConfiguration.getHoverTooltipHideTimeout(); 25879 } 25880 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 25881 postDelayed(mTooltipInfo.mHideTooltipRunnable, timeout); 25882 } 25883 return true; 25884 25885 case MotionEvent.ACTION_HOVER_EXIT: 25886 if (!mTooltipInfo.mTooltipFromLongClick) { 25887 hideTooltip(); 25888 } 25889 break; 25890 } 25891 return false; 25892 } 25893 25894 void handleTooltipKey(KeyEvent event) { 25895 switch (event.getAction()) { 25896 case KeyEvent.ACTION_DOWN: 25897 if (event.getRepeatCount() == 0) { 25898 hideTooltip(); 25899 } 25900 break; 25901 25902 case KeyEvent.ACTION_UP: 25903 handleTooltipUp(); 25904 break; 25905 } 25906 } 25907 25908 private void handleTooltipUp() { 25909 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 25910 return; 25911 } 25912 removeCallbacks(mTooltipInfo.mHideTooltipRunnable); 25913 postDelayed(mTooltipInfo.mHideTooltipRunnable, 25914 ViewConfiguration.getLongPressTooltipHideTimeout()); 25915 } 25916 25917 private int getFocusableAttribute(TypedArray attributes) { 25918 TypedValue val = new TypedValue(); 25919 if (attributes.getValue(com.android.internal.R.styleable.View_focusable, val)) { 25920 if (val.type == TypedValue.TYPE_INT_BOOLEAN) { 25921 return (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE); 25922 } else { 25923 return val.data; 25924 } 25925 } else { 25926 return FOCUSABLE_AUTO; 25927 } 25928 } 25929 25930 /** 25931 * @return The content view of the tooltip popup currently being shown, or null if the tooltip 25932 * is not showing. 25933 * @hide 25934 */ 25935 @TestApi 25936 public View getTooltipView() { 25937 if (mTooltipInfo == null || mTooltipInfo.mTooltipPopup == null) { 25938 return null; 25939 } 25940 return mTooltipInfo.mTooltipPopup.getContentView(); 25941 } 25942} 25943