View.java revision 8f8a11b7fa26e603519131001ab46596aa30ba1a
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.view; 18 19import android.animation.AnimatorInflater; 20import android.animation.StateListAnimator; 21import android.annotation.IntDef; 22import android.annotation.NonNull; 23import android.annotation.Nullable; 24import android.content.ClipData; 25import android.content.Context; 26import android.content.res.ColorStateList; 27import android.content.res.Configuration; 28import android.content.res.Resources; 29import android.content.res.TypedArray; 30import android.graphics.Bitmap; 31import android.graphics.Canvas; 32import android.graphics.Insets; 33import android.graphics.Interpolator; 34import android.graphics.LinearGradient; 35import android.graphics.Matrix; 36import android.graphics.Outline; 37import android.graphics.Paint; 38import android.graphics.Path; 39import android.graphics.PathMeasure; 40import android.graphics.PixelFormat; 41import android.graphics.Point; 42import android.graphics.PorterDuff; 43import android.graphics.PorterDuffXfermode; 44import android.graphics.Rect; 45import android.graphics.RectF; 46import android.graphics.Region; 47import android.graphics.Shader; 48import android.graphics.drawable.ColorDrawable; 49import android.graphics.drawable.Drawable; 50import android.hardware.display.DisplayManagerGlobal; 51import android.os.Bundle; 52import android.os.Handler; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.RemoteException; 57import android.os.SystemClock; 58import android.os.SystemProperties; 59import android.text.TextUtils; 60import android.util.AttributeSet; 61import android.util.FloatProperty; 62import android.util.LayoutDirection; 63import android.util.Log; 64import android.util.LongSparseLongArray; 65import android.util.Pools.SynchronizedPool; 66import android.util.Property; 67import android.util.SparseArray; 68import android.util.SuperNotCalledException; 69import android.util.TypedValue; 70import android.view.ContextMenu.ContextMenuInfo; 71import android.view.AccessibilityIterators.TextSegmentIterator; 72import android.view.AccessibilityIterators.CharacterTextSegmentIterator; 73import android.view.AccessibilityIterators.WordTextSegmentIterator; 74import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; 75import android.view.accessibility.AccessibilityEvent; 76import android.view.accessibility.AccessibilityEventSource; 77import android.view.accessibility.AccessibilityManager; 78import android.view.accessibility.AccessibilityNodeInfo; 79import android.view.accessibility.AccessibilityNodeProvider; 80import android.view.animation.Animation; 81import android.view.animation.AnimationUtils; 82import android.view.animation.Transformation; 83import android.view.inputmethod.EditorInfo; 84import android.view.inputmethod.InputConnection; 85import android.view.inputmethod.InputMethodManager; 86import android.widget.ScrollBarDrawable; 87 88import static android.os.Build.VERSION_CODES.*; 89import static java.lang.Math.max; 90 91import com.android.internal.R; 92import com.android.internal.util.Predicate; 93import com.android.internal.view.menu.MenuBuilder; 94import com.google.android.collect.Lists; 95import com.google.android.collect.Maps; 96 97import java.lang.annotation.Retention; 98import java.lang.annotation.RetentionPolicy; 99import java.lang.ref.WeakReference; 100import java.lang.reflect.Field; 101import java.lang.reflect.InvocationTargetException; 102import java.lang.reflect.Method; 103import java.lang.reflect.Modifier; 104import java.util.ArrayList; 105import java.util.Arrays; 106import java.util.Collections; 107import java.util.HashMap; 108import java.util.List; 109import java.util.Locale; 110import java.util.Map; 111import java.util.concurrent.CopyOnWriteArrayList; 112import java.util.concurrent.atomic.AtomicInteger; 113 114/** 115 * <p> 116 * This class represents the basic building block for user interface components. A View 117 * occupies a rectangular area on the screen and is responsible for drawing and 118 * event handling. View is the base class for <em>widgets</em>, which are 119 * used to create interactive UI components (buttons, text fields, etc.). The 120 * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which 121 * are invisible containers that hold other Views (or other ViewGroups) and define 122 * their layout properties. 123 * </p> 124 * 125 * <div class="special reference"> 126 * <h3>Developer Guides</h3> 127 * <p>For information about using this class to develop your application's user interface, 128 * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. 129 * </div> 130 * 131 * <a name="Using"></a> 132 * <h3>Using Views</h3> 133 * <p> 134 * All of the views in a window are arranged in a single tree. You can add views 135 * either from code or by specifying a tree of views in one or more XML layout 136 * files. There are many specialized subclasses of views that act as controls or 137 * are capable of displaying text, images, or other content. 138 * </p> 139 * <p> 140 * Once you have created a tree of views, there are typically a few types of 141 * common operations you may wish to perform: 142 * <ul> 143 * <li><strong>Set properties:</strong> for example setting the text of a 144 * {@link android.widget.TextView}. The available properties and the methods 145 * that set them will vary among the different subclasses of views. Note that 146 * properties that are known at build time can be set in the XML layout 147 * files.</li> 148 * <li><strong>Set focus:</strong> The framework will handled moving focus in 149 * response to user input. To force focus to a specific view, call 150 * {@link #requestFocus}.</li> 151 * <li><strong>Set up listeners:</strong> Views allow clients to set listeners 152 * that will be notified when something interesting happens to the view. For 153 * example, all views will let you set a listener to be notified when the view 154 * gains or loses focus. You can register such a listener using 155 * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. 156 * Other view subclasses offer more specialized listeners. For example, a Button 157 * exposes a listener to notify clients when the button is clicked.</li> 158 * <li><strong>Set visibility:</strong> You can hide or show views using 159 * {@link #setVisibility(int)}.</li> 160 * </ul> 161 * </p> 162 * <p><em> 163 * Note: The Android framework is responsible for measuring, laying out and 164 * drawing views. You should not call methods that perform these actions on 165 * views yourself unless you are actually implementing a 166 * {@link android.view.ViewGroup}. 167 * </em></p> 168 * 169 * <a name="Lifecycle"></a> 170 * <h3>Implementing a Custom View</h3> 171 * 172 * <p> 173 * To implement a custom view, you will usually begin by providing overrides for 174 * some of the standard methods that the framework calls on all views. You do 175 * not need to override all of these methods. In fact, you can start by just 176 * overriding {@link #onDraw(android.graphics.Canvas)}. 177 * <table border="2" width="85%" align="center" cellpadding="5"> 178 * <thead> 179 * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> 180 * </thead> 181 * 182 * <tbody> 183 * <tr> 184 * <td rowspan="2">Creation</td> 185 * <td>Constructors</td> 186 * <td>There is a form of the constructor that are called when the view 187 * is created from code and a form that is called when the view is 188 * inflated from a layout file. The second form should parse and apply 189 * any attributes defined in the layout file. 190 * </td> 191 * </tr> 192 * <tr> 193 * <td><code>{@link #onFinishInflate()}</code></td> 194 * <td>Called after a view and all of its children has been inflated 195 * from XML.</td> 196 * </tr> 197 * 198 * <tr> 199 * <td rowspan="3">Layout</td> 200 * <td><code>{@link #onMeasure(int, int)}</code></td> 201 * <td>Called to determine the size requirements for this view and all 202 * of its children. 203 * </td> 204 * </tr> 205 * <tr> 206 * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> 207 * <td>Called when this view should assign a size and position to all 208 * of its children. 209 * </td> 210 * </tr> 211 * <tr> 212 * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> 213 * <td>Called when the size of this view has changed. 214 * </td> 215 * </tr> 216 * 217 * <tr> 218 * <td>Drawing</td> 219 * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> 220 * <td>Called when the view should render its content. 221 * </td> 222 * </tr> 223 * 224 * <tr> 225 * <td rowspan="4">Event processing</td> 226 * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> 227 * <td>Called when a new hardware key event occurs. 228 * </td> 229 * </tr> 230 * <tr> 231 * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> 232 * <td>Called when a hardware key up event occurs. 233 * </td> 234 * </tr> 235 * <tr> 236 * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> 237 * <td>Called when a trackball motion event occurs. 238 * </td> 239 * </tr> 240 * <tr> 241 * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> 242 * <td>Called when a touch screen motion event occurs. 243 * </td> 244 * </tr> 245 * 246 * <tr> 247 * <td rowspan="2">Focus</td> 248 * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> 249 * <td>Called when the view gains or loses focus. 250 * </td> 251 * </tr> 252 * 253 * <tr> 254 * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> 255 * <td>Called when the window containing the view gains or loses focus. 256 * </td> 257 * </tr> 258 * 259 * <tr> 260 * <td rowspan="3">Attaching</td> 261 * <td><code>{@link #onAttachedToWindow()}</code></td> 262 * <td>Called when the view is attached to a window. 263 * </td> 264 * </tr> 265 * 266 * <tr> 267 * <td><code>{@link #onDetachedFromWindow}</code></td> 268 * <td>Called when the view is detached from its window. 269 * </td> 270 * </tr> 271 * 272 * <tr> 273 * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> 274 * <td>Called when the visibility of the window containing the view 275 * has changed. 276 * </td> 277 * </tr> 278 * </tbody> 279 * 280 * </table> 281 * </p> 282 * 283 * <a name="IDs"></a> 284 * <h3>IDs</h3> 285 * Views may have an integer id associated with them. These ids are typically 286 * assigned in the layout XML files, and are used to find specific views within 287 * the view tree. A common pattern is to: 288 * <ul> 289 * <li>Define a Button in the layout file and assign it a unique ID. 290 * <pre> 291 * <Button 292 * android:id="@+id/my_button" 293 * android:layout_width="wrap_content" 294 * android:layout_height="wrap_content" 295 * android:text="@string/my_button_text"/> 296 * </pre></li> 297 * <li>From the onCreate method of an Activity, find the Button 298 * <pre class="prettyprint"> 299 * Button myButton = (Button) findViewById(R.id.my_button); 300 * </pre></li> 301 * </ul> 302 * <p> 303 * View IDs need not be unique throughout the tree, but it is good practice to 304 * ensure that they are at least unique within the part of the tree you are 305 * searching. 306 * </p> 307 * 308 * <a name="Position"></a> 309 * <h3>Position</h3> 310 * <p> 311 * The geometry of a view is that of a rectangle. A view has a location, 312 * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and 313 * two dimensions, expressed as a width and a height. The unit for location 314 * and dimensions is the pixel. 315 * </p> 316 * 317 * <p> 318 * It is possible to retrieve the location of a view by invoking the methods 319 * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, 320 * coordinate of the rectangle representing the view. The latter returns the 321 * top, or Y, coordinate of the rectangle representing the view. These methods 322 * both return the location of the view relative to its parent. For instance, 323 * when getLeft() returns 20, that means the view is located 20 pixels to the 324 * right of the left edge of its direct parent. 325 * </p> 326 * 327 * <p> 328 * In addition, several convenience methods are offered to avoid unnecessary 329 * computations, namely {@link #getRight()} and {@link #getBottom()}. 330 * These methods return the coordinates of the right and bottom edges of the 331 * rectangle representing the view. For instance, calling {@link #getRight()} 332 * is similar to the following computation: <code>getLeft() + getWidth()</code> 333 * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) 334 * </p> 335 * 336 * <a name="SizePaddingMargins"></a> 337 * <h3>Size, padding and margins</h3> 338 * <p> 339 * The size of a view is expressed with a width and a height. A view actually 340 * possess two pairs of width and height values. 341 * </p> 342 * 343 * <p> 344 * The first pair is known as <em>measured width</em> and 345 * <em>measured height</em>. These dimensions define how big a view wants to be 346 * within its parent (see <a href="#Layout">Layout</a> for more details.) The 347 * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} 348 * and {@link #getMeasuredHeight()}. 349 * </p> 350 * 351 * <p> 352 * The second pair is simply known as <em>width</em> and <em>height</em>, or 353 * sometimes <em>drawing width</em> and <em>drawing height</em>. These 354 * dimensions define the actual size of the view on screen, at drawing time and 355 * after layout. These values may, but do not have to, be different from the 356 * measured width and height. The width and height can be obtained by calling 357 * {@link #getWidth()} and {@link #getHeight()}. 358 * </p> 359 * 360 * <p> 361 * To measure its dimensions, a view takes into account its padding. The padding 362 * is expressed in pixels for the left, top, right and bottom parts of the view. 363 * Padding can be used to offset the content of the view by a specific amount of 364 * pixels. For instance, a left padding of 2 will push the view's content by 365 * 2 pixels to the right of the left edge. Padding can be set using the 366 * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} 367 * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, 368 * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, 369 * {@link #getPaddingEnd()}. 370 * </p> 371 * 372 * <p> 373 * Even though a view can define a padding, it does not provide any support for 374 * margins. However, view groups provide such a support. Refer to 375 * {@link android.view.ViewGroup} and 376 * {@link android.view.ViewGroup.MarginLayoutParams} for further information. 377 * </p> 378 * 379 * <a name="Layout"></a> 380 * <h3>Layout</h3> 381 * <p> 382 * Layout is a two pass process: a measure pass and a layout pass. The measuring 383 * pass is implemented in {@link #measure(int, int)} and is a top-down traversal 384 * of the view tree. Each view pushes dimension specifications down the tree 385 * during the recursion. At the end of the measure pass, every view has stored 386 * its measurements. The second pass happens in 387 * {@link #layout(int,int,int,int)} and is also top-down. During 388 * this pass each parent is responsible for positioning all of its children 389 * using the sizes computed in the measure pass. 390 * </p> 391 * 392 * <p> 393 * When a view's measure() method returns, its {@link #getMeasuredWidth()} and 394 * {@link #getMeasuredHeight()} values must be set, along with those for all of 395 * that view's descendants. A view's measured width and measured height values 396 * must respect the constraints imposed by the view's parents. This guarantees 397 * that at the end of the measure pass, all parents accept all of their 398 * children's measurements. A parent view may call measure() more than once on 399 * its children. For example, the parent may measure each child once with 400 * unspecified dimensions to find out how big they want to be, then call 401 * measure() on them again with actual numbers if the sum of all the children's 402 * unconstrained sizes is too big or too small. 403 * </p> 404 * 405 * <p> 406 * The measure pass uses two classes to communicate dimensions. The 407 * {@link MeasureSpec} class is used by views to tell their parents how they 408 * want to be measured and positioned. The base LayoutParams class just 409 * describes how big the view wants to be for both width and height. For each 410 * dimension, it can specify one of: 411 * <ul> 412 * <li> an exact number 413 * <li>MATCH_PARENT, which means the view wants to be as big as its parent 414 * (minus padding) 415 * <li> WRAP_CONTENT, which means that the view wants to be just big enough to 416 * enclose its content (plus padding). 417 * </ul> 418 * There are subclasses of LayoutParams for different subclasses of ViewGroup. 419 * For example, AbsoluteLayout has its own subclass of LayoutParams which adds 420 * an X and Y value. 421 * </p> 422 * 423 * <p> 424 * MeasureSpecs are used to push requirements down the tree from parent to 425 * child. A MeasureSpec can be in one of three modes: 426 * <ul> 427 * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension 428 * of a child view. For example, a LinearLayout may call measure() on its child 429 * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how 430 * tall the child view wants to be given a width of 240 pixels. 431 * <li>EXACTLY: This is used by the parent to impose an exact size on the 432 * child. The child must use this size, and guarantee that all of its 433 * descendants will fit within this size. 434 * <li>AT_MOST: This is used by the parent to impose a maximum size on the 435 * child. The child must guarantee that it and all of its descendants will fit 436 * within this size. 437 * </ul> 438 * </p> 439 * 440 * <p> 441 * To intiate a layout, call {@link #requestLayout}. This method is typically 442 * called by a view on itself when it believes that is can no longer fit within 443 * its current bounds. 444 * </p> 445 * 446 * <a name="Drawing"></a> 447 * <h3>Drawing</h3> 448 * <p> 449 * Drawing is handled by walking the tree and recording the drawing commands of 450 * any View that needs to update. After this, the drawing commands of the 451 * entire tree are issued to screen, clipped to the newly damaged area. 452 * </p> 453 * 454 * <p> 455 * The tree is largely recorded and drawn in order, with parents drawn before 456 * (i.e., behind) their children, with siblings drawn in the order they appear 457 * in the tree. If you set a background drawable for a View, then the View will 458 * draw it before calling back to its <code>onDraw()</code> method. The child 459 * drawing order can be overridden with 460 * {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean) custom child drawing order} 461 * in a ViewGroup, and with {@link #setZ(float)} custom Z values} set on Views. 462 * </p> 463 * 464 * <p> 465 * To force a view to draw, call {@link #invalidate()}. 466 * </p> 467 * 468 * <a name="EventHandlingThreading"></a> 469 * <h3>Event Handling and Threading</h3> 470 * <p> 471 * The basic cycle of a view is as follows: 472 * <ol> 473 * <li>An event comes in and is dispatched to the appropriate view. The view 474 * handles the event and notifies any listeners.</li> 475 * <li>If in the course of processing the event, the view's bounds may need 476 * to be changed, the view will call {@link #requestLayout()}.</li> 477 * <li>Similarly, if in the course of processing the event the view's appearance 478 * may need to be changed, the view will call {@link #invalidate()}.</li> 479 * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, 480 * the framework will take care of measuring, laying out, and drawing the tree 481 * as appropriate.</li> 482 * </ol> 483 * </p> 484 * 485 * <p><em>Note: The entire view tree is single threaded. You must always be on 486 * the UI thread when calling any method on any view.</em> 487 * If you are doing work on other threads and want to update the state of a view 488 * from that thread, you should use a {@link Handler}. 489 * </p> 490 * 491 * <a name="FocusHandling"></a> 492 * <h3>Focus Handling</h3> 493 * <p> 494 * The framework will handle routine focus movement in response to user input. 495 * This includes changing the focus as views are removed or hidden, or as new 496 * views become available. Views indicate their willingness to take focus 497 * through the {@link #isFocusable} method. To change whether a view can take 498 * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) 499 * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} 500 * and can change this via {@link #setFocusableInTouchMode(boolean)}. 501 * </p> 502 * <p> 503 * Focus movement is based on an algorithm which finds the nearest neighbor in a 504 * given direction. In rare cases, the default algorithm may not match the 505 * intended behavior of the developer. In these situations, you can provide 506 * explicit overrides by using these XML attributes in the layout file: 507 * <pre> 508 * nextFocusDown 509 * nextFocusLeft 510 * nextFocusRight 511 * nextFocusUp 512 * </pre> 513 * </p> 514 * 515 * 516 * <p> 517 * To get a particular view to take focus, call {@link #requestFocus()}. 518 * </p> 519 * 520 * <a name="TouchMode"></a> 521 * <h3>Touch Mode</h3> 522 * <p> 523 * When a user is navigating a user interface via directional keys such as a D-pad, it is 524 * necessary to give focus to actionable items such as buttons so the user can see 525 * what will take input. If the device has touch capabilities, however, and the user 526 * begins interacting with the interface by touching it, it is no longer necessary to 527 * always highlight, or give focus to, a particular view. This motivates a mode 528 * for interaction named 'touch mode'. 529 * </p> 530 * <p> 531 * For a touch capable device, once the user touches the screen, the device 532 * will enter touch mode. From this point onward, only views for which 533 * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. 534 * Other views that are touchable, like buttons, will not take focus when touched; they will 535 * only fire the on click listeners. 536 * </p> 537 * <p> 538 * Any time a user hits a directional key, such as a D-pad direction, the view device will 539 * exit touch mode, and find a view to take focus, so that the user may resume interacting 540 * with the user interface without touching the screen again. 541 * </p> 542 * <p> 543 * The touch mode state is maintained across {@link android.app.Activity}s. Call 544 * {@link #isInTouchMode} to see whether the device is currently in touch mode. 545 * </p> 546 * 547 * <a name="Scrolling"></a> 548 * <h3>Scrolling</h3> 549 * <p> 550 * The framework provides basic support for views that wish to internally 551 * scroll their content. This includes keeping track of the X and Y scroll 552 * offset as well as mechanisms for drawing scrollbars. See 553 * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and 554 * {@link #awakenScrollBars()} for more details. 555 * </p> 556 * 557 * <a name="Tags"></a> 558 * <h3>Tags</h3> 559 * <p> 560 * Unlike IDs, tags are not used to identify views. Tags are essentially an 561 * extra piece of information that can be associated with a view. They are most 562 * often used as a convenience to store data related to views in the views 563 * themselves rather than by putting them in a separate structure. 564 * </p> 565 * 566 * <a name="Properties"></a> 567 * <h3>Properties</h3> 568 * <p> 569 * The View class exposes an {@link #ALPHA} property, as well as several transform-related 570 * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are 571 * available both in the {@link Property} form as well as in similarly-named setter/getter 572 * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can 573 * be used to set persistent state associated with these rendering-related properties on the view. 574 * The properties and methods can also be used in conjunction with 575 * {@link android.animation.Animator Animator}-based animations, described more in the 576 * <a href="#Animation">Animation</a> section. 577 * </p> 578 * 579 * <a name="Animation"></a> 580 * <h3>Animation</h3> 581 * <p> 582 * Starting with Android 3.0, the preferred way of animating views is to use the 583 * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based 584 * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and 585 * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 586 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only 587 * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class 588 * makes animating these View properties particularly easy and efficient. 589 * </p> 590 * <p> 591 * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. 592 * You can attach an {@link Animation} object to a view using 593 * {@link #setAnimation(Animation)} or 594 * {@link #startAnimation(Animation)}. The animation can alter the scale, 595 * rotation, translation and alpha of a view over time. If the animation is 596 * attached to a view that has children, the animation will affect the entire 597 * subtree rooted by that node. When an animation is started, the framework will 598 * take care of redrawing the appropriate views until the animation completes. 599 * </p> 600 * 601 * <a name="Security"></a> 602 * <h3>Security</h3> 603 * <p> 604 * Sometimes it is essential that an application be able to verify that an action 605 * is being performed with the full knowledge and consent of the user, such as 606 * granting a permission request, making a purchase or clicking on an advertisement. 607 * Unfortunately, a malicious application could try to spoof the user into 608 * performing these actions, unaware, by concealing the intended purpose of the view. 609 * As a remedy, the framework offers a touch filtering mechanism that can be used to 610 * improve the security of views that provide access to sensitive functionality. 611 * </p><p> 612 * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the 613 * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework 614 * will discard touches that are received whenever the view's window is obscured by 615 * another visible window. As a result, the view will not receive touches whenever a 616 * toast, dialog or other window appears above the view's window. 617 * </p><p> 618 * For more fine-grained control over security, consider overriding the 619 * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own 620 * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. 621 * </p> 622 * 623 * @attr ref android.R.styleable#View_alpha 624 * @attr ref android.R.styleable#View_background 625 * @attr ref android.R.styleable#View_clickable 626 * @attr ref android.R.styleable#View_contentDescription 627 * @attr ref android.R.styleable#View_drawingCacheQuality 628 * @attr ref android.R.styleable#View_duplicateParentState 629 * @attr ref android.R.styleable#View_id 630 * @attr ref android.R.styleable#View_requiresFadingEdge 631 * @attr ref android.R.styleable#View_fadeScrollbars 632 * @attr ref android.R.styleable#View_fadingEdgeLength 633 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 634 * @attr ref android.R.styleable#View_fitsSystemWindows 635 * @attr ref android.R.styleable#View_isScrollContainer 636 * @attr ref android.R.styleable#View_focusable 637 * @attr ref android.R.styleable#View_focusableInTouchMode 638 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 639 * @attr ref android.R.styleable#View_keepScreenOn 640 * @attr ref android.R.styleable#View_layerType 641 * @attr ref android.R.styleable#View_layoutDirection 642 * @attr ref android.R.styleable#View_longClickable 643 * @attr ref android.R.styleable#View_minHeight 644 * @attr ref android.R.styleable#View_minWidth 645 * @attr ref android.R.styleable#View_nextFocusDown 646 * @attr ref android.R.styleable#View_nextFocusLeft 647 * @attr ref android.R.styleable#View_nextFocusRight 648 * @attr ref android.R.styleable#View_nextFocusUp 649 * @attr ref android.R.styleable#View_onClick 650 * @attr ref android.R.styleable#View_padding 651 * @attr ref android.R.styleable#View_paddingBottom 652 * @attr ref android.R.styleable#View_paddingLeft 653 * @attr ref android.R.styleable#View_paddingRight 654 * @attr ref android.R.styleable#View_paddingTop 655 * @attr ref android.R.styleable#View_paddingStart 656 * @attr ref android.R.styleable#View_paddingEnd 657 * @attr ref android.R.styleable#View_saveEnabled 658 * @attr ref android.R.styleable#View_rotation 659 * @attr ref android.R.styleable#View_rotationX 660 * @attr ref android.R.styleable#View_rotationY 661 * @attr ref android.R.styleable#View_scaleX 662 * @attr ref android.R.styleable#View_scaleY 663 * @attr ref android.R.styleable#View_scrollX 664 * @attr ref android.R.styleable#View_scrollY 665 * @attr ref android.R.styleable#View_scrollbarSize 666 * @attr ref android.R.styleable#View_scrollbarStyle 667 * @attr ref android.R.styleable#View_scrollbars 668 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 669 * @attr ref android.R.styleable#View_scrollbarFadeDuration 670 * @attr ref android.R.styleable#View_scrollbarTrackHorizontal 671 * @attr ref android.R.styleable#View_scrollbarThumbHorizontal 672 * @attr ref android.R.styleable#View_scrollbarThumbVertical 673 * @attr ref android.R.styleable#View_scrollbarTrackVertical 674 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack 675 * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack 676 * @attr ref android.R.styleable#View_stateListAnimator 677 * @attr ref android.R.styleable#View_transitionName 678 * @attr ref android.R.styleable#View_soundEffectsEnabled 679 * @attr ref android.R.styleable#View_tag 680 * @attr ref android.R.styleable#View_textAlignment 681 * @attr ref android.R.styleable#View_textDirection 682 * @attr ref android.R.styleable#View_transformPivotX 683 * @attr ref android.R.styleable#View_transformPivotY 684 * @attr ref android.R.styleable#View_translationX 685 * @attr ref android.R.styleable#View_translationY 686 * @attr ref android.R.styleable#View_translationZ 687 * @attr ref android.R.styleable#View_visibility 688 * 689 * @see android.view.ViewGroup 690 */ 691public class View implements Drawable.Callback, KeyEvent.Callback, 692 AccessibilityEventSource { 693 private static final boolean DBG = false; 694 695 /** 696 * The logging tag used by this class with android.util.Log. 697 */ 698 protected static final String VIEW_LOG_TAG = "View"; 699 700 /** 701 * When set to true, apps will draw debugging information about their layouts. 702 * 703 * @hide 704 */ 705 public static final String DEBUG_LAYOUT_PROPERTY = "debug.layout"; 706 707 /** 708 * When set to true, this view will save its attribute data. 709 * 710 * @hide 711 */ 712 public static boolean mDebugViewAttributes = false; 713 714 /** 715 * Used to mark a View that has no ID. 716 */ 717 public static final int NO_ID = -1; 718 719 /** 720 * Signals that compatibility booleans have been initialized according to 721 * target SDK versions. 722 */ 723 private static boolean sCompatibilityDone = false; 724 725 /** 726 * Use the old (broken) way of building MeasureSpecs. 727 */ 728 private static boolean sUseBrokenMakeMeasureSpec = false; 729 730 /** 731 * Ignore any optimizations using the measure cache. 732 */ 733 private static boolean sIgnoreMeasureCache = false; 734 735 /** 736 * This view does not want keystrokes. Use with TAKES_FOCUS_MASK when 737 * calling setFlags. 738 */ 739 private static final int NOT_FOCUSABLE = 0x00000000; 740 741 /** 742 * This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling 743 * setFlags. 744 */ 745 private static final int FOCUSABLE = 0x00000001; 746 747 /** 748 * Mask for use with setFlags indicating bits used for focus. 749 */ 750 private static final int FOCUSABLE_MASK = 0x00000001; 751 752 /** 753 * This view will adjust its padding to fit sytem windows (e.g. status bar) 754 */ 755 private static final int FITS_SYSTEM_WINDOWS = 0x00000002; 756 757 /** @hide */ 758 @IntDef({VISIBLE, INVISIBLE, GONE}) 759 @Retention(RetentionPolicy.SOURCE) 760 public @interface Visibility {} 761 762 /** 763 * This view is visible. 764 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 765 * android:visibility}. 766 */ 767 public static final int VISIBLE = 0x00000000; 768 769 /** 770 * This view is invisible, but it still takes up space for layout purposes. 771 * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 772 * android:visibility}. 773 */ 774 public static final int INVISIBLE = 0x00000004; 775 776 /** 777 * This view is invisible, and it doesn't take any space for layout 778 * purposes. Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code 779 * android:visibility}. 780 */ 781 public static final int GONE = 0x00000008; 782 783 /** 784 * Mask for use with setFlags indicating bits used for visibility. 785 * {@hide} 786 */ 787 static final int VISIBILITY_MASK = 0x0000000C; 788 789 private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE}; 790 791 /** 792 * This view is enabled. Interpretation varies by subclass. 793 * Use with ENABLED_MASK when calling setFlags. 794 * {@hide} 795 */ 796 static final int ENABLED = 0x00000000; 797 798 /** 799 * This view is disabled. Interpretation varies by subclass. 800 * Use with ENABLED_MASK when calling setFlags. 801 * {@hide} 802 */ 803 static final int DISABLED = 0x00000020; 804 805 /** 806 * Mask for use with setFlags indicating bits used for indicating whether 807 * this view is enabled 808 * {@hide} 809 */ 810 static final int ENABLED_MASK = 0x00000020; 811 812 /** 813 * This view won't draw. {@link #onDraw(android.graphics.Canvas)} won't be 814 * called and further optimizations will be performed. It is okay to have 815 * this flag set and a background. Use with DRAW_MASK when calling setFlags. 816 * {@hide} 817 */ 818 static final int WILL_NOT_DRAW = 0x00000080; 819 820 /** 821 * Mask for use with setFlags indicating bits used for indicating whether 822 * this view is will draw 823 * {@hide} 824 */ 825 static final int DRAW_MASK = 0x00000080; 826 827 /** 828 * <p>This view doesn't show scrollbars.</p> 829 * {@hide} 830 */ 831 static final int SCROLLBARS_NONE = 0x00000000; 832 833 /** 834 * <p>This view shows horizontal scrollbars.</p> 835 * {@hide} 836 */ 837 static final int SCROLLBARS_HORIZONTAL = 0x00000100; 838 839 /** 840 * <p>This view shows vertical scrollbars.</p> 841 * {@hide} 842 */ 843 static final int SCROLLBARS_VERTICAL = 0x00000200; 844 845 /** 846 * <p>Mask for use with setFlags indicating bits used for indicating which 847 * scrollbars are enabled.</p> 848 * {@hide} 849 */ 850 static final int SCROLLBARS_MASK = 0x00000300; 851 852 /** 853 * Indicates that the view should filter touches when its window is obscured. 854 * Refer to the class comments for more information about this security feature. 855 * {@hide} 856 */ 857 static final int FILTER_TOUCHES_WHEN_OBSCURED = 0x00000400; 858 859 /** 860 * Set for framework elements that use FITS_SYSTEM_WINDOWS, to indicate 861 * that they are optional and should be skipped if the window has 862 * requested system UI flags that ignore those insets for layout. 863 */ 864 static final int OPTIONAL_FITS_SYSTEM_WINDOWS = 0x00000800; 865 866 /** 867 * <p>This view doesn't show fading edges.</p> 868 * {@hide} 869 */ 870 static final int FADING_EDGE_NONE = 0x00000000; 871 872 /** 873 * <p>This view shows horizontal fading edges.</p> 874 * {@hide} 875 */ 876 static final int FADING_EDGE_HORIZONTAL = 0x00001000; 877 878 /** 879 * <p>This view shows vertical fading edges.</p> 880 * {@hide} 881 */ 882 static final int FADING_EDGE_VERTICAL = 0x00002000; 883 884 /** 885 * <p>Mask for use with setFlags indicating bits used for indicating which 886 * fading edges are enabled.</p> 887 * {@hide} 888 */ 889 static final int FADING_EDGE_MASK = 0x00003000; 890 891 /** 892 * <p>Indicates this view can be clicked. When clickable, a View reacts 893 * to clicks by notifying the OnClickListener.<p> 894 * {@hide} 895 */ 896 static final int CLICKABLE = 0x00004000; 897 898 /** 899 * <p>Indicates this view is caching its drawing into a bitmap.</p> 900 * {@hide} 901 */ 902 static final int DRAWING_CACHE_ENABLED = 0x00008000; 903 904 /** 905 * <p>Indicates that no icicle should be saved for this view.<p> 906 * {@hide} 907 */ 908 static final int SAVE_DISABLED = 0x000010000; 909 910 /** 911 * <p>Mask for use with setFlags indicating bits used for the saveEnabled 912 * property.</p> 913 * {@hide} 914 */ 915 static final int SAVE_DISABLED_MASK = 0x000010000; 916 917 /** 918 * <p>Indicates that no drawing cache should ever be created for this view.<p> 919 * {@hide} 920 */ 921 static final int WILL_NOT_CACHE_DRAWING = 0x000020000; 922 923 /** 924 * <p>Indicates this view can take / keep focus when int touch mode.</p> 925 * {@hide} 926 */ 927 static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000; 928 929 /** @hide */ 930 @Retention(RetentionPolicy.SOURCE) 931 @IntDef({DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH, DRAWING_CACHE_QUALITY_AUTO}) 932 public @interface DrawingCacheQuality {} 933 934 /** 935 * <p>Enables low quality mode for the drawing cache.</p> 936 */ 937 public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; 938 939 /** 940 * <p>Enables high quality mode for the drawing cache.</p> 941 */ 942 public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; 943 944 /** 945 * <p>Enables automatic quality mode for the drawing cache.</p> 946 */ 947 public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; 948 949 private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { 950 DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH 951 }; 952 953 /** 954 * <p>Mask for use with setFlags indicating bits used for the cache 955 * quality property.</p> 956 * {@hide} 957 */ 958 static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000; 959 960 /** 961 * <p> 962 * Indicates this view can be long clicked. When long clickable, a View 963 * reacts to long clicks by notifying the OnLongClickListener or showing a 964 * context menu. 965 * </p> 966 * {@hide} 967 */ 968 static final int LONG_CLICKABLE = 0x00200000; 969 970 /** 971 * <p>Indicates that this view gets its drawable states from its direct parent 972 * and ignores its original internal states.</p> 973 * 974 * @hide 975 */ 976 static final int DUPLICATE_PARENT_STATE = 0x00400000; 977 978 /** @hide */ 979 @IntDef({ 980 SCROLLBARS_INSIDE_OVERLAY, 981 SCROLLBARS_INSIDE_INSET, 982 SCROLLBARS_OUTSIDE_OVERLAY, 983 SCROLLBARS_OUTSIDE_INSET 984 }) 985 @Retention(RetentionPolicy.SOURCE) 986 public @interface ScrollBarStyle {} 987 988 /** 989 * The scrollbar style to display the scrollbars inside the content area, 990 * without increasing the padding. The scrollbars will be overlaid with 991 * translucency on the view's content. 992 */ 993 public static final int SCROLLBARS_INSIDE_OVERLAY = 0; 994 995 /** 996 * The scrollbar style to display the scrollbars inside the padded area, 997 * increasing the padding of the view. The scrollbars will not overlap the 998 * content area of the view. 999 */ 1000 public static final int SCROLLBARS_INSIDE_INSET = 0x01000000; 1001 1002 /** 1003 * The scrollbar style to display the scrollbars at the edge of the view, 1004 * without increasing the padding. The scrollbars will be overlaid with 1005 * translucency. 1006 */ 1007 public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000; 1008 1009 /** 1010 * The scrollbar style to display the scrollbars at the edge of the view, 1011 * increasing the padding of the view. The scrollbars will only overlap the 1012 * background, if any. 1013 */ 1014 public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000; 1015 1016 /** 1017 * Mask to check if the scrollbar style is overlay or inset. 1018 * {@hide} 1019 */ 1020 static final int SCROLLBARS_INSET_MASK = 0x01000000; 1021 1022 /** 1023 * Mask to check if the scrollbar style is inside or outside. 1024 * {@hide} 1025 */ 1026 static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000; 1027 1028 /** 1029 * Mask for scrollbar style. 1030 * {@hide} 1031 */ 1032 static final int SCROLLBARS_STYLE_MASK = 0x03000000; 1033 1034 /** 1035 * View flag indicating that the screen should remain on while the 1036 * window containing this view is visible to the user. This effectively 1037 * takes care of automatically setting the WindowManager's 1038 * {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}. 1039 */ 1040 public static final int KEEP_SCREEN_ON = 0x04000000; 1041 1042 /** 1043 * View flag indicating whether this view should have sound effects enabled 1044 * for events such as clicking and touching. 1045 */ 1046 public static final int SOUND_EFFECTS_ENABLED = 0x08000000; 1047 1048 /** 1049 * View flag indicating whether this view should have haptic feedback 1050 * enabled for events such as long presses. 1051 */ 1052 public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000; 1053 1054 /** 1055 * <p>Indicates that the view hierarchy should stop saving state when 1056 * it reaches this view. If state saving is initiated immediately at 1057 * the view, it will be allowed. 1058 * {@hide} 1059 */ 1060 static final int PARENT_SAVE_DISABLED = 0x20000000; 1061 1062 /** 1063 * <p>Mask for use with setFlags indicating bits used for PARENT_SAVE_DISABLED.</p> 1064 * {@hide} 1065 */ 1066 static final int PARENT_SAVE_DISABLED_MASK = 0x20000000; 1067 1068 /** @hide */ 1069 @IntDef(flag = true, 1070 value = { 1071 FOCUSABLES_ALL, 1072 FOCUSABLES_TOUCH_MODE 1073 }) 1074 @Retention(RetentionPolicy.SOURCE) 1075 public @interface FocusableMode {} 1076 1077 /** 1078 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1079 * should add all focusable Views regardless if they are focusable in touch mode. 1080 */ 1081 public static final int FOCUSABLES_ALL = 0x00000000; 1082 1083 /** 1084 * View flag indicating whether {@link #addFocusables(ArrayList, int, int)} 1085 * should add only Views focusable in touch mode. 1086 */ 1087 public static final int FOCUSABLES_TOUCH_MODE = 0x00000001; 1088 1089 /** @hide */ 1090 @IntDef({ 1091 FOCUS_BACKWARD, 1092 FOCUS_FORWARD, 1093 FOCUS_LEFT, 1094 FOCUS_UP, 1095 FOCUS_RIGHT, 1096 FOCUS_DOWN 1097 }) 1098 @Retention(RetentionPolicy.SOURCE) 1099 public @interface FocusDirection {} 1100 1101 /** @hide */ 1102 @IntDef({ 1103 FOCUS_LEFT, 1104 FOCUS_UP, 1105 FOCUS_RIGHT, 1106 FOCUS_DOWN 1107 }) 1108 @Retention(RetentionPolicy.SOURCE) 1109 public @interface FocusRealDirection {} // Like @FocusDirection, but without forward/backward 1110 1111 /** 1112 * Use with {@link #focusSearch(int)}. Move focus to the previous selectable 1113 * item. 1114 */ 1115 public static final int FOCUS_BACKWARD = 0x00000001; 1116 1117 /** 1118 * Use with {@link #focusSearch(int)}. Move focus to the next selectable 1119 * item. 1120 */ 1121 public static final int FOCUS_FORWARD = 0x00000002; 1122 1123 /** 1124 * Use with {@link #focusSearch(int)}. Move focus to the left. 1125 */ 1126 public static final int FOCUS_LEFT = 0x00000011; 1127 1128 /** 1129 * Use with {@link #focusSearch(int)}. Move focus up. 1130 */ 1131 public static final int FOCUS_UP = 0x00000021; 1132 1133 /** 1134 * Use with {@link #focusSearch(int)}. Move focus to the right. 1135 */ 1136 public static final int FOCUS_RIGHT = 0x00000042; 1137 1138 /** 1139 * Use with {@link #focusSearch(int)}. Move focus down. 1140 */ 1141 public static final int FOCUS_DOWN = 0x00000082; 1142 1143 /** 1144 * Bits of {@link #getMeasuredWidthAndState()} and 1145 * {@link #getMeasuredWidthAndState()} that provide the actual measured size. 1146 */ 1147 public static final int MEASURED_SIZE_MASK = 0x00ffffff; 1148 1149 /** 1150 * Bits of {@link #getMeasuredWidthAndState()} and 1151 * {@link #getMeasuredWidthAndState()} that provide the additional state bits. 1152 */ 1153 public static final int MEASURED_STATE_MASK = 0xff000000; 1154 1155 /** 1156 * Bit shift of {@link #MEASURED_STATE_MASK} to get to the height bits 1157 * for functions that combine both width and height into a single int, 1158 * such as {@link #getMeasuredState()} and the childState argument of 1159 * {@link #resolveSizeAndState(int, int, int)}. 1160 */ 1161 public static final int MEASURED_HEIGHT_STATE_SHIFT = 16; 1162 1163 /** 1164 * Bit of {@link #getMeasuredWidthAndState()} and 1165 * {@link #getMeasuredWidthAndState()} that indicates the measured size 1166 * is smaller that the space the view would like to have. 1167 */ 1168 public static final int MEASURED_STATE_TOO_SMALL = 0x01000000; 1169 1170 /** 1171 * Base View state sets 1172 */ 1173 // Singles 1174 /** 1175 * Indicates the view has no states set. States are used with 1176 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1177 * view depending on its state. 1178 * 1179 * @see android.graphics.drawable.Drawable 1180 * @see #getDrawableState() 1181 */ 1182 protected static final int[] EMPTY_STATE_SET; 1183 /** 1184 * Indicates the view is enabled. States are used with 1185 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1186 * view depending on its state. 1187 * 1188 * @see android.graphics.drawable.Drawable 1189 * @see #getDrawableState() 1190 */ 1191 protected static final int[] ENABLED_STATE_SET; 1192 /** 1193 * Indicates the view is focused. States are used with 1194 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1195 * view depending on its state. 1196 * 1197 * @see android.graphics.drawable.Drawable 1198 * @see #getDrawableState() 1199 */ 1200 protected static final int[] FOCUSED_STATE_SET; 1201 /** 1202 * Indicates the view is selected. States are used with 1203 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1204 * view depending on its state. 1205 * 1206 * @see android.graphics.drawable.Drawable 1207 * @see #getDrawableState() 1208 */ 1209 protected static final int[] SELECTED_STATE_SET; 1210 /** 1211 * Indicates the view is pressed. States are used with 1212 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1213 * view depending on its state. 1214 * 1215 * @see android.graphics.drawable.Drawable 1216 * @see #getDrawableState() 1217 */ 1218 protected static final int[] PRESSED_STATE_SET; 1219 /** 1220 * Indicates the view's window has focus. States are used with 1221 * {@link android.graphics.drawable.Drawable} to change the drawing of the 1222 * view depending on its state. 1223 * 1224 * @see android.graphics.drawable.Drawable 1225 * @see #getDrawableState() 1226 */ 1227 protected static final int[] WINDOW_FOCUSED_STATE_SET; 1228 // Doubles 1229 /** 1230 * Indicates the view is enabled and has the focus. 1231 * 1232 * @see #ENABLED_STATE_SET 1233 * @see #FOCUSED_STATE_SET 1234 */ 1235 protected static final int[] ENABLED_FOCUSED_STATE_SET; 1236 /** 1237 * Indicates the view is enabled and selected. 1238 * 1239 * @see #ENABLED_STATE_SET 1240 * @see #SELECTED_STATE_SET 1241 */ 1242 protected static final int[] ENABLED_SELECTED_STATE_SET; 1243 /** 1244 * Indicates the view is enabled and that its window has focus. 1245 * 1246 * @see #ENABLED_STATE_SET 1247 * @see #WINDOW_FOCUSED_STATE_SET 1248 */ 1249 protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET; 1250 /** 1251 * Indicates the view is focused and selected. 1252 * 1253 * @see #FOCUSED_STATE_SET 1254 * @see #SELECTED_STATE_SET 1255 */ 1256 protected static final int[] FOCUSED_SELECTED_STATE_SET; 1257 /** 1258 * Indicates the view has the focus and that its window has the focus. 1259 * 1260 * @see #FOCUSED_STATE_SET 1261 * @see #WINDOW_FOCUSED_STATE_SET 1262 */ 1263 protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET; 1264 /** 1265 * Indicates the view is selected and that its window has the focus. 1266 * 1267 * @see #SELECTED_STATE_SET 1268 * @see #WINDOW_FOCUSED_STATE_SET 1269 */ 1270 protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET; 1271 // Triples 1272 /** 1273 * Indicates the view is enabled, focused and selected. 1274 * 1275 * @see #ENABLED_STATE_SET 1276 * @see #FOCUSED_STATE_SET 1277 * @see #SELECTED_STATE_SET 1278 */ 1279 protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET; 1280 /** 1281 * Indicates the view is enabled, focused and its window has the focus. 1282 * 1283 * @see #ENABLED_STATE_SET 1284 * @see #FOCUSED_STATE_SET 1285 * @see #WINDOW_FOCUSED_STATE_SET 1286 */ 1287 protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1288 /** 1289 * Indicates the view is enabled, selected and its window has the focus. 1290 * 1291 * @see #ENABLED_STATE_SET 1292 * @see #SELECTED_STATE_SET 1293 * @see #WINDOW_FOCUSED_STATE_SET 1294 */ 1295 protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1296 /** 1297 * Indicates the view is focused, selected and its window has the focus. 1298 * 1299 * @see #FOCUSED_STATE_SET 1300 * @see #SELECTED_STATE_SET 1301 * @see #WINDOW_FOCUSED_STATE_SET 1302 */ 1303 protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1304 /** 1305 * Indicates the view is enabled, focused, selected and its window 1306 * has the focus. 1307 * 1308 * @see #ENABLED_STATE_SET 1309 * @see #FOCUSED_STATE_SET 1310 * @see #SELECTED_STATE_SET 1311 * @see #WINDOW_FOCUSED_STATE_SET 1312 */ 1313 protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1314 /** 1315 * Indicates the view is pressed and its window has the focus. 1316 * 1317 * @see #PRESSED_STATE_SET 1318 * @see #WINDOW_FOCUSED_STATE_SET 1319 */ 1320 protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET; 1321 /** 1322 * Indicates the view is pressed and selected. 1323 * 1324 * @see #PRESSED_STATE_SET 1325 * @see #SELECTED_STATE_SET 1326 */ 1327 protected static final int[] PRESSED_SELECTED_STATE_SET; 1328 /** 1329 * Indicates the view is pressed, selected and its window has the focus. 1330 * 1331 * @see #PRESSED_STATE_SET 1332 * @see #SELECTED_STATE_SET 1333 * @see #WINDOW_FOCUSED_STATE_SET 1334 */ 1335 protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1336 /** 1337 * Indicates the view is pressed and focused. 1338 * 1339 * @see #PRESSED_STATE_SET 1340 * @see #FOCUSED_STATE_SET 1341 */ 1342 protected static final int[] PRESSED_FOCUSED_STATE_SET; 1343 /** 1344 * Indicates the view is pressed, focused and its window has the focus. 1345 * 1346 * @see #PRESSED_STATE_SET 1347 * @see #FOCUSED_STATE_SET 1348 * @see #WINDOW_FOCUSED_STATE_SET 1349 */ 1350 protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1351 /** 1352 * Indicates the view is pressed, focused and selected. 1353 * 1354 * @see #PRESSED_STATE_SET 1355 * @see #SELECTED_STATE_SET 1356 * @see #FOCUSED_STATE_SET 1357 */ 1358 protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET; 1359 /** 1360 * Indicates the view is pressed, focused, selected and its window has the focus. 1361 * 1362 * @see #PRESSED_STATE_SET 1363 * @see #FOCUSED_STATE_SET 1364 * @see #SELECTED_STATE_SET 1365 * @see #WINDOW_FOCUSED_STATE_SET 1366 */ 1367 protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1368 /** 1369 * Indicates the view is pressed and enabled. 1370 * 1371 * @see #PRESSED_STATE_SET 1372 * @see #ENABLED_STATE_SET 1373 */ 1374 protected static final int[] PRESSED_ENABLED_STATE_SET; 1375 /** 1376 * Indicates the view is pressed, enabled and its window has the focus. 1377 * 1378 * @see #PRESSED_STATE_SET 1379 * @see #ENABLED_STATE_SET 1380 * @see #WINDOW_FOCUSED_STATE_SET 1381 */ 1382 protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET; 1383 /** 1384 * Indicates the view is pressed, enabled and selected. 1385 * 1386 * @see #PRESSED_STATE_SET 1387 * @see #ENABLED_STATE_SET 1388 * @see #SELECTED_STATE_SET 1389 */ 1390 protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET; 1391 /** 1392 * Indicates the view is pressed, enabled, selected and its window has the 1393 * focus. 1394 * 1395 * @see #PRESSED_STATE_SET 1396 * @see #ENABLED_STATE_SET 1397 * @see #SELECTED_STATE_SET 1398 * @see #WINDOW_FOCUSED_STATE_SET 1399 */ 1400 protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1401 /** 1402 * Indicates the view is pressed, enabled and focused. 1403 * 1404 * @see #PRESSED_STATE_SET 1405 * @see #ENABLED_STATE_SET 1406 * @see #FOCUSED_STATE_SET 1407 */ 1408 protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET; 1409 /** 1410 * Indicates the view is pressed, enabled, focused and its window has the 1411 * focus. 1412 * 1413 * @see #PRESSED_STATE_SET 1414 * @see #ENABLED_STATE_SET 1415 * @see #FOCUSED_STATE_SET 1416 * @see #WINDOW_FOCUSED_STATE_SET 1417 */ 1418 protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET; 1419 /** 1420 * Indicates the view is pressed, enabled, focused and selected. 1421 * 1422 * @see #PRESSED_STATE_SET 1423 * @see #ENABLED_STATE_SET 1424 * @see #SELECTED_STATE_SET 1425 * @see #FOCUSED_STATE_SET 1426 */ 1427 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET; 1428 /** 1429 * Indicates the view is pressed, enabled, focused, selected and its window 1430 * has the focus. 1431 * 1432 * @see #PRESSED_STATE_SET 1433 * @see #ENABLED_STATE_SET 1434 * @see #SELECTED_STATE_SET 1435 * @see #FOCUSED_STATE_SET 1436 * @see #WINDOW_FOCUSED_STATE_SET 1437 */ 1438 protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET; 1439 1440 /** 1441 * The order here is very important to {@link #getDrawableState()} 1442 */ 1443 private static final int[][] VIEW_STATE_SETS; 1444 1445 static final int VIEW_STATE_WINDOW_FOCUSED = 1; 1446 static final int VIEW_STATE_SELECTED = 1 << 1; 1447 static final int VIEW_STATE_FOCUSED = 1 << 2; 1448 static final int VIEW_STATE_ENABLED = 1 << 3; 1449 static final int VIEW_STATE_PRESSED = 1 << 4; 1450 static final int VIEW_STATE_ACTIVATED = 1 << 5; 1451 static final int VIEW_STATE_ACCELERATED = 1 << 6; 1452 static final int VIEW_STATE_HOVERED = 1 << 7; 1453 static final int VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; 1454 static final int VIEW_STATE_DRAG_HOVERED = 1 << 9; 1455 1456 static final int[] VIEW_STATE_IDS = new int[] { 1457 R.attr.state_window_focused, VIEW_STATE_WINDOW_FOCUSED, 1458 R.attr.state_selected, VIEW_STATE_SELECTED, 1459 R.attr.state_focused, VIEW_STATE_FOCUSED, 1460 R.attr.state_enabled, VIEW_STATE_ENABLED, 1461 R.attr.state_pressed, VIEW_STATE_PRESSED, 1462 R.attr.state_activated, VIEW_STATE_ACTIVATED, 1463 R.attr.state_accelerated, VIEW_STATE_ACCELERATED, 1464 R.attr.state_hovered, VIEW_STATE_HOVERED, 1465 R.attr.state_drag_can_accept, VIEW_STATE_DRAG_CAN_ACCEPT, 1466 R.attr.state_drag_hovered, VIEW_STATE_DRAG_HOVERED 1467 }; 1468 1469 static { 1470 if ((VIEW_STATE_IDS.length/2) != R.styleable.ViewDrawableStates.length) { 1471 throw new IllegalStateException( 1472 "VIEW_STATE_IDs array length does not match ViewDrawableStates style array"); 1473 } 1474 int[] orderedIds = new int[VIEW_STATE_IDS.length]; 1475 for (int i = 0; i < R.styleable.ViewDrawableStates.length; i++) { 1476 int viewState = R.styleable.ViewDrawableStates[i]; 1477 for (int j = 0; j<VIEW_STATE_IDS.length; j += 2) { 1478 if (VIEW_STATE_IDS[j] == viewState) { 1479 orderedIds[i * 2] = viewState; 1480 orderedIds[i * 2 + 1] = VIEW_STATE_IDS[j + 1]; 1481 } 1482 } 1483 } 1484 final int NUM_BITS = VIEW_STATE_IDS.length / 2; 1485 VIEW_STATE_SETS = new int[1 << NUM_BITS][]; 1486 for (int i = 0; i < VIEW_STATE_SETS.length; i++) { 1487 int numBits = Integer.bitCount(i); 1488 int[] set = new int[numBits]; 1489 int pos = 0; 1490 for (int j = 0; j < orderedIds.length; j += 2) { 1491 if ((i & orderedIds[j+1]) != 0) { 1492 set[pos++] = orderedIds[j]; 1493 } 1494 } 1495 VIEW_STATE_SETS[i] = set; 1496 } 1497 1498 EMPTY_STATE_SET = VIEW_STATE_SETS[0]; 1499 WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_WINDOW_FOCUSED]; 1500 SELECTED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_SELECTED]; 1501 SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1502 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED]; 1503 FOCUSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_FOCUSED]; 1504 FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1505 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED]; 1506 FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1507 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED]; 1508 FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1509 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1510 | VIEW_STATE_FOCUSED]; 1511 ENABLED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_ENABLED]; 1512 ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1513 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED]; 1514 ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1515 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED]; 1516 ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1517 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1518 | VIEW_STATE_ENABLED]; 1519 ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1520 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED]; 1521 ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1522 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1523 | VIEW_STATE_ENABLED]; 1524 ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1525 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1526 | VIEW_STATE_ENABLED]; 1527 ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1528 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1529 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED]; 1530 1531 PRESSED_STATE_SET = VIEW_STATE_SETS[VIEW_STATE_PRESSED]; 1532 PRESSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1533 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_PRESSED]; 1534 PRESSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1535 VIEW_STATE_SELECTED | VIEW_STATE_PRESSED]; 1536 PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1537 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1538 | VIEW_STATE_PRESSED]; 1539 PRESSED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1540 VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1541 PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1542 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1543 | VIEW_STATE_PRESSED]; 1544 PRESSED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1545 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1546 | VIEW_STATE_PRESSED]; 1547 PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1548 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1549 | VIEW_STATE_FOCUSED | VIEW_STATE_PRESSED]; 1550 PRESSED_ENABLED_STATE_SET = VIEW_STATE_SETS[ 1551 VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1552 PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1553 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_ENABLED 1554 | VIEW_STATE_PRESSED]; 1555 PRESSED_ENABLED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1556 VIEW_STATE_SELECTED | VIEW_STATE_ENABLED 1557 | VIEW_STATE_PRESSED]; 1558 PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1559 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1560 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1561 PRESSED_ENABLED_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1562 VIEW_STATE_FOCUSED | VIEW_STATE_ENABLED 1563 | VIEW_STATE_PRESSED]; 1564 PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1565 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_FOCUSED 1566 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1567 PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = VIEW_STATE_SETS[ 1568 VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED 1569 | VIEW_STATE_ENABLED | VIEW_STATE_PRESSED]; 1570 PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = VIEW_STATE_SETS[ 1571 VIEW_STATE_WINDOW_FOCUSED | VIEW_STATE_SELECTED 1572 | VIEW_STATE_FOCUSED| VIEW_STATE_ENABLED 1573 | VIEW_STATE_PRESSED]; 1574 } 1575 1576 /** 1577 * Accessibility event types that are dispatched for text population. 1578 */ 1579 private static final int POPULATING_ACCESSIBILITY_EVENT_TYPES = 1580 AccessibilityEvent.TYPE_VIEW_CLICKED 1581 | AccessibilityEvent.TYPE_VIEW_LONG_CLICKED 1582 | AccessibilityEvent.TYPE_VIEW_SELECTED 1583 | AccessibilityEvent.TYPE_VIEW_FOCUSED 1584 | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED 1585 | AccessibilityEvent.TYPE_VIEW_HOVER_ENTER 1586 | AccessibilityEvent.TYPE_VIEW_HOVER_EXIT 1587 | AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED 1588 | AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED 1589 | AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED 1590 | AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY; 1591 1592 /** 1593 * Temporary Rect currently for use in setBackground(). This will probably 1594 * be extended in the future to hold our own class with more than just 1595 * a Rect. :) 1596 */ 1597 static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>(); 1598 1599 /** 1600 * Map used to store views' tags. 1601 */ 1602 private SparseArray<Object> mKeyedTags; 1603 1604 /** 1605 * The next available accessibility id. 1606 */ 1607 private static int sNextAccessibilityViewId; 1608 1609 /** 1610 * The animation currently associated with this view. 1611 * @hide 1612 */ 1613 protected Animation mCurrentAnimation = null; 1614 1615 /** 1616 * Width as measured during measure pass. 1617 * {@hide} 1618 */ 1619 @ViewDebug.ExportedProperty(category = "measurement") 1620 int mMeasuredWidth; 1621 1622 /** 1623 * Height as measured during measure pass. 1624 * {@hide} 1625 */ 1626 @ViewDebug.ExportedProperty(category = "measurement") 1627 int mMeasuredHeight; 1628 1629 /** 1630 * Flag to indicate that this view was marked INVALIDATED, or had its display list 1631 * invalidated, prior to the current drawing iteration. If true, the view must re-draw 1632 * its display list. This flag, used only when hw accelerated, allows us to clear the 1633 * flag while retaining this information until it's needed (at getDisplayList() time and 1634 * in drawChild(), when we decide to draw a view's children's display lists into our own). 1635 * 1636 * {@hide} 1637 */ 1638 boolean mRecreateDisplayList = false; 1639 1640 /** 1641 * The view's identifier. 1642 * {@hide} 1643 * 1644 * @see #setId(int) 1645 * @see #getId() 1646 */ 1647 @ViewDebug.ExportedProperty(resolveId = true) 1648 int mID = NO_ID; 1649 1650 /** 1651 * The stable ID of this view for accessibility purposes. 1652 */ 1653 int mAccessibilityViewId = NO_ID; 1654 1655 private int mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 1656 1657 SendViewStateChangedAccessibilityEvent mSendViewStateChangedAccessibilityEvent; 1658 1659 /** 1660 * The view's tag. 1661 * {@hide} 1662 * 1663 * @see #setTag(Object) 1664 * @see #getTag() 1665 */ 1666 protected Object mTag = null; 1667 1668 // for mPrivateFlags: 1669 /** {@hide} */ 1670 static final int PFLAG_WANTS_FOCUS = 0x00000001; 1671 /** {@hide} */ 1672 static final int PFLAG_FOCUSED = 0x00000002; 1673 /** {@hide} */ 1674 static final int PFLAG_SELECTED = 0x00000004; 1675 /** {@hide} */ 1676 static final int PFLAG_IS_ROOT_NAMESPACE = 0x00000008; 1677 /** {@hide} */ 1678 static final int PFLAG_HAS_BOUNDS = 0x00000010; 1679 /** {@hide} */ 1680 static final int PFLAG_DRAWN = 0x00000020; 1681 /** 1682 * When this flag is set, this view is running an animation on behalf of its 1683 * children and should therefore not cancel invalidate requests, even if they 1684 * lie outside of this view's bounds. 1685 * 1686 * {@hide} 1687 */ 1688 static final int PFLAG_DRAW_ANIMATION = 0x00000040; 1689 /** {@hide} */ 1690 static final int PFLAG_SKIP_DRAW = 0x00000080; 1691 /** {@hide} */ 1692 static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; 1693 /** {@hide} */ 1694 static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; 1695 /** {@hide} */ 1696 static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; 1697 /** {@hide} */ 1698 static final int PFLAG_MEASURED_DIMENSION_SET = 0x00000800; 1699 /** {@hide} */ 1700 static final int PFLAG_FORCE_LAYOUT = 0x00001000; 1701 /** {@hide} */ 1702 static final int PFLAG_LAYOUT_REQUIRED = 0x00002000; 1703 1704 private static final int PFLAG_PRESSED = 0x00004000; 1705 1706 /** {@hide} */ 1707 static final int PFLAG_DRAWING_CACHE_VALID = 0x00008000; 1708 /** 1709 * Flag used to indicate that this view should be drawn once more (and only once 1710 * more) after its animation has completed. 1711 * {@hide} 1712 */ 1713 static final int PFLAG_ANIMATION_STARTED = 0x00010000; 1714 1715 private static final int PFLAG_SAVE_STATE_CALLED = 0x00020000; 1716 1717 /** 1718 * Indicates that the View returned true when onSetAlpha() was called and that 1719 * the alpha must be restored. 1720 * {@hide} 1721 */ 1722 static final int PFLAG_ALPHA_SET = 0x00040000; 1723 1724 /** 1725 * Set by {@link #setScrollContainer(boolean)}. 1726 */ 1727 static final int PFLAG_SCROLL_CONTAINER = 0x00080000; 1728 1729 /** 1730 * Set by {@link #setScrollContainer(boolean)}. 1731 */ 1732 static final int PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; 1733 1734 /** 1735 * View flag indicating whether this view was invalidated (fully or partially.) 1736 * 1737 * @hide 1738 */ 1739 static final int PFLAG_DIRTY = 0x00200000; 1740 1741 /** 1742 * View flag indicating whether this view was invalidated by an opaque 1743 * invalidate request. 1744 * 1745 * @hide 1746 */ 1747 static final int PFLAG_DIRTY_OPAQUE = 0x00400000; 1748 1749 /** 1750 * Mask for {@link #PFLAG_DIRTY} and {@link #PFLAG_DIRTY_OPAQUE}. 1751 * 1752 * @hide 1753 */ 1754 static final int PFLAG_DIRTY_MASK = 0x00600000; 1755 1756 /** 1757 * Indicates whether the background is opaque. 1758 * 1759 * @hide 1760 */ 1761 static final int PFLAG_OPAQUE_BACKGROUND = 0x00800000; 1762 1763 /** 1764 * Indicates whether the scrollbars are opaque. 1765 * 1766 * @hide 1767 */ 1768 static final int PFLAG_OPAQUE_SCROLLBARS = 0x01000000; 1769 1770 /** 1771 * Indicates whether the view is opaque. 1772 * 1773 * @hide 1774 */ 1775 static final int PFLAG_OPAQUE_MASK = 0x01800000; 1776 1777 /** 1778 * Indicates a prepressed state; 1779 * the short time between ACTION_DOWN and recognizing 1780 * a 'real' press. Prepressed is used to recognize quick taps 1781 * even when they are shorter than ViewConfiguration.getTapTimeout(). 1782 * 1783 * @hide 1784 */ 1785 private static final int PFLAG_PREPRESSED = 0x02000000; 1786 1787 /** 1788 * Indicates whether the view is temporarily detached. 1789 * 1790 * @hide 1791 */ 1792 static final int PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; 1793 1794 /** 1795 * Indicates that we should awaken scroll bars once attached 1796 * 1797 * @hide 1798 */ 1799 private static final int PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; 1800 1801 /** 1802 * Indicates that the view has received HOVER_ENTER. Cleared on HOVER_EXIT. 1803 * @hide 1804 */ 1805 private static final int PFLAG_HOVERED = 0x10000000; 1806 1807 /** 1808 * no longer needed, should be reused 1809 */ 1810 private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; 1811 1812 /** {@hide} */ 1813 static final int PFLAG_ACTIVATED = 0x40000000; 1814 1815 /** 1816 * Indicates that this view was specifically invalidated, not just dirtied because some 1817 * child view was invalidated. The flag is used to determine when we need to recreate 1818 * a view's display list (as opposed to just returning a reference to its existing 1819 * display list). 1820 * 1821 * @hide 1822 */ 1823 static final int PFLAG_INVALIDATED = 0x80000000; 1824 1825 /** 1826 * Masks for mPrivateFlags2, as generated by dumpFlags(): 1827 * 1828 * |-------|-------|-------|-------| 1829 * 1 PFLAG2_DRAG_CAN_ACCEPT 1830 * 1 PFLAG2_DRAG_HOVERED 1831 * 11 PFLAG2_LAYOUT_DIRECTION_MASK 1832 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL 1833 * 1 PFLAG2_LAYOUT_DIRECTION_RESOLVED 1834 * 11 PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK 1835 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[1] 1836 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[2] 1837 * 11 PFLAG2_TEXT_DIRECTION_FLAGS[3] 1838 * 1 PFLAG2_TEXT_DIRECTION_FLAGS[4] 1839 * 1 1 PFLAG2_TEXT_DIRECTION_FLAGS[5] 1840 * 111 PFLAG2_TEXT_DIRECTION_MASK 1841 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED 1842 * 1 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT 1843 * 111 PFLAG2_TEXT_DIRECTION_RESOLVED_MASK 1844 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[1] 1845 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[2] 1846 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[3] 1847 * 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[4] 1848 * 1 1 PFLAG2_TEXT_ALIGNMENT_FLAGS[5] 1849 * 11 PFLAG2_TEXT_ALIGNMENT_FLAGS[6] 1850 * 111 PFLAG2_TEXT_ALIGNMENT_MASK 1851 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED 1852 * 1 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT 1853 * 111 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK 1854 * 111 PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK 1855 * 11 PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK 1856 * 1 PFLAG2_ACCESSIBILITY_FOCUSED 1857 * 1 PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED 1858 * 1 PFLAG2_VIEW_QUICK_REJECTED 1859 * 1 PFLAG2_PADDING_RESOLVED 1860 * 1 PFLAG2_DRAWABLE_RESOLVED 1861 * 1 PFLAG2_HAS_TRANSIENT_STATE 1862 * |-------|-------|-------|-------| 1863 */ 1864 1865 /** 1866 * Indicates that this view has reported that it can accept the current drag's content. 1867 * Cleared when the drag operation concludes. 1868 * @hide 1869 */ 1870 static final int PFLAG2_DRAG_CAN_ACCEPT = 0x00000001; 1871 1872 /** 1873 * Indicates that this view is currently directly under the drag location in a 1874 * drag-and-drop operation involving content that it can accept. Cleared when 1875 * the drag exits the view, or when the drag operation concludes. 1876 * @hide 1877 */ 1878 static final int PFLAG2_DRAG_HOVERED = 0x00000002; 1879 1880 /** @hide */ 1881 @IntDef({ 1882 LAYOUT_DIRECTION_LTR, 1883 LAYOUT_DIRECTION_RTL, 1884 LAYOUT_DIRECTION_INHERIT, 1885 LAYOUT_DIRECTION_LOCALE 1886 }) 1887 @Retention(RetentionPolicy.SOURCE) 1888 // Not called LayoutDirection to avoid conflict with android.util.LayoutDirection 1889 public @interface LayoutDir {} 1890 1891 /** @hide */ 1892 @IntDef({ 1893 LAYOUT_DIRECTION_LTR, 1894 LAYOUT_DIRECTION_RTL 1895 }) 1896 @Retention(RetentionPolicy.SOURCE) 1897 public @interface ResolvedLayoutDir {} 1898 1899 /** 1900 * Horizontal layout direction of this view is from Left to Right. 1901 * Use with {@link #setLayoutDirection}. 1902 */ 1903 public static final int LAYOUT_DIRECTION_LTR = LayoutDirection.LTR; 1904 1905 /** 1906 * Horizontal layout direction of this view is from Right to Left. 1907 * Use with {@link #setLayoutDirection}. 1908 */ 1909 public static final int LAYOUT_DIRECTION_RTL = LayoutDirection.RTL; 1910 1911 /** 1912 * Horizontal layout direction of this view is inherited from its parent. 1913 * Use with {@link #setLayoutDirection}. 1914 */ 1915 public static final int LAYOUT_DIRECTION_INHERIT = LayoutDirection.INHERIT; 1916 1917 /** 1918 * Horizontal layout direction of this view is from deduced from the default language 1919 * script for the locale. Use with {@link #setLayoutDirection}. 1920 */ 1921 public static final int LAYOUT_DIRECTION_LOCALE = LayoutDirection.LOCALE; 1922 1923 /** 1924 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 1925 * @hide 1926 */ 1927 static final int PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT = 2; 1928 1929 /** 1930 * Mask for use with private flags indicating bits used for horizontal layout direction. 1931 * @hide 1932 */ 1933 static final int PFLAG2_LAYOUT_DIRECTION_MASK = 0x00000003 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1934 1935 /** 1936 * Indicates whether the view horizontal layout direction has been resolved and drawn to the 1937 * right-to-left direction. 1938 * @hide 1939 */ 1940 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL = 4 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1941 1942 /** 1943 * Indicates whether the view horizontal layout direction has been resolved. 1944 * @hide 1945 */ 1946 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED = 8 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1947 1948 /** 1949 * Mask for use with private flags indicating bits used for resolved horizontal layout direction. 1950 * @hide 1951 */ 1952 static final int PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK = 0x0000000C 1953 << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 1954 1955 /* 1956 * Array of horizontal layout direction flags for mapping attribute "layoutDirection" to correct 1957 * flag value. 1958 * @hide 1959 */ 1960 private static final int[] LAYOUT_DIRECTION_FLAGS = { 1961 LAYOUT_DIRECTION_LTR, 1962 LAYOUT_DIRECTION_RTL, 1963 LAYOUT_DIRECTION_INHERIT, 1964 LAYOUT_DIRECTION_LOCALE 1965 }; 1966 1967 /** 1968 * Default horizontal layout direction. 1969 */ 1970 private static final int LAYOUT_DIRECTION_DEFAULT = LAYOUT_DIRECTION_INHERIT; 1971 1972 /** 1973 * Default horizontal layout direction. 1974 * @hide 1975 */ 1976 static final int LAYOUT_DIRECTION_RESOLVED_DEFAULT = LAYOUT_DIRECTION_LTR; 1977 1978 /** 1979 * Text direction is inherited thru {@link ViewGroup} 1980 */ 1981 public static final int TEXT_DIRECTION_INHERIT = 0; 1982 1983 /** 1984 * Text direction is using "first strong algorithm". The first strong directional character 1985 * determines the paragraph direction. If there is no strong directional character, the 1986 * paragraph direction is the view's resolved layout direction. 1987 */ 1988 public static final int TEXT_DIRECTION_FIRST_STRONG = 1; 1989 1990 /** 1991 * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains 1992 * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. 1993 * If there are neither, the paragraph direction is the view's resolved layout direction. 1994 */ 1995 public static final int TEXT_DIRECTION_ANY_RTL = 2; 1996 1997 /** 1998 * Text direction is forced to LTR. 1999 */ 2000 public static final int TEXT_DIRECTION_LTR = 3; 2001 2002 /** 2003 * Text direction is forced to RTL. 2004 */ 2005 public static final int TEXT_DIRECTION_RTL = 4; 2006 2007 /** 2008 * Text direction is coming from the system Locale. 2009 */ 2010 public static final int TEXT_DIRECTION_LOCALE = 5; 2011 2012 /** 2013 * Default text direction is inherited 2014 */ 2015 private static final int TEXT_DIRECTION_DEFAULT = TEXT_DIRECTION_INHERIT; 2016 2017 /** 2018 * Default resolved text direction 2019 * @hide 2020 */ 2021 static final int TEXT_DIRECTION_RESOLVED_DEFAULT = TEXT_DIRECTION_FIRST_STRONG; 2022 2023 /** 2024 * Bit shift to get the horizontal layout direction. (bits after LAYOUT_DIRECTION_RESOLVED) 2025 * @hide 2026 */ 2027 static final int PFLAG2_TEXT_DIRECTION_MASK_SHIFT = 6; 2028 2029 /** 2030 * Mask for use with private flags indicating bits used for text direction. 2031 * @hide 2032 */ 2033 static final int PFLAG2_TEXT_DIRECTION_MASK = 0x00000007 2034 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2035 2036 /** 2037 * Array of text direction flags for mapping attribute "textDirection" to correct 2038 * flag value. 2039 * @hide 2040 */ 2041 private static final int[] PFLAG2_TEXT_DIRECTION_FLAGS = { 2042 TEXT_DIRECTION_INHERIT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2043 TEXT_DIRECTION_FIRST_STRONG << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2044 TEXT_DIRECTION_ANY_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2045 TEXT_DIRECTION_LTR << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2046 TEXT_DIRECTION_RTL << PFLAG2_TEXT_DIRECTION_MASK_SHIFT, 2047 TEXT_DIRECTION_LOCALE << PFLAG2_TEXT_DIRECTION_MASK_SHIFT 2048 }; 2049 2050 /** 2051 * Indicates whether the view text direction has been resolved. 2052 * @hide 2053 */ 2054 static final int PFLAG2_TEXT_DIRECTION_RESOLVED = 0x00000008 2055 << PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 2056 2057 /** 2058 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2059 * @hide 2060 */ 2061 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT = 10; 2062 2063 /** 2064 * Mask for use with private flags indicating bits used for resolved text direction. 2065 * @hide 2066 */ 2067 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_MASK = 0x00000007 2068 << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2069 2070 /** 2071 * Indicates whether the view text direction has been resolved to the "first strong" heuristic. 2072 * @hide 2073 */ 2074 static final int PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT = 2075 TEXT_DIRECTION_RESOLVED_DEFAULT << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 2076 2077 /** @hide */ 2078 @IntDef({ 2079 TEXT_ALIGNMENT_INHERIT, 2080 TEXT_ALIGNMENT_GRAVITY, 2081 TEXT_ALIGNMENT_CENTER, 2082 TEXT_ALIGNMENT_TEXT_START, 2083 TEXT_ALIGNMENT_TEXT_END, 2084 TEXT_ALIGNMENT_VIEW_START, 2085 TEXT_ALIGNMENT_VIEW_END 2086 }) 2087 @Retention(RetentionPolicy.SOURCE) 2088 public @interface TextAlignment {} 2089 2090 /** 2091 * Default text alignment. The text alignment of this View is inherited from its parent. 2092 * Use with {@link #setTextAlignment(int)} 2093 */ 2094 public static final int TEXT_ALIGNMENT_INHERIT = 0; 2095 2096 /** 2097 * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, 2098 * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. 2099 * 2100 * Use with {@link #setTextAlignment(int)} 2101 */ 2102 public static final int TEXT_ALIGNMENT_GRAVITY = 1; 2103 2104 /** 2105 * Align to the start of the paragraph, e.g. ALIGN_NORMAL. 2106 * 2107 * Use with {@link #setTextAlignment(int)} 2108 */ 2109 public static final int TEXT_ALIGNMENT_TEXT_START = 2; 2110 2111 /** 2112 * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. 2113 * 2114 * Use with {@link #setTextAlignment(int)} 2115 */ 2116 public static final int TEXT_ALIGNMENT_TEXT_END = 3; 2117 2118 /** 2119 * Center the paragraph, e.g. ALIGN_CENTER. 2120 * 2121 * Use with {@link #setTextAlignment(int)} 2122 */ 2123 public static final int TEXT_ALIGNMENT_CENTER = 4; 2124 2125 /** 2126 * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved 2127 * layoutDirection is LTR, and ALIGN_RIGHT otherwise. 2128 * 2129 * Use with {@link #setTextAlignment(int)} 2130 */ 2131 public static final int TEXT_ALIGNMENT_VIEW_START = 5; 2132 2133 /** 2134 * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved 2135 * layoutDirection is LTR, and ALIGN_LEFT otherwise. 2136 * 2137 * Use with {@link #setTextAlignment(int)} 2138 */ 2139 public static final int TEXT_ALIGNMENT_VIEW_END = 6; 2140 2141 /** 2142 * Default text alignment is inherited 2143 */ 2144 private static final int TEXT_ALIGNMENT_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2145 2146 /** 2147 * Default resolved text alignment 2148 * @hide 2149 */ 2150 static final int TEXT_ALIGNMENT_RESOLVED_DEFAULT = TEXT_ALIGNMENT_GRAVITY; 2151 2152 /** 2153 * Bit shift to get the horizontal layout direction. (bits after DRAG_HOVERED) 2154 * @hide 2155 */ 2156 static final int PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT = 13; 2157 2158 /** 2159 * Mask for use with private flags indicating bits used for text alignment. 2160 * @hide 2161 */ 2162 static final int PFLAG2_TEXT_ALIGNMENT_MASK = 0x00000007 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2163 2164 /** 2165 * Array of text direction flags for mapping attribute "textAlignment" to correct 2166 * flag value. 2167 * @hide 2168 */ 2169 private static final int[] PFLAG2_TEXT_ALIGNMENT_FLAGS = { 2170 TEXT_ALIGNMENT_INHERIT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2171 TEXT_ALIGNMENT_GRAVITY << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2172 TEXT_ALIGNMENT_TEXT_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2173 TEXT_ALIGNMENT_TEXT_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2174 TEXT_ALIGNMENT_CENTER << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2175 TEXT_ALIGNMENT_VIEW_START << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT, 2176 TEXT_ALIGNMENT_VIEW_END << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT 2177 }; 2178 2179 /** 2180 * Indicates whether the view text alignment has been resolved. 2181 * @hide 2182 */ 2183 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED = 0x00000008 << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 2184 2185 /** 2186 * Bit shift to get the resolved text alignment. 2187 * @hide 2188 */ 2189 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT = 17; 2190 2191 /** 2192 * Mask for use with private flags indicating bits used for text alignment. 2193 * @hide 2194 */ 2195 static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK = 0x00000007 2196 << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2197 2198 /** 2199 * Indicates whether if the view text alignment has been resolved to gravity 2200 */ 2201 private static final int PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT = 2202 TEXT_ALIGNMENT_RESOLVED_DEFAULT << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 2203 2204 // Accessiblity constants for mPrivateFlags2 2205 2206 /** 2207 * Shift for the bits in {@link #mPrivateFlags2} related to the 2208 * "importantForAccessibility" attribute. 2209 */ 2210 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT = 20; 2211 2212 /** 2213 * Automatically determine whether a view is important for accessibility. 2214 */ 2215 public static final int IMPORTANT_FOR_ACCESSIBILITY_AUTO = 0x00000000; 2216 2217 /** 2218 * The view is important for accessibility. 2219 */ 2220 public static final int IMPORTANT_FOR_ACCESSIBILITY_YES = 0x00000001; 2221 2222 /** 2223 * The view is not important for accessibility. 2224 */ 2225 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO = 0x00000002; 2226 2227 /** 2228 * The view is not important for accessibility, nor are any of its 2229 * descendant views. 2230 */ 2231 public static final int IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS = 0x00000004; 2232 2233 /** 2234 * The default whether the view is important for accessibility. 2235 */ 2236 static final int IMPORTANT_FOR_ACCESSIBILITY_DEFAULT = IMPORTANT_FOR_ACCESSIBILITY_AUTO; 2237 2238 /** 2239 * Mask for obtainig the bits which specify how to determine 2240 * whether a view is important for accessibility. 2241 */ 2242 static final int PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK = (IMPORTANT_FOR_ACCESSIBILITY_AUTO 2243 | IMPORTANT_FOR_ACCESSIBILITY_YES | IMPORTANT_FOR_ACCESSIBILITY_NO 2244 | IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) 2245 << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 2246 2247 /** 2248 * Shift for the bits in {@link #mPrivateFlags2} related to the 2249 * "accessibilityLiveRegion" attribute. 2250 */ 2251 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT = 23; 2252 2253 /** 2254 * Live region mode specifying that accessibility services should not 2255 * automatically announce changes to this view. This is the default live 2256 * region mode for most views. 2257 * <p> 2258 * Use with {@link #setAccessibilityLiveRegion(int)}. 2259 */ 2260 public static final int ACCESSIBILITY_LIVE_REGION_NONE = 0x00000000; 2261 2262 /** 2263 * Live region mode specifying that accessibility services should announce 2264 * changes to this view. 2265 * <p> 2266 * Use with {@link #setAccessibilityLiveRegion(int)}. 2267 */ 2268 public static final int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001; 2269 2270 /** 2271 * Live region mode specifying that accessibility services should interrupt 2272 * ongoing speech to immediately announce changes to this view. 2273 * <p> 2274 * Use with {@link #setAccessibilityLiveRegion(int)}. 2275 */ 2276 public static final int ACCESSIBILITY_LIVE_REGION_ASSERTIVE = 0x00000002; 2277 2278 /** 2279 * The default whether the view is important for accessibility. 2280 */ 2281 static final int ACCESSIBILITY_LIVE_REGION_DEFAULT = ACCESSIBILITY_LIVE_REGION_NONE; 2282 2283 /** 2284 * Mask for obtaining the bits which specify a view's accessibility live 2285 * region mode. 2286 */ 2287 static final int PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK = (ACCESSIBILITY_LIVE_REGION_NONE 2288 | ACCESSIBILITY_LIVE_REGION_POLITE | ACCESSIBILITY_LIVE_REGION_ASSERTIVE) 2289 << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 2290 2291 /** 2292 * Flag indicating whether a view has accessibility focus. 2293 */ 2294 static final int PFLAG2_ACCESSIBILITY_FOCUSED = 0x04000000; 2295 2296 /** 2297 * Flag whether the accessibility state of the subtree rooted at this view changed. 2298 */ 2299 static final int PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED = 0x08000000; 2300 2301 /** 2302 * Flag indicating whether a view failed the quickReject() check in draw(). This condition 2303 * is used to check whether later changes to the view's transform should invalidate the 2304 * view to force the quickReject test to run again. 2305 */ 2306 static final int PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; 2307 2308 /** 2309 * Flag indicating that start/end padding has been resolved into left/right padding 2310 * for use in measurement, layout, drawing, etc. This is set by {@link #resolvePadding()} 2311 * and checked by {@link #measure(int, int)} to determine if padding needs to be resolved 2312 * during measurement. In some special cases this is required such as when an adapter-based 2313 * view measures prospective children without attaching them to a window. 2314 */ 2315 static final int PFLAG2_PADDING_RESOLVED = 0x20000000; 2316 2317 /** 2318 * Flag indicating that the start/end drawables has been resolved into left/right ones. 2319 */ 2320 static final int PFLAG2_DRAWABLE_RESOLVED = 0x40000000; 2321 2322 /** 2323 * Indicates that the view is tracking some sort of transient state 2324 * that the app should not need to be aware of, but that the framework 2325 * should take special care to preserve. 2326 */ 2327 static final int PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; 2328 2329 /** 2330 * Group of bits indicating that RTL properties resolution is done. 2331 */ 2332 static final int ALL_RTL_PROPERTIES_RESOLVED = PFLAG2_LAYOUT_DIRECTION_RESOLVED | 2333 PFLAG2_TEXT_DIRECTION_RESOLVED | 2334 PFLAG2_TEXT_ALIGNMENT_RESOLVED | 2335 PFLAG2_PADDING_RESOLVED | 2336 PFLAG2_DRAWABLE_RESOLVED; 2337 2338 // There are a couple of flags left in mPrivateFlags2 2339 2340 /* End of masks for mPrivateFlags2 */ 2341 2342 /** 2343 * Masks for mPrivateFlags3, as generated by dumpFlags(): 2344 * 2345 * |-------|-------|-------|-------| 2346 * 1 PFLAG3_VIEW_IS_ANIMATING_TRANSFORM 2347 * 1 PFLAG3_VIEW_IS_ANIMATING_ALPHA 2348 * 1 PFLAG3_IS_LAID_OUT 2349 * 1 PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT 2350 * 1 PFLAG3_CALLED_SUPER 2351 * |-------|-------|-------|-------| 2352 */ 2353 2354 /** 2355 * Flag indicating that view has a transform animation set on it. This is used to track whether 2356 * an animation is cleared between successive frames, in order to tell the associated 2357 * DisplayList to clear its animation matrix. 2358 */ 2359 static final int PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; 2360 2361 /** 2362 * Flag indicating that view has an alpha animation set on it. This is used to track whether an 2363 * animation is cleared between successive frames, in order to tell the associated 2364 * DisplayList to restore its alpha value. 2365 */ 2366 static final int PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; 2367 2368 /** 2369 * Flag indicating that the view has been through at least one layout since it 2370 * was last attached to a window. 2371 */ 2372 static final int PFLAG3_IS_LAID_OUT = 0x4; 2373 2374 /** 2375 * Flag indicating that a call to measure() was skipped and should be done 2376 * instead when layout() is invoked. 2377 */ 2378 static final int PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; 2379 2380 /** 2381 * Flag indicating that an overridden method correctly called down to 2382 * the superclass implementation as required by the API spec. 2383 */ 2384 static final int PFLAG3_CALLED_SUPER = 0x10; 2385 2386 /** 2387 * Flag indicating that we're in the process of applying window insets. 2388 */ 2389 static final int PFLAG3_APPLYING_INSETS = 0x20; 2390 2391 /** 2392 * Flag indicating that we're in the process of fitting system windows using the old method. 2393 */ 2394 static final int PFLAG3_FITTING_SYSTEM_WINDOWS = 0x40; 2395 2396 /** 2397 * Flag indicating that nested scrolling is enabled for this view. 2398 * The view will optionally cooperate with views up its parent chain to allow for 2399 * integrated nested scrolling along the same axis. 2400 */ 2401 static final int PFLAG3_NESTED_SCROLLING_ENABLED = 0x80; 2402 2403 /** 2404 * Flag indicating that outline was invalidated and should be rebuilt the next time 2405 * the DisplayList is updated. 2406 */ 2407 static final int PFLAG3_OUTLINE_INVALID = 0x100; 2408 2409 /* End of masks for mPrivateFlags3 */ 2410 2411 static final int DRAG_MASK = PFLAG2_DRAG_CAN_ACCEPT | PFLAG2_DRAG_HOVERED; 2412 2413 /** 2414 * Always allow a user to over-scroll this view, provided it is a 2415 * view that can scroll. 2416 * 2417 * @see #getOverScrollMode() 2418 * @see #setOverScrollMode(int) 2419 */ 2420 public static final int OVER_SCROLL_ALWAYS = 0; 2421 2422 /** 2423 * Allow a user to over-scroll this view only if the content is large 2424 * enough to meaningfully scroll, provided it is a view that can scroll. 2425 * 2426 * @see #getOverScrollMode() 2427 * @see #setOverScrollMode(int) 2428 */ 2429 public static final int OVER_SCROLL_IF_CONTENT_SCROLLS = 1; 2430 2431 /** 2432 * Never allow a user to over-scroll this view. 2433 * 2434 * @see #getOverScrollMode() 2435 * @see #setOverScrollMode(int) 2436 */ 2437 public static final int OVER_SCROLL_NEVER = 2; 2438 2439 /** 2440 * Special constant for {@link #setSystemUiVisibility(int)}: View has 2441 * requested the system UI (status bar) to be visible (the default). 2442 * 2443 * @see #setSystemUiVisibility(int) 2444 */ 2445 public static final int SYSTEM_UI_FLAG_VISIBLE = 0; 2446 2447 /** 2448 * Flag for {@link #setSystemUiVisibility(int)}: View has requested the 2449 * system UI to enter an unobtrusive "low profile" mode. 2450 * 2451 * <p>This is for use in games, book readers, video players, or any other 2452 * "immersive" application where the usual system chrome is deemed too distracting. 2453 * 2454 * <p>In low profile mode, the status bar and/or navigation icons may dim. 2455 * 2456 * @see #setSystemUiVisibility(int) 2457 */ 2458 public static final int SYSTEM_UI_FLAG_LOW_PROFILE = 0x00000001; 2459 2460 /** 2461 * Flag for {@link #setSystemUiVisibility(int)}: View has requested that the 2462 * system navigation be temporarily hidden. 2463 * 2464 * <p>This is an even less obtrusive state than that called for by 2465 * {@link #SYSTEM_UI_FLAG_LOW_PROFILE}; on devices that draw essential navigation controls 2466 * (Home, Back, and the like) on screen, <code>SYSTEM_UI_FLAG_HIDE_NAVIGATION</code> will cause 2467 * those to disappear. This is useful (in conjunction with the 2468 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN FLAG_FULLSCREEN} and 2469 * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN FLAG_LAYOUT_IN_SCREEN} 2470 * window flags) for displaying content using every last pixel on the display. 2471 * 2472 * <p>There is a limitation: because navigation controls are so important, the least user 2473 * interaction will cause them to reappear immediately. When this happens, both 2474 * this flag and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be cleared automatically, 2475 * so that both elements reappear at the same time. 2476 * 2477 * @see #setSystemUiVisibility(int) 2478 */ 2479 public static final int SYSTEM_UI_FLAG_HIDE_NAVIGATION = 0x00000002; 2480 2481 /** 2482 * Flag for {@link #setSystemUiVisibility(int)}: View has requested to go 2483 * into the normal fullscreen mode so that its content can take over the screen 2484 * while still allowing the user to interact with the application. 2485 * 2486 * <p>This has the same visual effect as 2487 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN 2488 * WindowManager.LayoutParams.FLAG_FULLSCREEN}, 2489 * meaning that non-critical screen decorations (such as the status bar) will be 2490 * hidden while the user is in the View's window, focusing the experience on 2491 * that content. Unlike the window flag, if you are using ActionBar in 2492 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2493 * Window.FEATURE_ACTION_BAR_OVERLAY}, then enabling this flag will also 2494 * hide the action bar. 2495 * 2496 * <p>This approach to going fullscreen is best used over the window flag when 2497 * it is a transient state -- that is, the application does this at certain 2498 * points in its user interaction where it wants to allow the user to focus 2499 * on content, but not as a continuous state. For situations where the application 2500 * would like to simply stay full screen the entire time (such as a game that 2501 * wants to take over the screen), the 2502 * {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN window flag} 2503 * is usually a better approach. The state set here will be removed by the system 2504 * in various situations (such as the user moving to another application) like 2505 * the other system UI states. 2506 * 2507 * <p>When using this flag, the application should provide some easy facility 2508 * for the user to go out of it. A common example would be in an e-book 2509 * reader, where tapping on the screen brings back whatever screen and UI 2510 * decorations that had been hidden while the user was immersed in reading 2511 * the book. 2512 * 2513 * @see #setSystemUiVisibility(int) 2514 */ 2515 public static final int SYSTEM_UI_FLAG_FULLSCREEN = 0x00000004; 2516 2517 /** 2518 * Flag for {@link #setSystemUiVisibility(int)}: When using other layout 2519 * flags, we would like a stable view of the content insets given to 2520 * {@link #fitSystemWindows(Rect)}. This means that the insets seen there 2521 * will always represent the worst case that the application can expect 2522 * as a continuous state. In the stock Android UI this is the space for 2523 * the system bar, nav bar, and status bar, but not more transient elements 2524 * such as an input method. 2525 * 2526 * The stable layout your UI sees is based on the system UI modes you can 2527 * switch to. That is, if you specify {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 2528 * then you will get a stable layout for changes of the 2529 * {@link #SYSTEM_UI_FLAG_FULLSCREEN} mode; if you specify 2530 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} and 2531 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, then you can transition 2532 * to {@link #SYSTEM_UI_FLAG_FULLSCREEN} and {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} 2533 * with a stable layout. (Note that you should avoid using 2534 * {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} by itself.) 2535 * 2536 * If you have set the window flag {@link WindowManager.LayoutParams#FLAG_FULLSCREEN} 2537 * to hide the status bar (instead of using {@link #SYSTEM_UI_FLAG_FULLSCREEN}), 2538 * then a hidden status bar will be considered a "stable" state for purposes 2539 * here. This allows your UI to continually hide the status bar, while still 2540 * using the system UI flags to hide the action bar while still retaining 2541 * a stable layout. Note that changing the window fullscreen flag will never 2542 * provide a stable layout for a clean transition. 2543 * 2544 * <p>If you are using ActionBar in 2545 * overlay mode with {@link Window#FEATURE_ACTION_BAR_OVERLAY 2546 * Window.FEATURE_ACTION_BAR_OVERLAY}, this flag will also impact the 2547 * insets it adds to those given to the application. 2548 */ 2549 public static final int SYSTEM_UI_FLAG_LAYOUT_STABLE = 0x00000100; 2550 2551 /** 2552 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2553 * to be layed out as if it has requested 2554 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, even if it currently hasn't. This 2555 * allows it to avoid artifacts when switching in and out of that mode, at 2556 * the expense that some of its user interface may be covered by screen 2557 * decorations when they are shown. You can perform layout of your inner 2558 * UI elements to account for the navigation system UI through the 2559 * {@link #fitSystemWindows(Rect)} method. 2560 */ 2561 public static final int SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION = 0x00000200; 2562 2563 /** 2564 * Flag for {@link #setSystemUiVisibility(int)}: View would like its window 2565 * to be layed out as if it has requested 2566 * {@link #SYSTEM_UI_FLAG_FULLSCREEN}, even if it currently hasn't. This 2567 * allows it to avoid artifacts when switching in and out of that mode, at 2568 * the expense that some of its user interface may be covered by screen 2569 * decorations when they are shown. You can perform layout of your inner 2570 * UI elements to account for non-fullscreen system UI through the 2571 * {@link #fitSystemWindows(Rect)} method. 2572 */ 2573 public static final int SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN = 0x00000400; 2574 2575 /** 2576 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2577 * hiding the navigation bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. If this flag is 2578 * not set, {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any 2579 * user interaction. 2580 * <p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only 2581 * has an effect when used in combination with that flag.</p> 2582 */ 2583 public static final int SYSTEM_UI_FLAG_IMMERSIVE = 0x00000800; 2584 2585 /** 2586 * Flag for {@link #setSystemUiVisibility(int)}: View would like to remain interactive when 2587 * hiding the status bar with {@link #SYSTEM_UI_FLAG_FULLSCREEN} and/or hiding the navigation 2588 * bar with {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}. Use this flag to create an immersive 2589 * experience while also hiding the system bars. If this flag is not set, 2590 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION} will be force cleared by the system on any user 2591 * interaction, and {@link #SYSTEM_UI_FLAG_FULLSCREEN} will be force-cleared by the system 2592 * if the user swipes from the top of the screen. 2593 * <p>When system bars are hidden in immersive mode, they can be revealed temporarily with 2594 * system gestures, such as swiping from the top of the screen. These transient system bars 2595 * will overlay app’s content, may have some degree of transparency, and will automatically 2596 * hide after a short timeout. 2597 * </p><p>Since this flag is a modifier for {@link #SYSTEM_UI_FLAG_FULLSCREEN} and 2598 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, it only has an effect when used in combination 2599 * with one or both of those flags.</p> 2600 */ 2601 public static final int SYSTEM_UI_FLAG_IMMERSIVE_STICKY = 0x00001000; 2602 2603 /** 2604 * @deprecated Use {@link #SYSTEM_UI_FLAG_LOW_PROFILE} instead. 2605 */ 2606 public static final int STATUS_BAR_HIDDEN = SYSTEM_UI_FLAG_LOW_PROFILE; 2607 2608 /** 2609 * @deprecated Use {@link #SYSTEM_UI_FLAG_VISIBLE} instead. 2610 */ 2611 public static final int STATUS_BAR_VISIBLE = SYSTEM_UI_FLAG_VISIBLE; 2612 2613 /** 2614 * @hide 2615 * 2616 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2617 * out of the public fields to keep the undefined bits out of the developer's way. 2618 * 2619 * Flag to make the status bar not expandable. Unless you also 2620 * set {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS}, new notifications will continue to show. 2621 */ 2622 public static final int STATUS_BAR_DISABLE_EXPAND = 0x00010000; 2623 2624 /** 2625 * @hide 2626 * 2627 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2628 * out of the public fields to keep the undefined bits out of the developer's way. 2629 * 2630 * Flag to hide notification icons and scrolling ticker text. 2631 */ 2632 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ICONS = 0x00020000; 2633 2634 /** 2635 * @hide 2636 * 2637 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2638 * out of the public fields to keep the undefined bits out of the developer's way. 2639 * 2640 * Flag to disable incoming notification alerts. This will not block 2641 * icons, but it will block sound, vibrating and other visual or aural notifications. 2642 */ 2643 public static final int STATUS_BAR_DISABLE_NOTIFICATION_ALERTS = 0x00040000; 2644 2645 /** 2646 * @hide 2647 * 2648 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2649 * out of the public fields to keep the undefined bits out of the developer's way. 2650 * 2651 * Flag to hide only the scrolling ticker. Note that 2652 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_ICONS} implies 2653 * {@link #STATUS_BAR_DISABLE_NOTIFICATION_TICKER}. 2654 */ 2655 public static final int STATUS_BAR_DISABLE_NOTIFICATION_TICKER = 0x00080000; 2656 2657 /** 2658 * @hide 2659 * 2660 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2661 * out of the public fields to keep the undefined bits out of the developer's way. 2662 * 2663 * Flag to hide the center system info area. 2664 */ 2665 public static final int STATUS_BAR_DISABLE_SYSTEM_INFO = 0x00100000; 2666 2667 /** 2668 * @hide 2669 * 2670 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2671 * out of the public fields to keep the undefined bits out of the developer's way. 2672 * 2673 * Flag to hide only the home button. Don't use this 2674 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2675 */ 2676 public static final int STATUS_BAR_DISABLE_HOME = 0x00200000; 2677 2678 /** 2679 * @hide 2680 * 2681 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2682 * out of the public fields to keep the undefined bits out of the developer's way. 2683 * 2684 * Flag to hide only the back button. Don't use this 2685 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2686 */ 2687 public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; 2688 2689 /** 2690 * @hide 2691 * 2692 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2693 * out of the public fields to keep the undefined bits out of the developer's way. 2694 * 2695 * Flag to hide only the clock. You might use this if your activity has 2696 * its own clock making the status bar's clock redundant. 2697 */ 2698 public static final int STATUS_BAR_DISABLE_CLOCK = 0x00800000; 2699 2700 /** 2701 * @hide 2702 * 2703 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2704 * out of the public fields to keep the undefined bits out of the developer's way. 2705 * 2706 * Flag to hide only the recent apps button. Don't use this 2707 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2708 */ 2709 public static final int STATUS_BAR_DISABLE_RECENT = 0x01000000; 2710 2711 /** 2712 * @hide 2713 * 2714 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2715 * out of the public fields to keep the undefined bits out of the developer's way. 2716 * 2717 * Flag to disable the global search gesture. Don't use this 2718 * unless you're a special part of the system UI (i.e., setup wizard, keyguard). 2719 */ 2720 public static final int STATUS_BAR_DISABLE_SEARCH = 0x02000000; 2721 2722 /** 2723 * @hide 2724 * 2725 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2726 * out of the public fields to keep the undefined bits out of the developer's way. 2727 * 2728 * Flag to specify that the status bar is displayed in transient mode. 2729 */ 2730 public static final int STATUS_BAR_TRANSIENT = 0x04000000; 2731 2732 /** 2733 * @hide 2734 * 2735 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2736 * out of the public fields to keep the undefined bits out of the developer's way. 2737 * 2738 * Flag to specify that the navigation bar is displayed in transient mode. 2739 */ 2740 public static final int NAVIGATION_BAR_TRANSIENT = 0x08000000; 2741 2742 /** 2743 * @hide 2744 * 2745 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2746 * out of the public fields to keep the undefined bits out of the developer's way. 2747 * 2748 * Flag to specify that the hidden status bar would like to be shown. 2749 */ 2750 public static final int STATUS_BAR_UNHIDE = 0x10000000; 2751 2752 /** 2753 * @hide 2754 * 2755 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2756 * out of the public fields to keep the undefined bits out of the developer's way. 2757 * 2758 * Flag to specify that the hidden navigation bar would like to be shown. 2759 */ 2760 public static final int NAVIGATION_BAR_UNHIDE = 0x20000000; 2761 2762 /** 2763 * @hide 2764 * 2765 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2766 * out of the public fields to keep the undefined bits out of the developer's way. 2767 * 2768 * Flag to specify that the status bar is displayed in translucent mode. 2769 */ 2770 public static final int STATUS_BAR_TRANSLUCENT = 0x40000000; 2771 2772 /** 2773 * @hide 2774 * 2775 * NOTE: This flag may only be used in subtreeSystemUiVisibility. It is masked 2776 * out of the public fields to keep the undefined bits out of the developer's way. 2777 * 2778 * Flag to specify that the navigation bar is displayed in translucent mode. 2779 */ 2780 public static final int NAVIGATION_BAR_TRANSLUCENT = 0x80000000; 2781 2782 /** 2783 * @hide 2784 * 2785 * Whether Recents is visible or not. 2786 */ 2787 public static final int RECENT_APPS_VISIBLE = 0x00004000; 2788 2789 /** 2790 * @hide 2791 * 2792 * Makes system ui transparent. 2793 */ 2794 public static final int SYSTEM_UI_TRANSPARENT = 0x00008000; 2795 2796 /** 2797 * @hide 2798 */ 2799 public static final int PUBLIC_STATUS_BAR_VISIBILITY_MASK = 0x00003FFF; 2800 2801 /** 2802 * These are the system UI flags that can be cleared by events outside 2803 * of an application. Currently this is just the ability to tap on the 2804 * screen while hiding the navigation bar to have it return. 2805 * @hide 2806 */ 2807 public static final int SYSTEM_UI_CLEARABLE_FLAGS = 2808 SYSTEM_UI_FLAG_LOW_PROFILE | SYSTEM_UI_FLAG_HIDE_NAVIGATION 2809 | SYSTEM_UI_FLAG_FULLSCREEN; 2810 2811 /** 2812 * Flags that can impact the layout in relation to system UI. 2813 */ 2814 public static final int SYSTEM_UI_LAYOUT_FLAGS = 2815 SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION 2816 | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; 2817 2818 /** @hide */ 2819 @IntDef(flag = true, 2820 value = { FIND_VIEWS_WITH_TEXT, FIND_VIEWS_WITH_CONTENT_DESCRIPTION }) 2821 @Retention(RetentionPolicy.SOURCE) 2822 public @interface FindViewFlags {} 2823 2824 /** 2825 * Find views that render the specified text. 2826 * 2827 * @see #findViewsWithText(ArrayList, CharSequence, int) 2828 */ 2829 public static final int FIND_VIEWS_WITH_TEXT = 0x00000001; 2830 2831 /** 2832 * Find find views that contain the specified content description. 2833 * 2834 * @see #findViewsWithText(ArrayList, CharSequence, int) 2835 */ 2836 public static final int FIND_VIEWS_WITH_CONTENT_DESCRIPTION = 0x00000002; 2837 2838 /** 2839 * Find views that contain {@link AccessibilityNodeProvider}. Such 2840 * a View is a root of virtual view hierarchy and may contain the searched 2841 * text. If this flag is set Views with providers are automatically 2842 * added and it is a responsibility of the client to call the APIs of 2843 * the provider to determine whether the virtual tree rooted at this View 2844 * contains the text, i.e. getting the list of {@link AccessibilityNodeInfo}s 2845 * representing the virtual views with this text. 2846 * 2847 * @see #findViewsWithText(ArrayList, CharSequence, int) 2848 * 2849 * @hide 2850 */ 2851 public static final int FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS = 0x00000004; 2852 2853 /** 2854 * The undefined cursor position. 2855 * 2856 * @hide 2857 */ 2858 public static final int ACCESSIBILITY_CURSOR_POSITION_UNDEFINED = -1; 2859 2860 /** 2861 * Indicates that the screen has changed state and is now off. 2862 * 2863 * @see #onScreenStateChanged(int) 2864 */ 2865 public static final int SCREEN_STATE_OFF = 0x0; 2866 2867 /** 2868 * Indicates that the screen has changed state and is now on. 2869 * 2870 * @see #onScreenStateChanged(int) 2871 */ 2872 public static final int SCREEN_STATE_ON = 0x1; 2873 2874 /** 2875 * Indicates no axis of view scrolling. 2876 */ 2877 public static final int SCROLL_AXIS_NONE = 0; 2878 2879 /** 2880 * Indicates scrolling along the horizontal axis. 2881 */ 2882 public static final int SCROLL_AXIS_HORIZONTAL = 1 << 0; 2883 2884 /** 2885 * Indicates scrolling along the vertical axis. 2886 */ 2887 public static final int SCROLL_AXIS_VERTICAL = 1 << 1; 2888 2889 /** 2890 * Controls the over-scroll mode for this view. 2891 * See {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)}, 2892 * {@link #OVER_SCROLL_ALWAYS}, {@link #OVER_SCROLL_IF_CONTENT_SCROLLS}, 2893 * and {@link #OVER_SCROLL_NEVER}. 2894 */ 2895 private int mOverScrollMode; 2896 2897 /** 2898 * The parent this view is attached to. 2899 * {@hide} 2900 * 2901 * @see #getParent() 2902 */ 2903 protected ViewParent mParent; 2904 2905 /** 2906 * {@hide} 2907 */ 2908 AttachInfo mAttachInfo; 2909 2910 /** 2911 * {@hide} 2912 */ 2913 @ViewDebug.ExportedProperty(flagMapping = { 2914 @ViewDebug.FlagToString(mask = PFLAG_FORCE_LAYOUT, equals = PFLAG_FORCE_LAYOUT, 2915 name = "FORCE_LAYOUT"), 2916 @ViewDebug.FlagToString(mask = PFLAG_LAYOUT_REQUIRED, equals = PFLAG_LAYOUT_REQUIRED, 2917 name = "LAYOUT_REQUIRED"), 2918 @ViewDebug.FlagToString(mask = PFLAG_DRAWING_CACHE_VALID, equals = PFLAG_DRAWING_CACHE_VALID, 2919 name = "DRAWING_CACHE_INVALID", outputIf = false), 2920 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "DRAWN", outputIf = true), 2921 @ViewDebug.FlagToString(mask = PFLAG_DRAWN, equals = PFLAG_DRAWN, name = "NOT_DRAWN", outputIf = false), 2922 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY_OPAQUE, name = "DIRTY_OPAQUE"), 2923 @ViewDebug.FlagToString(mask = PFLAG_DIRTY_MASK, equals = PFLAG_DIRTY, name = "DIRTY") 2924 }, formatToHexString = true) 2925 int mPrivateFlags; 2926 int mPrivateFlags2; 2927 int mPrivateFlags3; 2928 2929 /** 2930 * This view's request for the visibility of the status bar. 2931 * @hide 2932 */ 2933 @ViewDebug.ExportedProperty(flagMapping = { 2934 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_LOW_PROFILE, 2935 equals = SYSTEM_UI_FLAG_LOW_PROFILE, 2936 name = "SYSTEM_UI_FLAG_LOW_PROFILE", outputIf = true), 2937 @ViewDebug.FlagToString(mask = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2938 equals = SYSTEM_UI_FLAG_HIDE_NAVIGATION, 2939 name = "SYSTEM_UI_FLAG_HIDE_NAVIGATION", outputIf = true), 2940 @ViewDebug.FlagToString(mask = PUBLIC_STATUS_BAR_VISIBILITY_MASK, 2941 equals = SYSTEM_UI_FLAG_VISIBLE, 2942 name = "SYSTEM_UI_FLAG_VISIBLE", outputIf = true) 2943 }, formatToHexString = true) 2944 int mSystemUiVisibility; 2945 2946 /** 2947 * Reference count for transient state. 2948 * @see #setHasTransientState(boolean) 2949 */ 2950 int mTransientStateCount = 0; 2951 2952 /** 2953 * Count of how many windows this view has been attached to. 2954 */ 2955 int mWindowAttachCount; 2956 2957 /** 2958 * The layout parameters associated with this view and used by the parent 2959 * {@link android.view.ViewGroup} to determine how this view should be 2960 * laid out. 2961 * {@hide} 2962 */ 2963 protected ViewGroup.LayoutParams mLayoutParams; 2964 2965 /** 2966 * The view flags hold various views states. 2967 * {@hide} 2968 */ 2969 @ViewDebug.ExportedProperty(formatToHexString = true) 2970 int mViewFlags; 2971 2972 static class TransformationInfo { 2973 /** 2974 * The transform matrix for the View. This transform is calculated internally 2975 * based on the translation, rotation, and scale properties. 2976 * 2977 * Do *not* use this variable directly; instead call getMatrix(), which will 2978 * load the value from the View's RenderNode. 2979 */ 2980 private final Matrix mMatrix = new Matrix(); 2981 2982 /** 2983 * The inverse transform matrix for the View. This transform is calculated 2984 * internally based on the translation, rotation, and scale properties. 2985 * 2986 * Do *not* use this variable directly; instead call getInverseMatrix(), 2987 * which will load the value from the View's RenderNode. 2988 */ 2989 private Matrix mInverseMatrix; 2990 2991 /** 2992 * The opacity of the View. This is a value from 0 to 1, where 0 means 2993 * completely transparent and 1 means completely opaque. 2994 */ 2995 @ViewDebug.ExportedProperty 2996 float mAlpha = 1f; 2997 2998 /** 2999 * The opacity of the view as manipulated by the Fade transition. This is a hidden 3000 * property only used by transitions, which is composited with the other alpha 3001 * values to calculate the final visual alpha value. 3002 */ 3003 float mTransitionAlpha = 1f; 3004 } 3005 3006 TransformationInfo mTransformationInfo; 3007 3008 /** 3009 * Current clip bounds. to which all drawing of this view are constrained. 3010 */ 3011 Rect mClipBounds = null; 3012 3013 private boolean mLastIsOpaque; 3014 3015 /** 3016 * The distance in pixels from the left edge of this view's parent 3017 * to the left edge of this view. 3018 * {@hide} 3019 */ 3020 @ViewDebug.ExportedProperty(category = "layout") 3021 protected int mLeft; 3022 /** 3023 * The distance in pixels from the left edge of this view's parent 3024 * to the right edge of this view. 3025 * {@hide} 3026 */ 3027 @ViewDebug.ExportedProperty(category = "layout") 3028 protected int mRight; 3029 /** 3030 * The distance in pixels from the top edge of this view's parent 3031 * to the top edge of this view. 3032 * {@hide} 3033 */ 3034 @ViewDebug.ExportedProperty(category = "layout") 3035 protected int mTop; 3036 /** 3037 * The distance in pixels from the top edge of this view's parent 3038 * to the bottom edge of this view. 3039 * {@hide} 3040 */ 3041 @ViewDebug.ExportedProperty(category = "layout") 3042 protected int mBottom; 3043 3044 /** 3045 * The offset, in pixels, by which the content of this view is scrolled 3046 * horizontally. 3047 * {@hide} 3048 */ 3049 @ViewDebug.ExportedProperty(category = "scrolling") 3050 protected int mScrollX; 3051 /** 3052 * The offset, in pixels, by which the content of this view is scrolled 3053 * vertically. 3054 * {@hide} 3055 */ 3056 @ViewDebug.ExportedProperty(category = "scrolling") 3057 protected int mScrollY; 3058 3059 /** 3060 * The left padding in pixels, that is the distance in pixels between the 3061 * left edge of this view and the left edge of its content. 3062 * {@hide} 3063 */ 3064 @ViewDebug.ExportedProperty(category = "padding") 3065 protected int mPaddingLeft = 0; 3066 /** 3067 * The right padding in pixels, that is the distance in pixels between the 3068 * right edge of this view and the right edge of its content. 3069 * {@hide} 3070 */ 3071 @ViewDebug.ExportedProperty(category = "padding") 3072 protected int mPaddingRight = 0; 3073 /** 3074 * The top padding in pixels, that is the distance in pixels between the 3075 * top edge of this view and the top edge of its content. 3076 * {@hide} 3077 */ 3078 @ViewDebug.ExportedProperty(category = "padding") 3079 protected int mPaddingTop; 3080 /** 3081 * The bottom padding in pixels, that is the distance in pixels between the 3082 * bottom edge of this view and the bottom edge of its content. 3083 * {@hide} 3084 */ 3085 @ViewDebug.ExportedProperty(category = "padding") 3086 protected int mPaddingBottom; 3087 3088 /** 3089 * The layout insets in pixels, that is the distance in pixels between the 3090 * visible edges of this view its bounds. 3091 */ 3092 private Insets mLayoutInsets; 3093 3094 /** 3095 * Briefly describes the view and is primarily used for accessibility support. 3096 */ 3097 private CharSequence mContentDescription; 3098 3099 /** 3100 * Specifies the id of a view for which this view serves as a label for 3101 * accessibility purposes. 3102 */ 3103 private int mLabelForId = View.NO_ID; 3104 3105 /** 3106 * Predicate for matching labeled view id with its label for 3107 * accessibility purposes. 3108 */ 3109 private MatchLabelForPredicate mMatchLabelForPredicate; 3110 3111 /** 3112 * Predicate for matching a view by its id. 3113 */ 3114 private MatchIdPredicate mMatchIdPredicate; 3115 3116 /** 3117 * Cache the paddingRight set by the user to append to the scrollbar's size. 3118 * 3119 * @hide 3120 */ 3121 @ViewDebug.ExportedProperty(category = "padding") 3122 protected int mUserPaddingRight; 3123 3124 /** 3125 * Cache the paddingBottom set by the user to append to the scrollbar's size. 3126 * 3127 * @hide 3128 */ 3129 @ViewDebug.ExportedProperty(category = "padding") 3130 protected int mUserPaddingBottom; 3131 3132 /** 3133 * Cache the paddingLeft set by the user to append to the scrollbar's size. 3134 * 3135 * @hide 3136 */ 3137 @ViewDebug.ExportedProperty(category = "padding") 3138 protected int mUserPaddingLeft; 3139 3140 /** 3141 * Cache the paddingStart set by the user to append to the scrollbar's size. 3142 * 3143 */ 3144 @ViewDebug.ExportedProperty(category = "padding") 3145 int mUserPaddingStart; 3146 3147 /** 3148 * Cache the paddingEnd set by the user to append to the scrollbar's size. 3149 * 3150 */ 3151 @ViewDebug.ExportedProperty(category = "padding") 3152 int mUserPaddingEnd; 3153 3154 /** 3155 * Cache initial left padding. 3156 * 3157 * @hide 3158 */ 3159 int mUserPaddingLeftInitial; 3160 3161 /** 3162 * Cache initial right padding. 3163 * 3164 * @hide 3165 */ 3166 int mUserPaddingRightInitial; 3167 3168 /** 3169 * Default undefined padding 3170 */ 3171 private static final int UNDEFINED_PADDING = Integer.MIN_VALUE; 3172 3173 /** 3174 * Cache if a left padding has been defined 3175 */ 3176 private boolean mLeftPaddingDefined = false; 3177 3178 /** 3179 * Cache if a right padding has been defined 3180 */ 3181 private boolean mRightPaddingDefined = false; 3182 3183 /** 3184 * @hide 3185 */ 3186 int mOldWidthMeasureSpec = Integer.MIN_VALUE; 3187 /** 3188 * @hide 3189 */ 3190 int mOldHeightMeasureSpec = Integer.MIN_VALUE; 3191 3192 private LongSparseLongArray mMeasureCache; 3193 3194 @ViewDebug.ExportedProperty(deepExport = true, prefix = "bg_") 3195 private Drawable mBackground; 3196 private TintInfo mBackgroundTint; 3197 3198 /** 3199 * RenderNode used for backgrounds. 3200 * <p> 3201 * When non-null and valid, this is expected to contain an up-to-date copy 3202 * of the background drawable. It is cleared on temporary detach, and reset 3203 * on cleanup. 3204 */ 3205 private RenderNode mBackgroundRenderNode; 3206 3207 private int mBackgroundResource; 3208 private boolean mBackgroundSizeChanged; 3209 3210 private String mTransitionName; 3211 3212 private static class TintInfo { 3213 ColorStateList mTintList; 3214 PorterDuff.Mode mTintMode; 3215 boolean mHasTintMode; 3216 boolean mHasTintList; 3217 } 3218 3219 static class ListenerInfo { 3220 /** 3221 * Listener used to dispatch focus change events. 3222 * This field should be made private, so it is hidden from the SDK. 3223 * {@hide} 3224 */ 3225 protected OnFocusChangeListener mOnFocusChangeListener; 3226 3227 /** 3228 * Listeners for layout change events. 3229 */ 3230 private ArrayList<OnLayoutChangeListener> mOnLayoutChangeListeners; 3231 3232 /** 3233 * Listeners for attach events. 3234 */ 3235 private CopyOnWriteArrayList<OnAttachStateChangeListener> mOnAttachStateChangeListeners; 3236 3237 /** 3238 * Listener used to dispatch click events. 3239 * This field should be made private, so it is hidden from the SDK. 3240 * {@hide} 3241 */ 3242 public OnClickListener mOnClickListener; 3243 3244 /** 3245 * Listener used to dispatch long click events. 3246 * This field should be made private, so it is hidden from the SDK. 3247 * {@hide} 3248 */ 3249 protected OnLongClickListener mOnLongClickListener; 3250 3251 /** 3252 * Listener used to build the context menu. 3253 * This field should be made private, so it is hidden from the SDK. 3254 * {@hide} 3255 */ 3256 protected OnCreateContextMenuListener mOnCreateContextMenuListener; 3257 3258 private OnKeyListener mOnKeyListener; 3259 3260 private OnTouchListener mOnTouchListener; 3261 3262 private OnHoverListener mOnHoverListener; 3263 3264 private OnGenericMotionListener mOnGenericMotionListener; 3265 3266 private OnDragListener mOnDragListener; 3267 3268 private OnSystemUiVisibilityChangeListener mOnSystemUiVisibilityChangeListener; 3269 3270 OnApplyWindowInsetsListener mOnApplyWindowInsetsListener; 3271 } 3272 3273 ListenerInfo mListenerInfo; 3274 3275 /** 3276 * The application environment this view lives in. 3277 * This field should be made private, so it is hidden from the SDK. 3278 * {@hide} 3279 */ 3280 @ViewDebug.ExportedProperty(deepExport = true) 3281 protected Context mContext; 3282 3283 private final Resources mResources; 3284 3285 private ScrollabilityCache mScrollCache; 3286 3287 private int[] mDrawableState = null; 3288 3289 ViewOutlineProvider mOutlineProvider = ViewOutlineProvider.BACKGROUND; 3290 3291 /** 3292 * Animator that automatically runs based on state changes. 3293 */ 3294 private StateListAnimator mStateListAnimator; 3295 3296 /** 3297 * When this view has focus and the next focus is {@link #FOCUS_LEFT}, 3298 * the user may specify which view to go to next. 3299 */ 3300 private int mNextFocusLeftId = View.NO_ID; 3301 3302 /** 3303 * When this view has focus and the next focus is {@link #FOCUS_RIGHT}, 3304 * the user may specify which view to go to next. 3305 */ 3306 private int mNextFocusRightId = View.NO_ID; 3307 3308 /** 3309 * When this view has focus and the next focus is {@link #FOCUS_UP}, 3310 * the user may specify which view to go to next. 3311 */ 3312 private int mNextFocusUpId = View.NO_ID; 3313 3314 /** 3315 * When this view has focus and the next focus is {@link #FOCUS_DOWN}, 3316 * the user may specify which view to go to next. 3317 */ 3318 private int mNextFocusDownId = View.NO_ID; 3319 3320 /** 3321 * When this view has focus and the next focus is {@link #FOCUS_FORWARD}, 3322 * the user may specify which view to go to next. 3323 */ 3324 int mNextFocusForwardId = View.NO_ID; 3325 3326 private CheckForLongPress mPendingCheckForLongPress; 3327 private CheckForTap mPendingCheckForTap = null; 3328 private PerformClick mPerformClick; 3329 private SendViewScrolledAccessibilityEvent mSendViewScrolledAccessibilityEvent; 3330 3331 private UnsetPressedState mUnsetPressedState; 3332 3333 /** 3334 * Whether the long press's action has been invoked. The tap's action is invoked on the 3335 * up event while a long press is invoked as soon as the long press duration is reached, so 3336 * a long press could be performed before the tap is checked, in which case the tap's action 3337 * should not be invoked. 3338 */ 3339 private boolean mHasPerformedLongPress; 3340 3341 /** 3342 * The minimum height of the view. We'll try our best to have the height 3343 * of this view to at least this amount. 3344 */ 3345 @ViewDebug.ExportedProperty(category = "measurement") 3346 private int mMinHeight; 3347 3348 /** 3349 * The minimum width of the view. We'll try our best to have the width 3350 * of this view to at least this amount. 3351 */ 3352 @ViewDebug.ExportedProperty(category = "measurement") 3353 private int mMinWidth; 3354 3355 /** 3356 * The delegate to handle touch events that are physically in this view 3357 * but should be handled by another view. 3358 */ 3359 private TouchDelegate mTouchDelegate = null; 3360 3361 /** 3362 * Solid color to use as a background when creating the drawing cache. Enables 3363 * the cache to use 16 bit bitmaps instead of 32 bit. 3364 */ 3365 private int mDrawingCacheBackgroundColor = 0; 3366 3367 /** 3368 * Special tree observer used when mAttachInfo is null. 3369 */ 3370 private ViewTreeObserver mFloatingTreeObserver; 3371 3372 /** 3373 * Cache the touch slop from the context that created the view. 3374 */ 3375 private int mTouchSlop; 3376 3377 /** 3378 * Object that handles automatic animation of view properties. 3379 */ 3380 private ViewPropertyAnimator mAnimator = null; 3381 3382 /** 3383 * Flag indicating that a drag can cross window boundaries. When 3384 * {@link #startDrag(ClipData, DragShadowBuilder, Object, int)} is called 3385 * with this flag set, all visible applications will be able to participate 3386 * in the drag operation and receive the dragged content. 3387 * 3388 * @hide 3389 */ 3390 public static final int DRAG_FLAG_GLOBAL = 1; 3391 3392 /** 3393 * Vertical scroll factor cached by {@link #getVerticalScrollFactor}. 3394 */ 3395 private float mVerticalScrollFactor; 3396 3397 /** 3398 * Position of the vertical scroll bar. 3399 */ 3400 private int mVerticalScrollbarPosition; 3401 3402 /** 3403 * Position the scroll bar at the default position as determined by the system. 3404 */ 3405 public static final int SCROLLBAR_POSITION_DEFAULT = 0; 3406 3407 /** 3408 * Position the scroll bar along the left edge. 3409 */ 3410 public static final int SCROLLBAR_POSITION_LEFT = 1; 3411 3412 /** 3413 * Position the scroll bar along the right edge. 3414 */ 3415 public static final int SCROLLBAR_POSITION_RIGHT = 2; 3416 3417 /** 3418 * Indicates that the view does not have a layer. 3419 * 3420 * @see #getLayerType() 3421 * @see #setLayerType(int, android.graphics.Paint) 3422 * @see #LAYER_TYPE_SOFTWARE 3423 * @see #LAYER_TYPE_HARDWARE 3424 */ 3425 public static final int LAYER_TYPE_NONE = 0; 3426 3427 /** 3428 * <p>Indicates that the view has a software layer. A software layer is backed 3429 * by a bitmap and causes the view to be rendered using Android's software 3430 * rendering pipeline, even if hardware acceleration is enabled.</p> 3431 * 3432 * <p>Software layers have various usages:</p> 3433 * <p>When the application is not using hardware acceleration, a software layer 3434 * is useful to apply a specific color filter and/or blending mode and/or 3435 * translucency to a view and all its children.</p> 3436 * <p>When the application is using hardware acceleration, a software layer 3437 * is useful to render drawing primitives not supported by the hardware 3438 * accelerated pipeline. It can also be used to cache a complex view tree 3439 * into a texture and reduce the complexity of drawing operations. For instance, 3440 * when animating a complex view tree with a translation, a software layer can 3441 * be used to render the view tree only once.</p> 3442 * <p>Software layers should be avoided when the affected view tree updates 3443 * often. Every update will require to re-render the software layer, which can 3444 * potentially be slow (particularly when hardware acceleration is turned on 3445 * since the layer will have to be uploaded into a hardware texture after every 3446 * update.)</p> 3447 * 3448 * @see #getLayerType() 3449 * @see #setLayerType(int, android.graphics.Paint) 3450 * @see #LAYER_TYPE_NONE 3451 * @see #LAYER_TYPE_HARDWARE 3452 */ 3453 public static final int LAYER_TYPE_SOFTWARE = 1; 3454 3455 /** 3456 * <p>Indicates that the view has a hardware layer. A hardware layer is backed 3457 * by a hardware specific texture (generally Frame Buffer Objects or FBO on 3458 * OpenGL hardware) and causes the view to be rendered using Android's hardware 3459 * rendering pipeline, but only if hardware acceleration is turned on for the 3460 * view hierarchy. When hardware acceleration is turned off, hardware layers 3461 * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p> 3462 * 3463 * <p>A hardware layer is useful to apply a specific color filter and/or 3464 * blending mode and/or translucency to a view and all its children.</p> 3465 * <p>A hardware layer can be used to cache a complex view tree into a 3466 * texture and reduce the complexity of drawing operations. For instance, 3467 * when animating a complex view tree with a translation, a hardware layer can 3468 * be used to render the view tree only once.</p> 3469 * <p>A hardware layer can also be used to increase the rendering quality when 3470 * rotation transformations are applied on a view. It can also be used to 3471 * prevent potential clipping issues when applying 3D transforms on a view.</p> 3472 * 3473 * @see #getLayerType() 3474 * @see #setLayerType(int, android.graphics.Paint) 3475 * @see #LAYER_TYPE_NONE 3476 * @see #LAYER_TYPE_SOFTWARE 3477 */ 3478 public static final int LAYER_TYPE_HARDWARE = 2; 3479 3480 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3481 @ViewDebug.IntToString(from = LAYER_TYPE_NONE, to = "NONE"), 3482 @ViewDebug.IntToString(from = LAYER_TYPE_SOFTWARE, to = "SOFTWARE"), 3483 @ViewDebug.IntToString(from = LAYER_TYPE_HARDWARE, to = "HARDWARE") 3484 }) 3485 int mLayerType = LAYER_TYPE_NONE; 3486 Paint mLayerPaint; 3487 3488 /** 3489 * Set to true when drawing cache is enabled and cannot be created. 3490 * 3491 * @hide 3492 */ 3493 public boolean mCachingFailed; 3494 private Bitmap mDrawingCache; 3495 private Bitmap mUnscaledDrawingCache; 3496 3497 /** 3498 * RenderNode holding View properties, potentially holding a DisplayList of View content. 3499 * <p> 3500 * When non-null and valid, this is expected to contain an up-to-date copy 3501 * of the View content. Its DisplayList content is cleared on temporary detach and reset on 3502 * cleanup. 3503 */ 3504 final RenderNode mRenderNode; 3505 3506 /** 3507 * Set to true when the view is sending hover accessibility events because it 3508 * is the innermost hovered view. 3509 */ 3510 private boolean mSendingHoverAccessibilityEvents; 3511 3512 /** 3513 * Delegate for injecting accessibility functionality. 3514 */ 3515 AccessibilityDelegate mAccessibilityDelegate; 3516 3517 /** 3518 * The view's overlay layer. Developers get a reference to the overlay via getOverlay() 3519 * and add/remove objects to/from the overlay directly through the Overlay methods. 3520 */ 3521 ViewOverlay mOverlay; 3522 3523 /** 3524 * The currently active parent view for receiving delegated nested scrolling events. 3525 * This is set by {@link #startNestedScroll(int)} during a touch interaction and cleared 3526 * by {@link #stopNestedScroll()} at the same point where we clear 3527 * requestDisallowInterceptTouchEvent. 3528 */ 3529 private ViewParent mNestedScrollingParent; 3530 3531 /** 3532 * Consistency verifier for debugging purposes. 3533 * @hide 3534 */ 3535 protected final InputEventConsistencyVerifier mInputEventConsistencyVerifier = 3536 InputEventConsistencyVerifier.isInstrumentationEnabled() ? 3537 new InputEventConsistencyVerifier(this, 0) : null; 3538 3539 private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1); 3540 3541 private int[] mTempNestedScrollConsumed; 3542 3543 /** 3544 * An overlay is going to draw this View instead of being drawn as part of this 3545 * View's parent. mGhostView is the View in the Overlay that must be invalidated 3546 * when this view is invalidated. 3547 */ 3548 GhostView mGhostView; 3549 3550 /** 3551 * Holds pairs of adjacent attribute data: attribute name followed by its value. 3552 * @hide 3553 */ 3554 @ViewDebug.ExportedProperty(category = "attributes", hasAdjacentMapping = true) 3555 public String[] mAttributes; 3556 3557 /** 3558 * Maps a Resource id to its name. 3559 */ 3560 private static SparseArray<String> mAttributeMap; 3561 3562 /** 3563 * Simple constructor to use when creating a view from code. 3564 * 3565 * @param context The Context the view is running in, through which it can 3566 * access the current theme, resources, etc. 3567 */ 3568 public View(Context context) { 3569 mContext = context; 3570 mResources = context != null ? context.getResources() : null; 3571 mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED; 3572 // Set some flags defaults 3573 mPrivateFlags2 = 3574 (LAYOUT_DIRECTION_DEFAULT << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) | 3575 (TEXT_DIRECTION_DEFAULT << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) | 3576 (PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT) | 3577 (TEXT_ALIGNMENT_DEFAULT << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) | 3578 (PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT) | 3579 (IMPORTANT_FOR_ACCESSIBILITY_DEFAULT << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT); 3580 mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 3581 setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS); 3582 mUserPaddingStart = UNDEFINED_PADDING; 3583 mUserPaddingEnd = UNDEFINED_PADDING; 3584 mRenderNode = RenderNode.create(getClass().getName(), this); 3585 3586 if (!sCompatibilityDone && context != null) { 3587 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3588 3589 // Older apps may need this compatibility hack for measurement. 3590 sUseBrokenMakeMeasureSpec = targetSdkVersion <= JELLY_BEAN_MR1; 3591 3592 // Older apps expect onMeasure() to always be called on a layout pass, regardless 3593 // of whether a layout was requested on that View. 3594 sIgnoreMeasureCache = targetSdkVersion < KITKAT; 3595 3596 sCompatibilityDone = true; 3597 } 3598 } 3599 3600 /** 3601 * Constructor that is called when inflating a view from XML. This is called 3602 * when a view is being constructed from an XML file, supplying attributes 3603 * that were specified in the XML file. This version uses a default style of 3604 * 0, so the only attribute values applied are those in the Context's Theme 3605 * and the given AttributeSet. 3606 * 3607 * <p> 3608 * The method onFinishInflate() will be called after all children have been 3609 * added. 3610 * 3611 * @param context The Context the view is running in, through which it can 3612 * access the current theme, resources, etc. 3613 * @param attrs The attributes of the XML tag that is inflating the view. 3614 * @see #View(Context, AttributeSet, int) 3615 */ 3616 public View(Context context, AttributeSet attrs) { 3617 this(context, attrs, 0); 3618 } 3619 3620 /** 3621 * Perform inflation from XML and apply a class-specific base style from a 3622 * theme attribute. This constructor of View allows subclasses to use their 3623 * own base style when they are inflating. For example, a Button class's 3624 * constructor would call this version of the super class constructor and 3625 * supply <code>R.attr.buttonStyle</code> for <var>defStyleAttr</var>; this 3626 * allows the theme's button style to modify all of the base view attributes 3627 * (in particular its background) as well as the Button class's attributes. 3628 * 3629 * @param context The Context the view is running in, through which it can 3630 * access the current theme, resources, etc. 3631 * @param attrs The attributes of the XML tag that is inflating the view. 3632 * @param defStyleAttr An attribute in the current theme that contains a 3633 * reference to a style resource that supplies default values for 3634 * the view. Can be 0 to not look for defaults. 3635 * @see #View(Context, AttributeSet) 3636 */ 3637 public View(Context context, AttributeSet attrs, int defStyleAttr) { 3638 this(context, attrs, defStyleAttr, 0); 3639 } 3640 3641 /** 3642 * Perform inflation from XML and apply a class-specific base style from a 3643 * theme attribute or style resource. This constructor of View allows 3644 * subclasses to use their own base style when they are inflating. 3645 * <p> 3646 * When determining the final value of a particular attribute, there are 3647 * four inputs that come into play: 3648 * <ol> 3649 * <li>Any attribute values in the given AttributeSet. 3650 * <li>The style resource specified in the AttributeSet (named "style"). 3651 * <li>The default style specified by <var>defStyleAttr</var>. 3652 * <li>The default style specified by <var>defStyleRes</var>. 3653 * <li>The base values in this theme. 3654 * </ol> 3655 * <p> 3656 * Each of these inputs is considered in-order, with the first listed taking 3657 * precedence over the following ones. In other words, if in the 3658 * AttributeSet you have supplied <code><Button * textColor="#ff000000"></code> 3659 * , then the button's text will <em>always</em> be black, regardless of 3660 * what is specified in any of the styles. 3661 * 3662 * @param context The Context the view is running in, through which it can 3663 * access the current theme, resources, etc. 3664 * @param attrs The attributes of the XML tag that is inflating the view. 3665 * @param defStyleAttr An attribute in the current theme that contains a 3666 * reference to a style resource that supplies default values for 3667 * the view. Can be 0 to not look for defaults. 3668 * @param defStyleRes A resource identifier of a style resource that 3669 * supplies default values for the view, used only if 3670 * defStyleAttr is 0 or can not be found in the theme. Can be 0 3671 * to not look for defaults. 3672 * @see #View(Context, AttributeSet, int) 3673 */ 3674 public View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 3675 this(context); 3676 3677 final TypedArray a = context.obtainStyledAttributes( 3678 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 3679 3680 if (mDebugViewAttributes) { 3681 saveAttributeData(attrs, a); 3682 } 3683 3684 Drawable background = null; 3685 3686 int leftPadding = -1; 3687 int topPadding = -1; 3688 int rightPadding = -1; 3689 int bottomPadding = -1; 3690 int startPadding = UNDEFINED_PADDING; 3691 int endPadding = UNDEFINED_PADDING; 3692 3693 int padding = -1; 3694 3695 int viewFlagValues = 0; 3696 int viewFlagMasks = 0; 3697 3698 boolean setScrollContainer = false; 3699 3700 int x = 0; 3701 int y = 0; 3702 3703 float tx = 0; 3704 float ty = 0; 3705 float tz = 0; 3706 float elevation = 0; 3707 float rotation = 0; 3708 float rotationX = 0; 3709 float rotationY = 0; 3710 float sx = 1f; 3711 float sy = 1f; 3712 boolean transformSet = false; 3713 3714 int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY; 3715 int overScrollMode = mOverScrollMode; 3716 boolean initializeScrollbars = false; 3717 3718 boolean startPaddingDefined = false; 3719 boolean endPaddingDefined = false; 3720 boolean leftPaddingDefined = false; 3721 boolean rightPaddingDefined = false; 3722 3723 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 3724 3725 final int N = a.getIndexCount(); 3726 for (int i = 0; i < N; i++) { 3727 int attr = a.getIndex(i); 3728 switch (attr) { 3729 case com.android.internal.R.styleable.View_background: 3730 background = a.getDrawable(attr); 3731 break; 3732 case com.android.internal.R.styleable.View_padding: 3733 padding = a.getDimensionPixelSize(attr, -1); 3734 mUserPaddingLeftInitial = padding; 3735 mUserPaddingRightInitial = padding; 3736 leftPaddingDefined = true; 3737 rightPaddingDefined = true; 3738 break; 3739 case com.android.internal.R.styleable.View_paddingLeft: 3740 leftPadding = a.getDimensionPixelSize(attr, -1); 3741 mUserPaddingLeftInitial = leftPadding; 3742 leftPaddingDefined = true; 3743 break; 3744 case com.android.internal.R.styleable.View_paddingTop: 3745 topPadding = a.getDimensionPixelSize(attr, -1); 3746 break; 3747 case com.android.internal.R.styleable.View_paddingRight: 3748 rightPadding = a.getDimensionPixelSize(attr, -1); 3749 mUserPaddingRightInitial = rightPadding; 3750 rightPaddingDefined = true; 3751 break; 3752 case com.android.internal.R.styleable.View_paddingBottom: 3753 bottomPadding = a.getDimensionPixelSize(attr, -1); 3754 break; 3755 case com.android.internal.R.styleable.View_paddingStart: 3756 startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3757 startPaddingDefined = (startPadding != UNDEFINED_PADDING); 3758 break; 3759 case com.android.internal.R.styleable.View_paddingEnd: 3760 endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); 3761 endPaddingDefined = (endPadding != UNDEFINED_PADDING); 3762 break; 3763 case com.android.internal.R.styleable.View_scrollX: 3764 x = a.getDimensionPixelOffset(attr, 0); 3765 break; 3766 case com.android.internal.R.styleable.View_scrollY: 3767 y = a.getDimensionPixelOffset(attr, 0); 3768 break; 3769 case com.android.internal.R.styleable.View_alpha: 3770 setAlpha(a.getFloat(attr, 1f)); 3771 break; 3772 case com.android.internal.R.styleable.View_transformPivotX: 3773 setPivotX(a.getDimensionPixelOffset(attr, 0)); 3774 break; 3775 case com.android.internal.R.styleable.View_transformPivotY: 3776 setPivotY(a.getDimensionPixelOffset(attr, 0)); 3777 break; 3778 case com.android.internal.R.styleable.View_translationX: 3779 tx = a.getDimensionPixelOffset(attr, 0); 3780 transformSet = true; 3781 break; 3782 case com.android.internal.R.styleable.View_translationY: 3783 ty = a.getDimensionPixelOffset(attr, 0); 3784 transformSet = true; 3785 break; 3786 case com.android.internal.R.styleable.View_translationZ: 3787 tz = a.getDimensionPixelOffset(attr, 0); 3788 transformSet = true; 3789 break; 3790 case com.android.internal.R.styleable.View_elevation: 3791 elevation = a.getDimensionPixelOffset(attr, 0); 3792 transformSet = true; 3793 break; 3794 case com.android.internal.R.styleable.View_rotation: 3795 rotation = a.getFloat(attr, 0); 3796 transformSet = true; 3797 break; 3798 case com.android.internal.R.styleable.View_rotationX: 3799 rotationX = a.getFloat(attr, 0); 3800 transformSet = true; 3801 break; 3802 case com.android.internal.R.styleable.View_rotationY: 3803 rotationY = a.getFloat(attr, 0); 3804 transformSet = true; 3805 break; 3806 case com.android.internal.R.styleable.View_scaleX: 3807 sx = a.getFloat(attr, 1f); 3808 transformSet = true; 3809 break; 3810 case com.android.internal.R.styleable.View_scaleY: 3811 sy = a.getFloat(attr, 1f); 3812 transformSet = true; 3813 break; 3814 case com.android.internal.R.styleable.View_id: 3815 mID = a.getResourceId(attr, NO_ID); 3816 break; 3817 case com.android.internal.R.styleable.View_tag: 3818 mTag = a.getText(attr); 3819 break; 3820 case com.android.internal.R.styleable.View_fitsSystemWindows: 3821 if (a.getBoolean(attr, false)) { 3822 viewFlagValues |= FITS_SYSTEM_WINDOWS; 3823 viewFlagMasks |= FITS_SYSTEM_WINDOWS; 3824 } 3825 break; 3826 case com.android.internal.R.styleable.View_focusable: 3827 if (a.getBoolean(attr, false)) { 3828 viewFlagValues |= FOCUSABLE; 3829 viewFlagMasks |= FOCUSABLE_MASK; 3830 } 3831 break; 3832 case com.android.internal.R.styleable.View_focusableInTouchMode: 3833 if (a.getBoolean(attr, false)) { 3834 viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE; 3835 viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK; 3836 } 3837 break; 3838 case com.android.internal.R.styleable.View_clickable: 3839 if (a.getBoolean(attr, false)) { 3840 viewFlagValues |= CLICKABLE; 3841 viewFlagMasks |= CLICKABLE; 3842 } 3843 break; 3844 case com.android.internal.R.styleable.View_longClickable: 3845 if (a.getBoolean(attr, false)) { 3846 viewFlagValues |= LONG_CLICKABLE; 3847 viewFlagMasks |= LONG_CLICKABLE; 3848 } 3849 break; 3850 case com.android.internal.R.styleable.View_saveEnabled: 3851 if (!a.getBoolean(attr, true)) { 3852 viewFlagValues |= SAVE_DISABLED; 3853 viewFlagMasks |= SAVE_DISABLED_MASK; 3854 } 3855 break; 3856 case com.android.internal.R.styleable.View_duplicateParentState: 3857 if (a.getBoolean(attr, false)) { 3858 viewFlagValues |= DUPLICATE_PARENT_STATE; 3859 viewFlagMasks |= DUPLICATE_PARENT_STATE; 3860 } 3861 break; 3862 case com.android.internal.R.styleable.View_visibility: 3863 final int visibility = a.getInt(attr, 0); 3864 if (visibility != 0) { 3865 viewFlagValues |= VISIBILITY_FLAGS[visibility]; 3866 viewFlagMasks |= VISIBILITY_MASK; 3867 } 3868 break; 3869 case com.android.internal.R.styleable.View_layoutDirection: 3870 // Clear any layout direction flags (included resolved bits) already set 3871 mPrivateFlags2 &= 3872 ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); 3873 // Set the layout direction flags depending on the value of the attribute 3874 final int layoutDirection = a.getInt(attr, -1); 3875 final int value = (layoutDirection != -1) ? 3876 LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; 3877 mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); 3878 break; 3879 case com.android.internal.R.styleable.View_drawingCacheQuality: 3880 final int cacheQuality = a.getInt(attr, 0); 3881 if (cacheQuality != 0) { 3882 viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; 3883 viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK; 3884 } 3885 break; 3886 case com.android.internal.R.styleable.View_contentDescription: 3887 setContentDescription(a.getString(attr)); 3888 break; 3889 case com.android.internal.R.styleable.View_labelFor: 3890 setLabelFor(a.getResourceId(attr, NO_ID)); 3891 break; 3892 case com.android.internal.R.styleable.View_soundEffectsEnabled: 3893 if (!a.getBoolean(attr, true)) { 3894 viewFlagValues &= ~SOUND_EFFECTS_ENABLED; 3895 viewFlagMasks |= SOUND_EFFECTS_ENABLED; 3896 } 3897 break; 3898 case com.android.internal.R.styleable.View_hapticFeedbackEnabled: 3899 if (!a.getBoolean(attr, true)) { 3900 viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED; 3901 viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED; 3902 } 3903 break; 3904 case R.styleable.View_scrollbars: 3905 final int scrollbars = a.getInt(attr, SCROLLBARS_NONE); 3906 if (scrollbars != SCROLLBARS_NONE) { 3907 viewFlagValues |= scrollbars; 3908 viewFlagMasks |= SCROLLBARS_MASK; 3909 initializeScrollbars = true; 3910 } 3911 break; 3912 //noinspection deprecation 3913 case R.styleable.View_fadingEdge: 3914 if (targetSdkVersion >= ICE_CREAM_SANDWICH) { 3915 // Ignore the attribute starting with ICS 3916 break; 3917 } 3918 // With builds < ICS, fall through and apply fading edges 3919 case R.styleable.View_requiresFadingEdge: 3920 final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE); 3921 if (fadingEdge != FADING_EDGE_NONE) { 3922 viewFlagValues |= fadingEdge; 3923 viewFlagMasks |= FADING_EDGE_MASK; 3924 initializeFadingEdgeInternal(a); 3925 } 3926 break; 3927 case R.styleable.View_scrollbarStyle: 3928 scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY); 3929 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 3930 viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK; 3931 viewFlagMasks |= SCROLLBARS_STYLE_MASK; 3932 } 3933 break; 3934 case R.styleable.View_isScrollContainer: 3935 setScrollContainer = true; 3936 if (a.getBoolean(attr, false)) { 3937 setScrollContainer(true); 3938 } 3939 break; 3940 case com.android.internal.R.styleable.View_keepScreenOn: 3941 if (a.getBoolean(attr, false)) { 3942 viewFlagValues |= KEEP_SCREEN_ON; 3943 viewFlagMasks |= KEEP_SCREEN_ON; 3944 } 3945 break; 3946 case R.styleable.View_filterTouchesWhenObscured: 3947 if (a.getBoolean(attr, false)) { 3948 viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED; 3949 viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED; 3950 } 3951 break; 3952 case R.styleable.View_nextFocusLeft: 3953 mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); 3954 break; 3955 case R.styleable.View_nextFocusRight: 3956 mNextFocusRightId = a.getResourceId(attr, View.NO_ID); 3957 break; 3958 case R.styleable.View_nextFocusUp: 3959 mNextFocusUpId = a.getResourceId(attr, View.NO_ID); 3960 break; 3961 case R.styleable.View_nextFocusDown: 3962 mNextFocusDownId = a.getResourceId(attr, View.NO_ID); 3963 break; 3964 case R.styleable.View_nextFocusForward: 3965 mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); 3966 break; 3967 case R.styleable.View_minWidth: 3968 mMinWidth = a.getDimensionPixelSize(attr, 0); 3969 break; 3970 case R.styleable.View_minHeight: 3971 mMinHeight = a.getDimensionPixelSize(attr, 0); 3972 break; 3973 case R.styleable.View_onClick: 3974 if (context.isRestricted()) { 3975 throw new IllegalStateException("The android:onClick attribute cannot " 3976 + "be used within a restricted context"); 3977 } 3978 3979 final String handlerName = a.getString(attr); 3980 if (handlerName != null) { 3981 setOnClickListener(new OnClickListener() { 3982 private Method mHandler; 3983 3984 public void onClick(View v) { 3985 if (mHandler == null) { 3986 try { 3987 mHandler = getContext().getClass().getMethod(handlerName, 3988 View.class); 3989 } catch (NoSuchMethodException e) { 3990 int id = getId(); 3991 String idText = id == NO_ID ? "" : " with id '" 3992 + getContext().getResources().getResourceEntryName( 3993 id) + "'"; 3994 throw new IllegalStateException("Could not find a method " + 3995 handlerName + "(View) in the activity " 3996 + getContext().getClass() + " for onClick handler" 3997 + " on view " + View.this.getClass() + idText, e); 3998 } 3999 } 4000 4001 try { 4002 mHandler.invoke(getContext(), View.this); 4003 } catch (IllegalAccessException e) { 4004 throw new IllegalStateException("Could not execute non " 4005 + "public method of the activity", e); 4006 } catch (InvocationTargetException e) { 4007 throw new IllegalStateException("Could not execute " 4008 + "method of the activity", e); 4009 } 4010 } 4011 }); 4012 } 4013 break; 4014 case R.styleable.View_overScrollMode: 4015 overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS); 4016 break; 4017 case R.styleable.View_verticalScrollbarPosition: 4018 mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); 4019 break; 4020 case R.styleable.View_layerType: 4021 setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null); 4022 break; 4023 case R.styleable.View_textDirection: 4024 // Clear any text direction flag already set 4025 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 4026 // Set the text direction flags depending on the value of the attribute 4027 final int textDirection = a.getInt(attr, -1); 4028 if (textDirection != -1) { 4029 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; 4030 } 4031 break; 4032 case R.styleable.View_textAlignment: 4033 // Clear any text alignment flag already set 4034 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 4035 // Set the text alignment flag depending on the value of the attribute 4036 final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); 4037 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; 4038 break; 4039 case R.styleable.View_importantForAccessibility: 4040 setImportantForAccessibility(a.getInt(attr, 4041 IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); 4042 break; 4043 case R.styleable.View_accessibilityLiveRegion: 4044 setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); 4045 break; 4046 case R.styleable.View_transitionName: 4047 setTransitionName(a.getString(attr)); 4048 break; 4049 case R.styleable.View_nestedScrollingEnabled: 4050 setNestedScrollingEnabled(a.getBoolean(attr, false)); 4051 break; 4052 case R.styleable.View_stateListAnimator: 4053 setStateListAnimator(AnimatorInflater.loadStateListAnimator(context, 4054 a.getResourceId(attr, 0))); 4055 break; 4056 case R.styleable.View_backgroundTint: 4057 // This will get applied later during setBackground(). 4058 if (mBackgroundTint == null) { 4059 mBackgroundTint = new TintInfo(); 4060 } 4061 mBackgroundTint.mTintList = a.getColorStateList( 4062 R.styleable.View_backgroundTint); 4063 mBackgroundTint.mHasTintList = true; 4064 break; 4065 case R.styleable.View_backgroundTintMode: 4066 // This will get applied later during setBackground(). 4067 if (mBackgroundTint == null) { 4068 mBackgroundTint = new TintInfo(); 4069 } 4070 mBackgroundTint.mTintMode = Drawable.parseTintMode(a.getInt( 4071 R.styleable.View_backgroundTintMode, -1), null); 4072 mBackgroundTint.mHasTintMode = true; 4073 break; 4074 case R.styleable.View_outlineProvider: 4075 setOutlineProviderFromAttribute(a.getInt(R.styleable.View_outlineProvider, 4076 PROVIDER_BACKGROUND)); 4077 break; 4078 } 4079 } 4080 4081 setOverScrollMode(overScrollMode); 4082 4083 // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet 4084 // the resolved layout direction). Those cached values will be used later during padding 4085 // resolution. 4086 mUserPaddingStart = startPadding; 4087 mUserPaddingEnd = endPadding; 4088 4089 if (background != null) { 4090 setBackground(background); 4091 } 4092 4093 // setBackground above will record that padding is currently provided by the background. 4094 // If we have padding specified via xml, record that here instead and use it. 4095 mLeftPaddingDefined = leftPaddingDefined; 4096 mRightPaddingDefined = rightPaddingDefined; 4097 4098 if (padding >= 0) { 4099 leftPadding = padding; 4100 topPadding = padding; 4101 rightPadding = padding; 4102 bottomPadding = padding; 4103 mUserPaddingLeftInitial = padding; 4104 mUserPaddingRightInitial = padding; 4105 } 4106 4107 if (isRtlCompatibilityMode()) { 4108 // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. 4109 // left / right padding are used if defined (meaning here nothing to do). If they are not 4110 // defined and start / end padding are defined (e.g. in Frameworks resources), then we use 4111 // start / end and resolve them as left / right (layout direction is not taken into account). 4112 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4113 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4114 // defined. 4115 if (!mLeftPaddingDefined && startPaddingDefined) { 4116 leftPadding = startPadding; 4117 } 4118 mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial; 4119 if (!mRightPaddingDefined && endPaddingDefined) { 4120 rightPadding = endPadding; 4121 } 4122 mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial; 4123 } else { 4124 // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right 4125 // values defined. Otherwise, left /right values are used. 4126 // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial 4127 // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if 4128 // defined. 4129 final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined; 4130 4131 if (mLeftPaddingDefined && !hasRelativePadding) { 4132 mUserPaddingLeftInitial = leftPadding; 4133 } 4134 if (mRightPaddingDefined && !hasRelativePadding) { 4135 mUserPaddingRightInitial = rightPadding; 4136 } 4137 } 4138 4139 internalSetPadding( 4140 mUserPaddingLeftInitial, 4141 topPadding >= 0 ? topPadding : mPaddingTop, 4142 mUserPaddingRightInitial, 4143 bottomPadding >= 0 ? bottomPadding : mPaddingBottom); 4144 4145 if (viewFlagMasks != 0) { 4146 setFlags(viewFlagValues, viewFlagMasks); 4147 } 4148 4149 if (initializeScrollbars) { 4150 initializeScrollbarsInternal(a); 4151 } 4152 4153 a.recycle(); 4154 4155 // Needs to be called after mViewFlags is set 4156 if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) { 4157 recomputePadding(); 4158 } 4159 4160 if (x != 0 || y != 0) { 4161 scrollTo(x, y); 4162 } 4163 4164 if (transformSet) { 4165 setTranslationX(tx); 4166 setTranslationY(ty); 4167 setTranslationZ(tz); 4168 setElevation(elevation); 4169 setRotation(rotation); 4170 setRotationX(rotationX); 4171 setRotationY(rotationY); 4172 setScaleX(sx); 4173 setScaleY(sy); 4174 } 4175 4176 if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) { 4177 setScrollContainer(true); 4178 } 4179 4180 computeOpaqueFlags(); 4181 } 4182 4183 /** 4184 * Non-public constructor for use in testing 4185 */ 4186 View() { 4187 mResources = null; 4188 mRenderNode = RenderNode.create(getClass().getName(), this); 4189 } 4190 4191 private static SparseArray<String> getAttributeMap() { 4192 if (mAttributeMap == null) { 4193 mAttributeMap = new SparseArray<String>(); 4194 } 4195 return mAttributeMap; 4196 } 4197 4198 private void saveAttributeData(AttributeSet attrs, TypedArray a) { 4199 int length = ((attrs == null ? 0 : attrs.getAttributeCount()) + a.getIndexCount()) * 2; 4200 mAttributes = new String[length]; 4201 4202 int i = 0; 4203 if (attrs != null) { 4204 for (i = 0; i < attrs.getAttributeCount(); i += 2) { 4205 mAttributes[i] = attrs.getAttributeName(i); 4206 mAttributes[i + 1] = attrs.getAttributeValue(i); 4207 } 4208 4209 } 4210 4211 SparseArray<String> attributeMap = getAttributeMap(); 4212 for (int j = 0; j < a.length(); ++j) { 4213 if (a.hasValue(j)) { 4214 try { 4215 int resourceId = a.getResourceId(j, 0); 4216 if (resourceId == 0) { 4217 continue; 4218 } 4219 4220 String resourceName = attributeMap.get(resourceId); 4221 if (resourceName == null) { 4222 resourceName = a.getResources().getResourceName(resourceId); 4223 attributeMap.put(resourceId, resourceName); 4224 } 4225 4226 mAttributes[i] = resourceName; 4227 mAttributes[i + 1] = a.getText(j).toString(); 4228 i += 2; 4229 } catch (Resources.NotFoundException e) { 4230 // if we can't get the resource name, we just ignore it 4231 } 4232 } 4233 } 4234 } 4235 4236 public String toString() { 4237 StringBuilder out = new StringBuilder(128); 4238 out.append(getClass().getName()); 4239 out.append('{'); 4240 out.append(Integer.toHexString(System.identityHashCode(this))); 4241 out.append(' '); 4242 switch (mViewFlags&VISIBILITY_MASK) { 4243 case VISIBLE: out.append('V'); break; 4244 case INVISIBLE: out.append('I'); break; 4245 case GONE: out.append('G'); break; 4246 default: out.append('.'); break; 4247 } 4248 out.append((mViewFlags&FOCUSABLE_MASK) == FOCUSABLE ? 'F' : '.'); 4249 out.append((mViewFlags&ENABLED_MASK) == ENABLED ? 'E' : '.'); 4250 out.append((mViewFlags&DRAW_MASK) == WILL_NOT_DRAW ? '.' : 'D'); 4251 out.append((mViewFlags&SCROLLBARS_HORIZONTAL) != 0 ? 'H' : '.'); 4252 out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.'); 4253 out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.'); 4254 out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.'); 4255 out.append(' '); 4256 out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.'); 4257 out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.'); 4258 out.append((mPrivateFlags&PFLAG_SELECTED) != 0 ? 'S' : '.'); 4259 if ((mPrivateFlags&PFLAG_PREPRESSED) != 0) { 4260 out.append('p'); 4261 } else { 4262 out.append((mPrivateFlags&PFLAG_PRESSED) != 0 ? 'P' : '.'); 4263 } 4264 out.append((mPrivateFlags&PFLAG_HOVERED) != 0 ? 'H' : '.'); 4265 out.append((mPrivateFlags&PFLAG_ACTIVATED) != 0 ? 'A' : '.'); 4266 out.append((mPrivateFlags&PFLAG_INVALIDATED) != 0 ? 'I' : '.'); 4267 out.append((mPrivateFlags&PFLAG_DIRTY_MASK) != 0 ? 'D' : '.'); 4268 out.append(' '); 4269 out.append(mLeft); 4270 out.append(','); 4271 out.append(mTop); 4272 out.append('-'); 4273 out.append(mRight); 4274 out.append(','); 4275 out.append(mBottom); 4276 final int id = getId(); 4277 if (id != NO_ID) { 4278 out.append(" #"); 4279 out.append(Integer.toHexString(id)); 4280 final Resources r = mResources; 4281 if (Resources.resourceHasPackage(id) && r != null) { 4282 try { 4283 String pkgname; 4284 switch (id&0xff000000) { 4285 case 0x7f000000: 4286 pkgname="app"; 4287 break; 4288 case 0x01000000: 4289 pkgname="android"; 4290 break; 4291 default: 4292 pkgname = r.getResourcePackageName(id); 4293 break; 4294 } 4295 String typename = r.getResourceTypeName(id); 4296 String entryname = r.getResourceEntryName(id); 4297 out.append(" "); 4298 out.append(pkgname); 4299 out.append(":"); 4300 out.append(typename); 4301 out.append("/"); 4302 out.append(entryname); 4303 } catch (Resources.NotFoundException e) { 4304 } 4305 } 4306 } 4307 out.append("}"); 4308 return out.toString(); 4309 } 4310 4311 /** 4312 * <p> 4313 * Initializes the fading edges from a given set of styled attributes. This 4314 * method should be called by subclasses that need fading edges and when an 4315 * instance of these subclasses is created programmatically rather than 4316 * being inflated from XML. This method is automatically called when the XML 4317 * is inflated. 4318 * </p> 4319 * 4320 * @param a the styled attributes set to initialize the fading edges from 4321 * 4322 * @removed 4323 */ 4324 protected void initializeFadingEdge(TypedArray a) { 4325 // This method probably shouldn't have been included in the SDK to begin with. 4326 // It relies on 'a' having been initialized using an attribute filter array that is 4327 // not publicly available to the SDK. The old method has been renamed 4328 // to initializeFadingEdgeInternal and hidden for framework use only; 4329 // this one initializes using defaults to make it safe to call for apps. 4330 4331 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4332 4333 initializeFadingEdgeInternal(arr); 4334 4335 arr.recycle(); 4336 } 4337 4338 /** 4339 * <p> 4340 * Initializes the fading edges from a given set of styled attributes. This 4341 * method should be called by subclasses that need fading edges and when an 4342 * instance of these subclasses is created programmatically rather than 4343 * being inflated from XML. This method is automatically called when the XML 4344 * is inflated. 4345 * </p> 4346 * 4347 * @param a the styled attributes set to initialize the fading edges from 4348 * @hide This is the real method; the public one is shimmed to be safe to call from apps. 4349 */ 4350 protected void initializeFadingEdgeInternal(TypedArray a) { 4351 initScrollCache(); 4352 4353 mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( 4354 R.styleable.View_fadingEdgeLength, 4355 ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); 4356 } 4357 4358 /** 4359 * Returns the size of the vertical faded edges used to indicate that more 4360 * content in this view is visible. 4361 * 4362 * @return The size in pixels of the vertical faded edge or 0 if vertical 4363 * faded edges are not enabled for this view. 4364 * @attr ref android.R.styleable#View_fadingEdgeLength 4365 */ 4366 public int getVerticalFadingEdgeLength() { 4367 if (isVerticalFadingEdgeEnabled()) { 4368 ScrollabilityCache cache = mScrollCache; 4369 if (cache != null) { 4370 return cache.fadingEdgeLength; 4371 } 4372 } 4373 return 0; 4374 } 4375 4376 /** 4377 * Set the size of the faded edge used to indicate that more content in this 4378 * view is available. Will not change whether the fading edge is enabled; use 4379 * {@link #setVerticalFadingEdgeEnabled(boolean)} or 4380 * {@link #setHorizontalFadingEdgeEnabled(boolean)} to enable the fading edge 4381 * for the vertical or horizontal fading edges. 4382 * 4383 * @param length The size in pixels of the faded edge used to indicate that more 4384 * content in this view is visible. 4385 */ 4386 public void setFadingEdgeLength(int length) { 4387 initScrollCache(); 4388 mScrollCache.fadingEdgeLength = length; 4389 } 4390 4391 /** 4392 * Returns the size of the horizontal faded edges used to indicate that more 4393 * content in this view is visible. 4394 * 4395 * @return The size in pixels of the horizontal faded edge or 0 if horizontal 4396 * faded edges are not enabled for this view. 4397 * @attr ref android.R.styleable#View_fadingEdgeLength 4398 */ 4399 public int getHorizontalFadingEdgeLength() { 4400 if (isHorizontalFadingEdgeEnabled()) { 4401 ScrollabilityCache cache = mScrollCache; 4402 if (cache != null) { 4403 return cache.fadingEdgeLength; 4404 } 4405 } 4406 return 0; 4407 } 4408 4409 /** 4410 * Returns the width of the vertical scrollbar. 4411 * 4412 * @return The width in pixels of the vertical scrollbar or 0 if there 4413 * is no vertical scrollbar. 4414 */ 4415 public int getVerticalScrollbarWidth() { 4416 ScrollabilityCache cache = mScrollCache; 4417 if (cache != null) { 4418 ScrollBarDrawable scrollBar = cache.scrollBar; 4419 if (scrollBar != null) { 4420 int size = scrollBar.getSize(true); 4421 if (size <= 0) { 4422 size = cache.scrollBarSize; 4423 } 4424 return size; 4425 } 4426 return 0; 4427 } 4428 return 0; 4429 } 4430 4431 /** 4432 * Returns the height of the horizontal scrollbar. 4433 * 4434 * @return The height in pixels of the horizontal scrollbar or 0 if 4435 * there is no horizontal scrollbar. 4436 */ 4437 protected int getHorizontalScrollbarHeight() { 4438 ScrollabilityCache cache = mScrollCache; 4439 if (cache != null) { 4440 ScrollBarDrawable scrollBar = cache.scrollBar; 4441 if (scrollBar != null) { 4442 int size = scrollBar.getSize(false); 4443 if (size <= 0) { 4444 size = cache.scrollBarSize; 4445 } 4446 return size; 4447 } 4448 return 0; 4449 } 4450 return 0; 4451 } 4452 4453 /** 4454 * <p> 4455 * Initializes the scrollbars from a given set of styled attributes. This 4456 * method should be called by subclasses that need scrollbars and when an 4457 * instance of these subclasses is created programmatically rather than 4458 * being inflated from XML. This method is automatically called when the XML 4459 * is inflated. 4460 * </p> 4461 * 4462 * @param a the styled attributes set to initialize the scrollbars from 4463 * 4464 * @removed 4465 */ 4466 protected void initializeScrollbars(TypedArray a) { 4467 // It's not safe to use this method from apps. The parameter 'a' must have been obtained 4468 // using the View filter array which is not available to the SDK. As such, internal 4469 // framework usage now uses initializeScrollbarsInternal and we grab a default 4470 // TypedArray with the right filter instead here. 4471 TypedArray arr = mContext.obtainStyledAttributes(com.android.internal.R.styleable.View); 4472 4473 initializeScrollbarsInternal(arr); 4474 4475 // We ignored the method parameter. Recycle the one we actually did use. 4476 arr.recycle(); 4477 } 4478 4479 /** 4480 * <p> 4481 * Initializes the scrollbars from a given set of styled attributes. This 4482 * method should be called by subclasses that need scrollbars and when an 4483 * instance of these subclasses is created programmatically rather than 4484 * being inflated from XML. This method is automatically called when the XML 4485 * is inflated. 4486 * </p> 4487 * 4488 * @param a the styled attributes set to initialize the scrollbars from 4489 * @hide 4490 */ 4491 protected void initializeScrollbarsInternal(TypedArray a) { 4492 initScrollCache(); 4493 4494 final ScrollabilityCache scrollabilityCache = mScrollCache; 4495 4496 if (scrollabilityCache.scrollBar == null) { 4497 scrollabilityCache.scrollBar = new ScrollBarDrawable(); 4498 } 4499 4500 final boolean fadeScrollbars = a.getBoolean(R.styleable.View_fadeScrollbars, true); 4501 4502 if (!fadeScrollbars) { 4503 scrollabilityCache.state = ScrollabilityCache.ON; 4504 } 4505 scrollabilityCache.fadeScrollBars = fadeScrollbars; 4506 4507 4508 scrollabilityCache.scrollBarFadeDuration = a.getInt( 4509 R.styleable.View_scrollbarFadeDuration, ViewConfiguration 4510 .getScrollBarFadeDuration()); 4511 scrollabilityCache.scrollBarDefaultDelayBeforeFade = a.getInt( 4512 R.styleable.View_scrollbarDefaultDelayBeforeFade, 4513 ViewConfiguration.getScrollDefaultDelay()); 4514 4515 4516 scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( 4517 com.android.internal.R.styleable.View_scrollbarSize, 4518 ViewConfiguration.get(mContext).getScaledScrollBarSize()); 4519 4520 Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); 4521 scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); 4522 4523 Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); 4524 if (thumb != null) { 4525 scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); 4526 } 4527 4528 boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, 4529 false); 4530 if (alwaysDraw) { 4531 scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); 4532 } 4533 4534 track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); 4535 scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); 4536 4537 thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); 4538 if (thumb != null) { 4539 scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); 4540 } 4541 4542 alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, 4543 false); 4544 if (alwaysDraw) { 4545 scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); 4546 } 4547 4548 // Apply layout direction to the new Drawables if needed 4549 final int layoutDirection = getLayoutDirection(); 4550 if (track != null) { 4551 track.setLayoutDirection(layoutDirection); 4552 } 4553 if (thumb != null) { 4554 thumb.setLayoutDirection(layoutDirection); 4555 } 4556 4557 // Re-apply user/background padding so that scrollbar(s) get added 4558 resolvePadding(); 4559 } 4560 4561 /** 4562 * <p> 4563 * Initalizes the scrollability cache if necessary. 4564 * </p> 4565 */ 4566 private void initScrollCache() { 4567 if (mScrollCache == null) { 4568 mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext), this); 4569 } 4570 } 4571 4572 private ScrollabilityCache getScrollCache() { 4573 initScrollCache(); 4574 return mScrollCache; 4575 } 4576 4577 /** 4578 * Set the position of the vertical scroll bar. Should be one of 4579 * {@link #SCROLLBAR_POSITION_DEFAULT}, {@link #SCROLLBAR_POSITION_LEFT} or 4580 * {@link #SCROLLBAR_POSITION_RIGHT}. 4581 * 4582 * @param position Where the vertical scroll bar should be positioned. 4583 */ 4584 public void setVerticalScrollbarPosition(int position) { 4585 if (mVerticalScrollbarPosition != position) { 4586 mVerticalScrollbarPosition = position; 4587 computeOpaqueFlags(); 4588 resolvePadding(); 4589 } 4590 } 4591 4592 /** 4593 * @return The position where the vertical scroll bar will show, if applicable. 4594 * @see #setVerticalScrollbarPosition(int) 4595 */ 4596 public int getVerticalScrollbarPosition() { 4597 return mVerticalScrollbarPosition; 4598 } 4599 4600 ListenerInfo getListenerInfo() { 4601 if (mListenerInfo != null) { 4602 return mListenerInfo; 4603 } 4604 mListenerInfo = new ListenerInfo(); 4605 return mListenerInfo; 4606 } 4607 4608 /** 4609 * Register a callback to be invoked when focus of this view changed. 4610 * 4611 * @param l The callback that will run. 4612 */ 4613 public void setOnFocusChangeListener(OnFocusChangeListener l) { 4614 getListenerInfo().mOnFocusChangeListener = l; 4615 } 4616 4617 /** 4618 * Add a listener that will be called when the bounds of the view change due to 4619 * layout processing. 4620 * 4621 * @param listener The listener that will be called when layout bounds change. 4622 */ 4623 public void addOnLayoutChangeListener(OnLayoutChangeListener listener) { 4624 ListenerInfo li = getListenerInfo(); 4625 if (li.mOnLayoutChangeListeners == null) { 4626 li.mOnLayoutChangeListeners = new ArrayList<OnLayoutChangeListener>(); 4627 } 4628 if (!li.mOnLayoutChangeListeners.contains(listener)) { 4629 li.mOnLayoutChangeListeners.add(listener); 4630 } 4631 } 4632 4633 /** 4634 * Remove a listener for layout changes. 4635 * 4636 * @param listener The listener for layout bounds change. 4637 */ 4638 public void removeOnLayoutChangeListener(OnLayoutChangeListener listener) { 4639 ListenerInfo li = mListenerInfo; 4640 if (li == null || li.mOnLayoutChangeListeners == null) { 4641 return; 4642 } 4643 li.mOnLayoutChangeListeners.remove(listener); 4644 } 4645 4646 /** 4647 * Add a listener for attach state changes. 4648 * 4649 * This listener will be called whenever this view is attached or detached 4650 * from a window. Remove the listener using 4651 * {@link #removeOnAttachStateChangeListener(OnAttachStateChangeListener)}. 4652 * 4653 * @param listener Listener to attach 4654 * @see #removeOnAttachStateChangeListener(OnAttachStateChangeListener) 4655 */ 4656 public void addOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4657 ListenerInfo li = getListenerInfo(); 4658 if (li.mOnAttachStateChangeListeners == null) { 4659 li.mOnAttachStateChangeListeners 4660 = new CopyOnWriteArrayList<OnAttachStateChangeListener>(); 4661 } 4662 li.mOnAttachStateChangeListeners.add(listener); 4663 } 4664 4665 /** 4666 * Remove a listener for attach state changes. The listener will receive no further 4667 * notification of window attach/detach events. 4668 * 4669 * @param listener Listener to remove 4670 * @see #addOnAttachStateChangeListener(OnAttachStateChangeListener) 4671 */ 4672 public void removeOnAttachStateChangeListener(OnAttachStateChangeListener listener) { 4673 ListenerInfo li = mListenerInfo; 4674 if (li == null || li.mOnAttachStateChangeListeners == null) { 4675 return; 4676 } 4677 li.mOnAttachStateChangeListeners.remove(listener); 4678 } 4679 4680 /** 4681 * Returns the focus-change callback registered for this view. 4682 * 4683 * @return The callback, or null if one is not registered. 4684 */ 4685 public OnFocusChangeListener getOnFocusChangeListener() { 4686 ListenerInfo li = mListenerInfo; 4687 return li != null ? li.mOnFocusChangeListener : null; 4688 } 4689 4690 /** 4691 * Register a callback to be invoked when this view is clicked. If this view is not 4692 * clickable, it becomes clickable. 4693 * 4694 * @param l The callback that will run 4695 * 4696 * @see #setClickable(boolean) 4697 */ 4698 public void setOnClickListener(OnClickListener l) { 4699 if (!isClickable()) { 4700 setClickable(true); 4701 } 4702 getListenerInfo().mOnClickListener = l; 4703 } 4704 4705 /** 4706 * Return whether this view has an attached OnClickListener. Returns 4707 * true if there is a listener, false if there is none. 4708 */ 4709 public boolean hasOnClickListeners() { 4710 ListenerInfo li = mListenerInfo; 4711 return (li != null && li.mOnClickListener != null); 4712 } 4713 4714 /** 4715 * Register a callback to be invoked when this view is clicked and held. If this view is not 4716 * long clickable, it becomes long clickable. 4717 * 4718 * @param l The callback that will run 4719 * 4720 * @see #setLongClickable(boolean) 4721 */ 4722 public void setOnLongClickListener(OnLongClickListener l) { 4723 if (!isLongClickable()) { 4724 setLongClickable(true); 4725 } 4726 getListenerInfo().mOnLongClickListener = l; 4727 } 4728 4729 /** 4730 * Register a callback to be invoked when the context menu for this view is 4731 * being built. If this view is not long clickable, it becomes long clickable. 4732 * 4733 * @param l The callback that will run 4734 * 4735 */ 4736 public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) { 4737 if (!isLongClickable()) { 4738 setLongClickable(true); 4739 } 4740 getListenerInfo().mOnCreateContextMenuListener = l; 4741 } 4742 4743 /** 4744 * Call this view's OnClickListener, if it is defined. Performs all normal 4745 * actions associated with clicking: reporting accessibility event, playing 4746 * a sound, etc. 4747 * 4748 * @return True there was an assigned OnClickListener that was called, false 4749 * otherwise is returned. 4750 */ 4751 public boolean performClick() { 4752 final boolean result; 4753 final ListenerInfo li = mListenerInfo; 4754 if (li != null && li.mOnClickListener != null) { 4755 playSoundEffect(SoundEffectConstants.CLICK); 4756 li.mOnClickListener.onClick(this); 4757 result = true; 4758 } else { 4759 result = false; 4760 } 4761 4762 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); 4763 return result; 4764 } 4765 4766 /** 4767 * Directly call any attached OnClickListener. Unlike {@link #performClick()}, 4768 * this only calls the listener, and does not do any associated clicking 4769 * actions like reporting an accessibility event. 4770 * 4771 * @return True there was an assigned OnClickListener that was called, false 4772 * otherwise is returned. 4773 */ 4774 public boolean callOnClick() { 4775 ListenerInfo li = mListenerInfo; 4776 if (li != null && li.mOnClickListener != null) { 4777 li.mOnClickListener.onClick(this); 4778 return true; 4779 } 4780 return false; 4781 } 4782 4783 /** 4784 * Call this view's OnLongClickListener, if it is defined. Invokes the context menu if the 4785 * OnLongClickListener did not consume the event. 4786 * 4787 * @return True if one of the above receivers consumed the event, false otherwise. 4788 */ 4789 public boolean performLongClick() { 4790 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED); 4791 4792 boolean handled = false; 4793 ListenerInfo li = mListenerInfo; 4794 if (li != null && li.mOnLongClickListener != null) { 4795 handled = li.mOnLongClickListener.onLongClick(View.this); 4796 } 4797 if (!handled) { 4798 handled = showContextMenu(); 4799 } 4800 if (handled) { 4801 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 4802 } 4803 return handled; 4804 } 4805 4806 /** 4807 * Performs button-related actions during a touch down event. 4808 * 4809 * @param event The event. 4810 * @return True if the down was consumed. 4811 * 4812 * @hide 4813 */ 4814 protected boolean performButtonActionOnTouchDown(MotionEvent event) { 4815 if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { 4816 if (showContextMenu(event.getX(), event.getY(), event.getMetaState())) { 4817 return true; 4818 } 4819 } 4820 return false; 4821 } 4822 4823 /** 4824 * Bring up the context menu for this view. 4825 * 4826 * @return Whether a context menu was displayed. 4827 */ 4828 public boolean showContextMenu() { 4829 return getParent().showContextMenuForChild(this); 4830 } 4831 4832 /** 4833 * Bring up the context menu for this view, referring to the item under the specified point. 4834 * 4835 * @param x The referenced x coordinate. 4836 * @param y The referenced y coordinate. 4837 * @param metaState The keyboard modifiers that were pressed. 4838 * @return Whether a context menu was displayed. 4839 * 4840 * @hide 4841 */ 4842 public boolean showContextMenu(float x, float y, int metaState) { 4843 return showContextMenu(); 4844 } 4845 4846 /** 4847 * Start an action mode. 4848 * 4849 * @param callback Callback that will control the lifecycle of the action mode 4850 * @return The new action mode if it is started, null otherwise 4851 * 4852 * @see ActionMode 4853 */ 4854 public ActionMode startActionMode(ActionMode.Callback callback) { 4855 ViewParent parent = getParent(); 4856 if (parent == null) return null; 4857 return parent.startActionModeForChild(this, callback); 4858 } 4859 4860 /** 4861 * Register a callback to be invoked when a hardware key is pressed in this view. 4862 * Key presses in software input methods will generally not trigger the methods of 4863 * this listener. 4864 * @param l the key listener to attach to this view 4865 */ 4866 public void setOnKeyListener(OnKeyListener l) { 4867 getListenerInfo().mOnKeyListener = l; 4868 } 4869 4870 /** 4871 * Register a callback to be invoked when a touch event is sent to this view. 4872 * @param l the touch listener to attach to this view 4873 */ 4874 public void setOnTouchListener(OnTouchListener l) { 4875 getListenerInfo().mOnTouchListener = l; 4876 } 4877 4878 /** 4879 * Register a callback to be invoked when a generic motion event is sent to this view. 4880 * @param l the generic motion listener to attach to this view 4881 */ 4882 public void setOnGenericMotionListener(OnGenericMotionListener l) { 4883 getListenerInfo().mOnGenericMotionListener = l; 4884 } 4885 4886 /** 4887 * Register a callback to be invoked when a hover event is sent to this view. 4888 * @param l the hover listener to attach to this view 4889 */ 4890 public void setOnHoverListener(OnHoverListener l) { 4891 getListenerInfo().mOnHoverListener = l; 4892 } 4893 4894 /** 4895 * Register a drag event listener callback object for this View. The parameter is 4896 * an implementation of {@link android.view.View.OnDragListener}. To send a drag event to a 4897 * View, the system calls the 4898 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent)} method. 4899 * @param l An implementation of {@link android.view.View.OnDragListener}. 4900 */ 4901 public void setOnDragListener(OnDragListener l) { 4902 getListenerInfo().mOnDragListener = l; 4903 } 4904 4905 /** 4906 * Give this view focus. This will cause 4907 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} to be called. 4908 * 4909 * Note: this does not check whether this {@link View} should get focus, it just 4910 * gives it focus no matter what. It should only be called internally by framework 4911 * code that knows what it is doing, namely {@link #requestFocus(int, Rect)}. 4912 * 4913 * @param direction values are {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 4914 * {@link View#FOCUS_LEFT} or {@link View#FOCUS_RIGHT}. This is the direction which 4915 * focus moved when requestFocus() is called. It may not always 4916 * apply, in which case use the default View.FOCUS_DOWN. 4917 * @param previouslyFocusedRect The rectangle of the view that had focus 4918 * prior in this View's coordinate system. 4919 */ 4920 void handleFocusGainInternal(@FocusRealDirection int direction, Rect previouslyFocusedRect) { 4921 if (DBG) { 4922 System.out.println(this + " requestFocus()"); 4923 } 4924 4925 if ((mPrivateFlags & PFLAG_FOCUSED) == 0) { 4926 mPrivateFlags |= PFLAG_FOCUSED; 4927 4928 View oldFocus = (mAttachInfo != null) ? getRootView().findFocus() : null; 4929 4930 if (mParent != null) { 4931 mParent.requestChildFocus(this, this); 4932 } 4933 4934 if (mAttachInfo != null) { 4935 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); 4936 } 4937 4938 onFocusChanged(true, direction, previouslyFocusedRect); 4939 refreshDrawableState(); 4940 } 4941 } 4942 4943 /** 4944 * Populates <code>outRect</code> with the hotspot bounds. By default, 4945 * the hotspot bounds are identical to the screen bounds. 4946 * 4947 * @param outRect rect to populate with hotspot bounds 4948 * @hide Only for internal use by views and widgets. 4949 */ 4950 public void getHotspotBounds(Rect outRect) { 4951 final Drawable background = getBackground(); 4952 if (background != null) { 4953 background.getHotspotBounds(outRect); 4954 } else { 4955 getBoundsOnScreen(outRect); 4956 } 4957 } 4958 4959 /** 4960 * Request that a rectangle of this view be visible on the screen, 4961 * scrolling if necessary just enough. 4962 * 4963 * <p>A View should call this if it maintains some notion of which part 4964 * of its content is interesting. For example, a text editing view 4965 * should call this when its cursor moves. 4966 * 4967 * @param rectangle The rectangle. 4968 * @return Whether any parent scrolled. 4969 */ 4970 public boolean requestRectangleOnScreen(Rect rectangle) { 4971 return requestRectangleOnScreen(rectangle, false); 4972 } 4973 4974 /** 4975 * Request that a rectangle of this view be visible on the screen, 4976 * scrolling if necessary just enough. 4977 * 4978 * <p>A View should call this if it maintains some notion of which part 4979 * of its content is interesting. For example, a text editing view 4980 * should call this when its cursor moves. 4981 * 4982 * <p>When <code>immediate</code> is set to true, scrolling will not be 4983 * animated. 4984 * 4985 * @param rectangle The rectangle. 4986 * @param immediate True to forbid animated scrolling, false otherwise 4987 * @return Whether any parent scrolled. 4988 */ 4989 public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) { 4990 if (mParent == null) { 4991 return false; 4992 } 4993 4994 View child = this; 4995 4996 RectF position = (mAttachInfo != null) ? mAttachInfo.mTmpTransformRect : new RectF(); 4997 position.set(rectangle); 4998 4999 ViewParent parent = mParent; 5000 boolean scrolled = false; 5001 while (parent != null) { 5002 rectangle.set((int) position.left, (int) position.top, 5003 (int) position.right, (int) position.bottom); 5004 5005 scrolled |= parent.requestChildRectangleOnScreen(child, 5006 rectangle, immediate); 5007 5008 if (!child.hasIdentityMatrix()) { 5009 child.getMatrix().mapRect(position); 5010 } 5011 5012 position.offset(child.mLeft, child.mTop); 5013 5014 if (!(parent instanceof View)) { 5015 break; 5016 } 5017 5018 View parentView = (View) parent; 5019 5020 position.offset(-parentView.getScrollX(), -parentView.getScrollY()); 5021 5022 child = parentView; 5023 parent = child.getParent(); 5024 } 5025 5026 return scrolled; 5027 } 5028 5029 /** 5030 * Called when this view wants to give up focus. If focus is cleared 5031 * {@link #onFocusChanged(boolean, int, android.graphics.Rect)} is called. 5032 * <p> 5033 * <strong>Note:</strong> When a View clears focus the framework is trying 5034 * to give focus to the first focusable View from the top. Hence, if this 5035 * View is the first from the top that can take focus, then all callbacks 5036 * related to clearing focus will be invoked after which the framework will 5037 * give focus to this view. 5038 * </p> 5039 */ 5040 public void clearFocus() { 5041 if (DBG) { 5042 System.out.println(this + " clearFocus()"); 5043 } 5044 5045 clearFocusInternal(null, true, true); 5046 } 5047 5048 /** 5049 * Clears focus from the view, optionally propagating the change up through 5050 * the parent hierarchy and requesting that the root view place new focus. 5051 * 5052 * @param propagate whether to propagate the change up through the parent 5053 * hierarchy 5054 * @param refocus when propagate is true, specifies whether to request the 5055 * root view place new focus 5056 */ 5057 void clearFocusInternal(View focused, boolean propagate, boolean refocus) { 5058 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 5059 mPrivateFlags &= ~PFLAG_FOCUSED; 5060 5061 if (propagate && mParent != null) { 5062 mParent.clearChildFocus(this); 5063 } 5064 5065 onFocusChanged(false, 0, null); 5066 refreshDrawableState(); 5067 5068 if (propagate && (!refocus || !rootViewRequestFocus())) { 5069 notifyGlobalFocusCleared(this); 5070 } 5071 } 5072 } 5073 5074 void notifyGlobalFocusCleared(View oldFocus) { 5075 if (oldFocus != null && mAttachInfo != null) { 5076 mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); 5077 } 5078 } 5079 5080 boolean rootViewRequestFocus() { 5081 final View root = getRootView(); 5082 return root != null && root.requestFocus(); 5083 } 5084 5085 /** 5086 * Called internally by the view system when a new view is getting focus. 5087 * This is what clears the old focus. 5088 * <p> 5089 * <b>NOTE:</b> The parent view's focused child must be updated manually 5090 * after calling this method. Otherwise, the view hierarchy may be left in 5091 * an inconstent state. 5092 */ 5093 void unFocus(View focused) { 5094 if (DBG) { 5095 System.out.println(this + " unFocus()"); 5096 } 5097 5098 clearFocusInternal(focused, false, false); 5099 } 5100 5101 /** 5102 * Returns true if this view has focus iteself, or is the ancestor of the 5103 * view that has focus. 5104 * 5105 * @return True if this view has or contains focus, false otherwise. 5106 */ 5107 @ViewDebug.ExportedProperty(category = "focus") 5108 public boolean hasFocus() { 5109 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 5110 } 5111 5112 /** 5113 * Returns true if this view is focusable or if it contains a reachable View 5114 * for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()" 5115 * is a View whose parents do not block descendants focus. 5116 * 5117 * Only {@link #VISIBLE} views are considered focusable. 5118 * 5119 * @return True if the view is focusable or if the view contains a focusable 5120 * View, false otherwise. 5121 * 5122 * @see ViewGroup#FOCUS_BLOCK_DESCENDANTS 5123 * @see ViewGroup#getTouchscreenBlocksFocus() 5124 */ 5125 public boolean hasFocusable() { 5126 if (!isFocusableInTouchMode()) { 5127 for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) { 5128 final ViewGroup g = (ViewGroup) p; 5129 if (g.shouldBlockFocusForTouchscreen()) { 5130 return false; 5131 } 5132 } 5133 } 5134 return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable(); 5135 } 5136 5137 /** 5138 * Called by the view system when the focus state of this view changes. 5139 * When the focus change event is caused by directional navigation, direction 5140 * and previouslyFocusedRect provide insight into where the focus is coming from. 5141 * When overriding, be sure to call up through to the super class so that 5142 * the standard focus handling will occur. 5143 * 5144 * @param gainFocus True if the View has focus; false otherwise. 5145 * @param direction The direction focus has moved when requestFocus() 5146 * is called to give this view focus. Values are 5147 * {@link #FOCUS_UP}, {@link #FOCUS_DOWN}, {@link #FOCUS_LEFT}, 5148 * {@link #FOCUS_RIGHT}, {@link #FOCUS_FORWARD}, or {@link #FOCUS_BACKWARD}. 5149 * It may not always apply, in which case use the default. 5150 * @param previouslyFocusedRect The rectangle, in this view's coordinate 5151 * system, of the previously focused view. If applicable, this will be 5152 * passed in as finer grained information about where the focus is coming 5153 * from (in addition to direction). Will be <code>null</code> otherwise. 5154 */ 5155 protected void onFocusChanged(boolean gainFocus, @FocusDirection int direction, 5156 @Nullable Rect previouslyFocusedRect) { 5157 if (gainFocus) { 5158 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED); 5159 } else { 5160 notifyViewAccessibilityStateChangedIfNeeded( 5161 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5162 } 5163 5164 InputMethodManager imm = InputMethodManager.peekInstance(); 5165 if (!gainFocus) { 5166 if (isPressed()) { 5167 setPressed(false); 5168 } 5169 if (imm != null && mAttachInfo != null 5170 && mAttachInfo.mHasWindowFocus) { 5171 imm.focusOut(this); 5172 } 5173 onFocusLost(); 5174 } else if (imm != null && mAttachInfo != null 5175 && mAttachInfo.mHasWindowFocus) { 5176 imm.focusIn(this); 5177 } 5178 5179 invalidate(true); 5180 ListenerInfo li = mListenerInfo; 5181 if (li != null && li.mOnFocusChangeListener != null) { 5182 li.mOnFocusChangeListener.onFocusChange(this, gainFocus); 5183 } 5184 5185 if (mAttachInfo != null) { 5186 mAttachInfo.mKeyDispatchState.reset(this); 5187 } 5188 } 5189 5190 /** 5191 * Sends an accessibility event of the given type. If accessibility is 5192 * not enabled this method has no effect. The default implementation calls 5193 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)} first 5194 * to populate information about the event source (this View), then calls 5195 * {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} to 5196 * populate the text content of the event source including its descendants, 5197 * and last calls 5198 * {@link ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} 5199 * on its parent to resuest sending of the event to interested parties. 5200 * <p> 5201 * If an {@link AccessibilityDelegate} has been specified via calling 5202 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5203 * {@link AccessibilityDelegate#sendAccessibilityEvent(View, int)} is 5204 * responsible for handling this call. 5205 * </p> 5206 * 5207 * @param eventType The type of the event to send, as defined by several types from 5208 * {@link android.view.accessibility.AccessibilityEvent}, such as 5209 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_CLICKED} or 5210 * {@link android.view.accessibility.AccessibilityEvent#TYPE_VIEW_HOVER_ENTER}. 5211 * 5212 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5213 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5214 * @see ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent) 5215 * @see AccessibilityDelegate 5216 */ 5217 public void sendAccessibilityEvent(int eventType) { 5218 if (mAccessibilityDelegate != null) { 5219 mAccessibilityDelegate.sendAccessibilityEvent(this, eventType); 5220 } else { 5221 sendAccessibilityEventInternal(eventType); 5222 } 5223 } 5224 5225 /** 5226 * Convenience method for sending a {@link AccessibilityEvent#TYPE_ANNOUNCEMENT} 5227 * {@link AccessibilityEvent} to make an announcement which is related to some 5228 * sort of a context change for which none of the events representing UI transitions 5229 * is a good fit. For example, announcing a new page in a book. If accessibility 5230 * is not enabled this method does nothing. 5231 * 5232 * @param text The announcement text. 5233 */ 5234 public void announceForAccessibility(CharSequence text) { 5235 if (AccessibilityManager.getInstance(mContext).isEnabled() && mParent != null) { 5236 AccessibilityEvent event = AccessibilityEvent.obtain( 5237 AccessibilityEvent.TYPE_ANNOUNCEMENT); 5238 onInitializeAccessibilityEvent(event); 5239 event.getText().add(text); 5240 event.setContentDescription(null); 5241 mParent.requestSendAccessibilityEvent(this, event); 5242 } 5243 } 5244 5245 /** 5246 * @see #sendAccessibilityEvent(int) 5247 * 5248 * Note: Called from the default {@link AccessibilityDelegate}. 5249 */ 5250 void sendAccessibilityEventInternal(int eventType) { 5251 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 5252 sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); 5253 } 5254 } 5255 5256 /** 5257 * This method behaves exactly as {@link #sendAccessibilityEvent(int)} but 5258 * takes as an argument an empty {@link AccessibilityEvent} and does not 5259 * perform a check whether accessibility is enabled. 5260 * <p> 5261 * If an {@link AccessibilityDelegate} has been specified via calling 5262 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5263 * {@link AccessibilityDelegate#sendAccessibilityEventUnchecked(View, AccessibilityEvent)} 5264 * is responsible for handling this call. 5265 * </p> 5266 * 5267 * @param event The event to send. 5268 * 5269 * @see #sendAccessibilityEvent(int) 5270 */ 5271 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 5272 if (mAccessibilityDelegate != null) { 5273 mAccessibilityDelegate.sendAccessibilityEventUnchecked(this, event); 5274 } else { 5275 sendAccessibilityEventUncheckedInternal(event); 5276 } 5277 } 5278 5279 /** 5280 * @see #sendAccessibilityEventUnchecked(AccessibilityEvent) 5281 * 5282 * Note: Called from the default {@link AccessibilityDelegate}. 5283 */ 5284 void sendAccessibilityEventUncheckedInternal(AccessibilityEvent event) { 5285 if (!isShown()) { 5286 return; 5287 } 5288 onInitializeAccessibilityEvent(event); 5289 // Only a subset of accessibility events populates text content. 5290 if ((event.getEventType() & POPULATING_ACCESSIBILITY_EVENT_TYPES) != 0) { 5291 dispatchPopulateAccessibilityEvent(event); 5292 } 5293 // In the beginning we called #isShown(), so we know that getParent() is not null. 5294 getParent().requestSendAccessibilityEvent(this, event); 5295 } 5296 5297 /** 5298 * Dispatches an {@link AccessibilityEvent} to the {@link View} first and then 5299 * to its children for adding their text content to the event. Note that the 5300 * event text is populated in a separate dispatch path since we add to the 5301 * event not only the text of the source but also the text of all its descendants. 5302 * A typical implementation will call 5303 * {@link #onPopulateAccessibilityEvent(AccessibilityEvent)} on the this view 5304 * and then call the {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5305 * on each child. Override this method if custom population of the event text 5306 * content is required. 5307 * <p> 5308 * If an {@link AccessibilityDelegate} has been specified via calling 5309 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5310 * {@link AccessibilityDelegate#dispatchPopulateAccessibilityEvent(View, AccessibilityEvent)} 5311 * is responsible for handling this call. 5312 * </p> 5313 * <p> 5314 * <em>Note:</em> Accessibility events of certain types are not dispatched for 5315 * populating the event text via this method. For details refer to {@link AccessibilityEvent}. 5316 * </p> 5317 * 5318 * @param event The event. 5319 * 5320 * @return True if the event population was completed. 5321 */ 5322 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 5323 if (mAccessibilityDelegate != null) { 5324 return mAccessibilityDelegate.dispatchPopulateAccessibilityEvent(this, event); 5325 } else { 5326 return dispatchPopulateAccessibilityEventInternal(event); 5327 } 5328 } 5329 5330 /** 5331 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5332 * 5333 * Note: Called from the default {@link AccessibilityDelegate}. 5334 */ 5335 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5336 onPopulateAccessibilityEvent(event); 5337 return false; 5338 } 5339 5340 /** 5341 * Called from {@link #dispatchPopulateAccessibilityEvent(AccessibilityEvent)} 5342 * giving a chance to this View to populate the accessibility event with its 5343 * text content. While this method is free to modify event 5344 * attributes other than text content, doing so should normally be performed in 5345 * {@link #onInitializeAccessibilityEvent(AccessibilityEvent)}. 5346 * <p> 5347 * Example: Adding formatted date string to an accessibility event in addition 5348 * to the text added by the super implementation: 5349 * <pre> public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5350 * super.onPopulateAccessibilityEvent(event); 5351 * final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY; 5352 * String selectedDateUtterance = DateUtils.formatDateTime(mContext, 5353 * mCurrentDate.getTimeInMillis(), flags); 5354 * event.getText().add(selectedDateUtterance); 5355 * }</pre> 5356 * <p> 5357 * If an {@link AccessibilityDelegate} has been specified via calling 5358 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5359 * {@link AccessibilityDelegate#onPopulateAccessibilityEvent(View, AccessibilityEvent)} 5360 * is responsible for handling this call. 5361 * </p> 5362 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5363 * information to the event, in case the default implementation has basic information to add. 5364 * </p> 5365 * 5366 * @param event The accessibility event which to populate. 5367 * 5368 * @see #sendAccessibilityEvent(int) 5369 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5370 */ 5371 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 5372 if (mAccessibilityDelegate != null) { 5373 mAccessibilityDelegate.onPopulateAccessibilityEvent(this, event); 5374 } else { 5375 onPopulateAccessibilityEventInternal(event); 5376 } 5377 } 5378 5379 /** 5380 * @see #onPopulateAccessibilityEvent(AccessibilityEvent) 5381 * 5382 * Note: Called from the default {@link AccessibilityDelegate}. 5383 */ 5384 void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 5385 } 5386 5387 /** 5388 * Initializes an {@link AccessibilityEvent} with information about 5389 * this View which is the event source. In other words, the source of 5390 * an accessibility event is the view whose state change triggered firing 5391 * the event. 5392 * <p> 5393 * Example: Setting the password property of an event in addition 5394 * to properties set by the super implementation: 5395 * <pre> public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5396 * super.onInitializeAccessibilityEvent(event); 5397 * event.setPassword(true); 5398 * }</pre> 5399 * <p> 5400 * If an {@link AccessibilityDelegate} has been specified via calling 5401 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5402 * {@link AccessibilityDelegate#onInitializeAccessibilityEvent(View, AccessibilityEvent)} 5403 * is responsible for handling this call. 5404 * </p> 5405 * <p class="note"><strong>Note:</strong> Always call the super implementation before adding 5406 * information to the event, in case the default implementation has basic information to add. 5407 * </p> 5408 * @param event The event to initialize. 5409 * 5410 * @see #sendAccessibilityEvent(int) 5411 * @see #dispatchPopulateAccessibilityEvent(AccessibilityEvent) 5412 */ 5413 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 5414 if (mAccessibilityDelegate != null) { 5415 mAccessibilityDelegate.onInitializeAccessibilityEvent(this, event); 5416 } else { 5417 onInitializeAccessibilityEventInternal(event); 5418 } 5419 } 5420 5421 /** 5422 * @see #onInitializeAccessibilityEvent(AccessibilityEvent) 5423 * 5424 * Note: Called from the default {@link AccessibilityDelegate}. 5425 */ 5426 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 5427 event.setSource(this); 5428 event.setClassName(View.class.getName()); 5429 event.setPackageName(getContext().getPackageName()); 5430 event.setEnabled(isEnabled()); 5431 event.setContentDescription(mContentDescription); 5432 5433 switch (event.getEventType()) { 5434 case AccessibilityEvent.TYPE_VIEW_FOCUSED: { 5435 ArrayList<View> focusablesTempList = (mAttachInfo != null) 5436 ? mAttachInfo.mTempArrayList : new ArrayList<View>(); 5437 getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL); 5438 event.setItemCount(focusablesTempList.size()); 5439 event.setCurrentItemIndex(focusablesTempList.indexOf(this)); 5440 if (mAttachInfo != null) { 5441 focusablesTempList.clear(); 5442 } 5443 } break; 5444 case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: { 5445 CharSequence text = getIterableTextForAccessibility(); 5446 if (text != null && text.length() > 0) { 5447 event.setFromIndex(getAccessibilitySelectionStart()); 5448 event.setToIndex(getAccessibilitySelectionEnd()); 5449 event.setItemCount(text.length()); 5450 } 5451 } break; 5452 } 5453 } 5454 5455 /** 5456 * Returns an {@link AccessibilityNodeInfo} representing this view from the 5457 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 5458 * This method is responsible for obtaining an accessibility node info from a 5459 * pool of reusable instances and calling 5460 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on this view to 5461 * initialize the former. 5462 * <p> 5463 * Note: The client is responsible for recycling the obtained instance by calling 5464 * {@link AccessibilityNodeInfo#recycle()} to minimize object creation. 5465 * </p> 5466 * 5467 * @return A populated {@link AccessibilityNodeInfo}. 5468 * 5469 * @see AccessibilityNodeInfo 5470 */ 5471 public AccessibilityNodeInfo createAccessibilityNodeInfo() { 5472 if (mAccessibilityDelegate != null) { 5473 return mAccessibilityDelegate.createAccessibilityNodeInfo(this); 5474 } else { 5475 return createAccessibilityNodeInfoInternal(); 5476 } 5477 } 5478 5479 /** 5480 * @see #createAccessibilityNodeInfo() 5481 */ 5482 AccessibilityNodeInfo createAccessibilityNodeInfoInternal() { 5483 AccessibilityNodeProvider provider = getAccessibilityNodeProvider(); 5484 if (provider != null) { 5485 return provider.createAccessibilityNodeInfo(View.NO_ID); 5486 } else { 5487 AccessibilityNodeInfo info = AccessibilityNodeInfo.obtain(this); 5488 onInitializeAccessibilityNodeInfo(info); 5489 return info; 5490 } 5491 } 5492 5493 /** 5494 * Initializes an {@link AccessibilityNodeInfo} with information about this view. 5495 * The base implementation sets: 5496 * <ul> 5497 * <li>{@link AccessibilityNodeInfo#setParent(View)},</li> 5498 * <li>{@link AccessibilityNodeInfo#setBoundsInParent(Rect)},</li> 5499 * <li>{@link AccessibilityNodeInfo#setBoundsInScreen(Rect)},</li> 5500 * <li>{@link AccessibilityNodeInfo#setPackageName(CharSequence)},</li> 5501 * <li>{@link AccessibilityNodeInfo#setClassName(CharSequence)},</li> 5502 * <li>{@link AccessibilityNodeInfo#setContentDescription(CharSequence)},</li> 5503 * <li>{@link AccessibilityNodeInfo#setEnabled(boolean)},</li> 5504 * <li>{@link AccessibilityNodeInfo#setClickable(boolean)},</li> 5505 * <li>{@link AccessibilityNodeInfo#setFocusable(boolean)},</li> 5506 * <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li> 5507 * <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li> 5508 * <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li> 5509 * </ul> 5510 * <p> 5511 * Subclasses should override this method, call the super implementation, 5512 * and set additional attributes. 5513 * </p> 5514 * <p> 5515 * If an {@link AccessibilityDelegate} has been specified via calling 5516 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5517 * {@link AccessibilityDelegate#onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo)} 5518 * is responsible for handling this call. 5519 * </p> 5520 * 5521 * @param info The instance to initialize. 5522 */ 5523 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 5524 if (mAccessibilityDelegate != null) { 5525 mAccessibilityDelegate.onInitializeAccessibilityNodeInfo(this, info); 5526 } else { 5527 onInitializeAccessibilityNodeInfoInternal(info); 5528 } 5529 } 5530 5531 /** 5532 * Gets the location of this view in screen coordintates. 5533 * 5534 * @param outRect The output location 5535 * @hide 5536 */ 5537 public void getBoundsOnScreen(Rect outRect) { 5538 if (mAttachInfo == null) { 5539 return; 5540 } 5541 5542 RectF position = mAttachInfo.mTmpTransformRect; 5543 position.set(0, 0, mRight - mLeft, mBottom - mTop); 5544 5545 if (!hasIdentityMatrix()) { 5546 getMatrix().mapRect(position); 5547 } 5548 5549 position.offset(mLeft, mTop); 5550 5551 ViewParent parent = mParent; 5552 while (parent instanceof View) { 5553 View parentView = (View) parent; 5554 5555 position.offset(-parentView.mScrollX, -parentView.mScrollY); 5556 5557 if (!parentView.hasIdentityMatrix()) { 5558 parentView.getMatrix().mapRect(position); 5559 } 5560 5561 position.offset(parentView.mLeft, parentView.mTop); 5562 5563 parent = parentView.mParent; 5564 } 5565 5566 if (parent instanceof ViewRootImpl) { 5567 ViewRootImpl viewRootImpl = (ViewRootImpl) parent; 5568 position.offset(0, -viewRootImpl.mCurScrollY); 5569 } 5570 5571 position.offset(mAttachInfo.mWindowLeft, mAttachInfo.mWindowTop); 5572 5573 outRect.set((int) (position.left + 0.5f), (int) (position.top + 0.5f), 5574 (int) (position.right + 0.5f), (int) (position.bottom + 0.5f)); 5575 } 5576 5577 /** 5578 * @see #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 5579 * 5580 * Note: Called from the default {@link AccessibilityDelegate}. 5581 */ 5582 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 5583 Rect bounds = mAttachInfo.mTmpInvalRect; 5584 5585 getDrawingRect(bounds); 5586 info.setBoundsInParent(bounds); 5587 5588 getBoundsOnScreen(bounds); 5589 info.setBoundsInScreen(bounds); 5590 5591 ViewParent parent = getParentForAccessibility(); 5592 if (parent instanceof View) { 5593 info.setParent((View) parent); 5594 } 5595 5596 if (mID != View.NO_ID) { 5597 View rootView = getRootView(); 5598 if (rootView == null) { 5599 rootView = this; 5600 } 5601 View label = rootView.findLabelForView(this, mID); 5602 if (label != null) { 5603 info.setLabeledBy(label); 5604 } 5605 5606 if ((mAttachInfo.mAccessibilityFetchFlags 5607 & AccessibilityNodeInfo.FLAG_REPORT_VIEW_IDS) != 0 5608 && Resources.resourceHasPackage(mID)) { 5609 try { 5610 String viewId = getResources().getResourceName(mID); 5611 info.setViewIdResourceName(viewId); 5612 } catch (Resources.NotFoundException nfe) { 5613 /* ignore */ 5614 } 5615 } 5616 } 5617 5618 if (mLabelForId != View.NO_ID) { 5619 View rootView = getRootView(); 5620 if (rootView == null) { 5621 rootView = this; 5622 } 5623 View labeled = rootView.findViewInsideOutShouldExist(this, mLabelForId); 5624 if (labeled != null) { 5625 info.setLabelFor(labeled); 5626 } 5627 } 5628 5629 info.setVisibleToUser(isVisibleToUser()); 5630 5631 info.setPackageName(mContext.getPackageName()); 5632 info.setClassName(View.class.getName()); 5633 info.setContentDescription(getContentDescription()); 5634 5635 info.setEnabled(isEnabled()); 5636 info.setClickable(isClickable()); 5637 info.setFocusable(isFocusable()); 5638 info.setFocused(isFocused()); 5639 info.setAccessibilityFocused(isAccessibilityFocused()); 5640 info.setSelected(isSelected()); 5641 info.setLongClickable(isLongClickable()); 5642 info.setLiveRegion(getAccessibilityLiveRegion()); 5643 5644 // TODO: These make sense only if we are in an AdapterView but all 5645 // views can be selected. Maybe from accessibility perspective 5646 // we should report as selectable view in an AdapterView. 5647 info.addAction(AccessibilityNodeInfo.ACTION_SELECT); 5648 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_SELECTION); 5649 5650 if (isFocusable()) { 5651 if (isFocused()) { 5652 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_FOCUS); 5653 } else { 5654 info.addAction(AccessibilityNodeInfo.ACTION_FOCUS); 5655 } 5656 } 5657 5658 if (!isAccessibilityFocused()) { 5659 info.addAction(AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS); 5660 } else { 5661 info.addAction(AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS); 5662 } 5663 5664 if (isClickable() && isEnabled()) { 5665 info.addAction(AccessibilityNodeInfo.ACTION_CLICK); 5666 } 5667 5668 if (isLongClickable() && isEnabled()) { 5669 info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK); 5670 } 5671 5672 CharSequence text = getIterableTextForAccessibility(); 5673 if (text != null && text.length() > 0) { 5674 info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd()); 5675 5676 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 5677 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 5678 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 5679 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 5680 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 5681 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH); 5682 } 5683 } 5684 5685 private View findLabelForView(View view, int labeledId) { 5686 if (mMatchLabelForPredicate == null) { 5687 mMatchLabelForPredicate = new MatchLabelForPredicate(); 5688 } 5689 mMatchLabelForPredicate.mLabeledId = labeledId; 5690 return findViewByPredicateInsideOut(view, mMatchLabelForPredicate); 5691 } 5692 5693 /** 5694 * Computes whether this view is visible to the user. Such a view is 5695 * attached, visible, all its predecessors are visible, it is not clipped 5696 * entirely by its predecessors, and has an alpha greater than zero. 5697 * 5698 * @return Whether the view is visible on the screen. 5699 * 5700 * @hide 5701 */ 5702 protected boolean isVisibleToUser() { 5703 return isVisibleToUser(null); 5704 } 5705 5706 /** 5707 * Computes whether the given portion of this view is visible to the user. 5708 * Such a view is attached, visible, all its predecessors are visible, 5709 * has an alpha greater than zero, and the specified portion is not 5710 * clipped entirely by its predecessors. 5711 * 5712 * @param boundInView the portion of the view to test; coordinates should be relative; may be 5713 * <code>null</code>, and the entire view will be tested in this case. 5714 * When <code>true</code> is returned by the function, the actual visible 5715 * region will be stored in this parameter; that is, if boundInView is fully 5716 * contained within the view, no modification will be made, otherwise regions 5717 * outside of the visible area of the view will be clipped. 5718 * 5719 * @return Whether the specified portion of the view is visible on the screen. 5720 * 5721 * @hide 5722 */ 5723 protected boolean isVisibleToUser(Rect boundInView) { 5724 if (mAttachInfo != null) { 5725 // Attached to invisible window means this view is not visible. 5726 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5727 return false; 5728 } 5729 // An invisible predecessor or one with alpha zero means 5730 // that this view is not visible to the user. 5731 Object current = this; 5732 while (current instanceof View) { 5733 View view = (View) current; 5734 // We have attach info so this view is attached and there is no 5735 // need to check whether we reach to ViewRootImpl on the way up. 5736 if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || 5737 view.getVisibility() != VISIBLE) { 5738 return false; 5739 } 5740 current = view.mParent; 5741 } 5742 // Check if the view is entirely covered by its predecessors. 5743 Rect visibleRect = mAttachInfo.mTmpInvalRect; 5744 Point offset = mAttachInfo.mPoint; 5745 if (!getGlobalVisibleRect(visibleRect, offset)) { 5746 return false; 5747 } 5748 // Check if the visible portion intersects the rectangle of interest. 5749 if (boundInView != null) { 5750 visibleRect.offset(-offset.x, -offset.y); 5751 return boundInView.intersect(visibleRect); 5752 } 5753 return true; 5754 } 5755 return false; 5756 } 5757 5758 /** 5759 * Computes a point on which a sequence of a down/up event can be sent to 5760 * trigger clicking this view. This method is for the exclusive use by the 5761 * accessibility layer to determine where to send a click event in explore 5762 * by touch mode. 5763 * 5764 * @param interactiveRegion The interactive portion of this window. 5765 * @param outPoint The point to populate. 5766 * @return True of such a point exists. 5767 */ 5768 boolean computeClickPointInScreenForAccessibility(Region interactiveRegion, 5769 Point outPoint) { 5770 // Since the interactive portion of the view is a region but as a view 5771 // may have a transformation matrix which cannot be applied to a 5772 // region we compute the view bounds rectangle and all interactive 5773 // predecessor's and sibling's (siblings of predecessors included) 5774 // rectangles that intersect the view bounds. At the 5775 // end if the view was partially covered by another interactive 5776 // view we compute the view's interactive region and pick a point 5777 // on its boundary path as regions do not offer APIs to get inner 5778 // points. Note that the the code is optimized to fail early and 5779 // avoid unnecessary allocations plus computations. 5780 5781 // The current approach has edge cases that may produce false 5782 // positives or false negatives. For example, a portion of the 5783 // view may be covered by an interactive descendant of a 5784 // predecessor, which we do not compute. Also a view may be handling 5785 // raw touch events instead registering click listeners, which 5786 // we cannot compute. Despite these limitations this approach will 5787 // work most of the time and it is a huge improvement over just 5788 // blindly sending the down and up events in the center of the 5789 // view. 5790 5791 // Cannot click on an unattached view. 5792 if (mAttachInfo == null) { 5793 return false; 5794 } 5795 5796 // Attached to an invisible window means this view is not visible. 5797 if (mAttachInfo.mWindowVisibility != View.VISIBLE) { 5798 return false; 5799 } 5800 5801 RectF bounds = mAttachInfo.mTmpTransformRect; 5802 bounds.set(0, 0, getWidth(), getHeight()); 5803 List<RectF> intersections = mAttachInfo.mTmpRectList; 5804 intersections.clear(); 5805 5806 if (mParent instanceof ViewGroup) { 5807 ViewGroup parentGroup = (ViewGroup) mParent; 5808 if (!parentGroup.translateBoundsAndIntersectionsInWindowCoordinates( 5809 this, bounds, intersections)) { 5810 intersections.clear(); 5811 return false; 5812 } 5813 } 5814 5815 // Take into account the window location. 5816 final int dx = mAttachInfo.mWindowLeft; 5817 final int dy = mAttachInfo.mWindowTop; 5818 bounds.offset(dx, dy); 5819 offsetRects(intersections, dx, dy); 5820 5821 if (intersections.isEmpty() && interactiveRegion == null) { 5822 outPoint.set((int) bounds.centerX(), (int) bounds.centerY()); 5823 } else { 5824 // This view is partially covered by other views, then compute 5825 // the not covered region and pick a point on its boundary. 5826 Region region = new Region(); 5827 region.set((int) bounds.left, (int) bounds.top, 5828 (int) bounds.right, (int) bounds.bottom); 5829 5830 final int intersectionCount = intersections.size(); 5831 for (int i = intersectionCount - 1; i >= 0; i--) { 5832 RectF intersection = intersections.remove(i); 5833 region.op((int) intersection.left, (int) intersection.top, 5834 (int) intersection.right, (int) intersection.bottom, 5835 Region.Op.DIFFERENCE); 5836 } 5837 5838 // If the view is completely covered, done. 5839 if (region.isEmpty()) { 5840 return false; 5841 } 5842 5843 // Take into account the interactive portion of the window 5844 // as the rest is covered by other windows. If no such a region 5845 // then the whole window is interactive. 5846 if (interactiveRegion != null) { 5847 region.op(interactiveRegion, Region.Op.INTERSECT); 5848 } 5849 5850 // If the view is completely covered, done. 5851 if (region.isEmpty()) { 5852 return false; 5853 } 5854 5855 // Try a shortcut here. 5856 if (region.isRect()) { 5857 Rect regionBounds = mAttachInfo.mTmpInvalRect; 5858 region.getBounds(regionBounds); 5859 outPoint.set(regionBounds.centerX(), regionBounds.centerY()); 5860 return true; 5861 } 5862 5863 // Get the a point on the region boundary path. 5864 Path path = region.getBoundaryPath(); 5865 PathMeasure pathMeasure = new PathMeasure(path, false); 5866 final float[] coordinates = mAttachInfo.mTmpTransformLocation; 5867 5868 // Without loss of generality pick a point. 5869 final float point = pathMeasure.getLength() * 0.01f; 5870 if (!pathMeasure.getPosTan(point, coordinates, null)) { 5871 return false; 5872 } 5873 5874 outPoint.set(Math.round(coordinates[0]), Math.round(coordinates[1])); 5875 } 5876 5877 return true; 5878 } 5879 5880 static void offsetRects(List<RectF> rects, float offsetX, float offsetY) { 5881 final int rectCount = rects.size(); 5882 for (int i = 0; i < rectCount; i++) { 5883 RectF intersection = rects.get(i); 5884 intersection.offset(offsetX, offsetY); 5885 } 5886 } 5887 5888 /** 5889 * Returns the delegate for implementing accessibility support via 5890 * composition. For more details see {@link AccessibilityDelegate}. 5891 * 5892 * @return The delegate, or null if none set. 5893 * 5894 * @hide 5895 */ 5896 public AccessibilityDelegate getAccessibilityDelegate() { 5897 return mAccessibilityDelegate; 5898 } 5899 5900 /** 5901 * Sets a delegate for implementing accessibility support via composition as 5902 * opposed to inheritance. The delegate's primary use is for implementing 5903 * backwards compatible widgets. For more details see {@link AccessibilityDelegate}. 5904 * 5905 * @param delegate The delegate instance. 5906 * 5907 * @see AccessibilityDelegate 5908 */ 5909 public void setAccessibilityDelegate(AccessibilityDelegate delegate) { 5910 mAccessibilityDelegate = delegate; 5911 } 5912 5913 /** 5914 * Gets the provider for managing a virtual view hierarchy rooted at this View 5915 * and reported to {@link android.accessibilityservice.AccessibilityService}s 5916 * that explore the window content. 5917 * <p> 5918 * If this method returns an instance, this instance is responsible for managing 5919 * {@link AccessibilityNodeInfo}s describing the virtual sub-tree rooted at this 5920 * View including the one representing the View itself. Similarly the returned 5921 * instance is responsible for performing accessibility actions on any virtual 5922 * view or the root view itself. 5923 * </p> 5924 * <p> 5925 * If an {@link AccessibilityDelegate} has been specified via calling 5926 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 5927 * {@link AccessibilityDelegate#getAccessibilityNodeProvider(View)} 5928 * is responsible for handling this call. 5929 * </p> 5930 * 5931 * @return The provider. 5932 * 5933 * @see AccessibilityNodeProvider 5934 */ 5935 public AccessibilityNodeProvider getAccessibilityNodeProvider() { 5936 if (mAccessibilityDelegate != null) { 5937 return mAccessibilityDelegate.getAccessibilityNodeProvider(this); 5938 } else { 5939 return null; 5940 } 5941 } 5942 5943 /** 5944 * Gets the unique identifier of this view on the screen for accessibility purposes. 5945 * If this {@link View} is not attached to any window, {@value #NO_ID} is returned. 5946 * 5947 * @return The view accessibility id. 5948 * 5949 * @hide 5950 */ 5951 public int getAccessibilityViewId() { 5952 if (mAccessibilityViewId == NO_ID) { 5953 mAccessibilityViewId = sNextAccessibilityViewId++; 5954 } 5955 return mAccessibilityViewId; 5956 } 5957 5958 /** 5959 * Gets the unique identifier of the window in which this View reseides. 5960 * 5961 * @return The window accessibility id. 5962 * 5963 * @hide 5964 */ 5965 public int getAccessibilityWindowId() { 5966 return mAttachInfo != null ? mAttachInfo.mAccessibilityWindowId 5967 : AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 5968 } 5969 5970 /** 5971 * Gets the {@link View} description. It briefly describes the view and is 5972 * primarily used for accessibility support. Set this property to enable 5973 * better accessibility support for your application. This is especially 5974 * true for views that do not have textual representation (For example, 5975 * ImageButton). 5976 * 5977 * @return The content description. 5978 * 5979 * @attr ref android.R.styleable#View_contentDescription 5980 */ 5981 @ViewDebug.ExportedProperty(category = "accessibility") 5982 public CharSequence getContentDescription() { 5983 return mContentDescription; 5984 } 5985 5986 /** 5987 * Sets the {@link View} description. It briefly describes the view and is 5988 * primarily used for accessibility support. Set this property to enable 5989 * better accessibility support for your application. This is especially 5990 * true for views that do not have textual representation (For example, 5991 * ImageButton). 5992 * 5993 * @param contentDescription The content description. 5994 * 5995 * @attr ref android.R.styleable#View_contentDescription 5996 */ 5997 @RemotableViewMethod 5998 public void setContentDescription(CharSequence contentDescription) { 5999 if (mContentDescription == null) { 6000 if (contentDescription == null) { 6001 return; 6002 } 6003 } else if (mContentDescription.equals(contentDescription)) { 6004 return; 6005 } 6006 mContentDescription = contentDescription; 6007 final boolean nonEmptyDesc = contentDescription != null && contentDescription.length() > 0; 6008 if (nonEmptyDesc && getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 6009 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 6010 notifySubtreeAccessibilityStateChangedIfNeeded(); 6011 } else { 6012 notifyViewAccessibilityStateChangedIfNeeded( 6013 AccessibilityEvent.CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION); 6014 } 6015 } 6016 6017 /** 6018 * Gets the id of a view for which this view serves as a label for 6019 * accessibility purposes. 6020 * 6021 * @return The labeled view id. 6022 */ 6023 @ViewDebug.ExportedProperty(category = "accessibility") 6024 public int getLabelFor() { 6025 return mLabelForId; 6026 } 6027 6028 /** 6029 * Sets the id of a view for which this view serves as a label for 6030 * accessibility purposes. 6031 * 6032 * @param id The labeled view id. 6033 */ 6034 @RemotableViewMethod 6035 public void setLabelFor(int id) { 6036 mLabelForId = id; 6037 if (mLabelForId != View.NO_ID 6038 && mID == View.NO_ID) { 6039 mID = generateViewId(); 6040 } 6041 } 6042 6043 /** 6044 * Invoked whenever this view loses focus, either by losing window focus or by losing 6045 * focus within its window. This method can be used to clear any state tied to the 6046 * focus. For instance, if a button is held pressed with the trackball and the window 6047 * loses focus, this method can be used to cancel the press. 6048 * 6049 * Subclasses of View overriding this method should always call super.onFocusLost(). 6050 * 6051 * @see #onFocusChanged(boolean, int, android.graphics.Rect) 6052 * @see #onWindowFocusChanged(boolean) 6053 * 6054 * @hide pending API council approval 6055 */ 6056 protected void onFocusLost() { 6057 resetPressedState(); 6058 } 6059 6060 private void resetPressedState() { 6061 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 6062 return; 6063 } 6064 6065 if (isPressed()) { 6066 setPressed(false); 6067 6068 if (!mHasPerformedLongPress) { 6069 removeLongPressCallback(); 6070 } 6071 } 6072 } 6073 6074 /** 6075 * Returns true if this view has focus 6076 * 6077 * @return True if this view has focus, false otherwise. 6078 */ 6079 @ViewDebug.ExportedProperty(category = "focus") 6080 public boolean isFocused() { 6081 return (mPrivateFlags & PFLAG_FOCUSED) != 0; 6082 } 6083 6084 /** 6085 * Find the view in the hierarchy rooted at this view that currently has 6086 * focus. 6087 * 6088 * @return The view that currently has focus, or null if no focused view can 6089 * be found. 6090 */ 6091 public View findFocus() { 6092 return (mPrivateFlags & PFLAG_FOCUSED) != 0 ? this : null; 6093 } 6094 6095 /** 6096 * Indicates whether this view is one of the set of scrollable containers in 6097 * its window. 6098 * 6099 * @return whether this view is one of the set of scrollable containers in 6100 * its window 6101 * 6102 * @attr ref android.R.styleable#View_isScrollContainer 6103 */ 6104 public boolean isScrollContainer() { 6105 return (mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0; 6106 } 6107 6108 /** 6109 * Change whether this view is one of the set of scrollable containers in 6110 * its window. This will be used to determine whether the window can 6111 * resize or must pan when a soft input area is open -- scrollable 6112 * containers allow the window to use resize mode since the container 6113 * will appropriately shrink. 6114 * 6115 * @attr ref android.R.styleable#View_isScrollContainer 6116 */ 6117 public void setScrollContainer(boolean isScrollContainer) { 6118 if (isScrollContainer) { 6119 if (mAttachInfo != null && (mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) == 0) { 6120 mAttachInfo.mScrollContainers.add(this); 6121 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 6122 } 6123 mPrivateFlags |= PFLAG_SCROLL_CONTAINER; 6124 } else { 6125 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 6126 mAttachInfo.mScrollContainers.remove(this); 6127 } 6128 mPrivateFlags &= ~(PFLAG_SCROLL_CONTAINER|PFLAG_SCROLL_CONTAINER_ADDED); 6129 } 6130 } 6131 6132 /** 6133 * Returns the quality of the drawing cache. 6134 * 6135 * @return One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6136 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6137 * 6138 * @see #setDrawingCacheQuality(int) 6139 * @see #setDrawingCacheEnabled(boolean) 6140 * @see #isDrawingCacheEnabled() 6141 * 6142 * @attr ref android.R.styleable#View_drawingCacheQuality 6143 */ 6144 @DrawingCacheQuality 6145 public int getDrawingCacheQuality() { 6146 return mViewFlags & DRAWING_CACHE_QUALITY_MASK; 6147 } 6148 6149 /** 6150 * Set the drawing cache quality of this view. This value is used only when the 6151 * drawing cache is enabled 6152 * 6153 * @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO}, 6154 * {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH} 6155 * 6156 * @see #getDrawingCacheQuality() 6157 * @see #setDrawingCacheEnabled(boolean) 6158 * @see #isDrawingCacheEnabled() 6159 * 6160 * @attr ref android.R.styleable#View_drawingCacheQuality 6161 */ 6162 public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { 6163 setFlags(quality, DRAWING_CACHE_QUALITY_MASK); 6164 } 6165 6166 /** 6167 * Returns whether the screen should remain on, corresponding to the current 6168 * value of {@link #KEEP_SCREEN_ON}. 6169 * 6170 * @return Returns true if {@link #KEEP_SCREEN_ON} is set. 6171 * 6172 * @see #setKeepScreenOn(boolean) 6173 * 6174 * @attr ref android.R.styleable#View_keepScreenOn 6175 */ 6176 public boolean getKeepScreenOn() { 6177 return (mViewFlags & KEEP_SCREEN_ON) != 0; 6178 } 6179 6180 /** 6181 * Controls whether the screen should remain on, modifying the 6182 * value of {@link #KEEP_SCREEN_ON}. 6183 * 6184 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}. 6185 * 6186 * @see #getKeepScreenOn() 6187 * 6188 * @attr ref android.R.styleable#View_keepScreenOn 6189 */ 6190 public void setKeepScreenOn(boolean keepScreenOn) { 6191 setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON); 6192 } 6193 6194 /** 6195 * Gets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6196 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6197 * 6198 * @attr ref android.R.styleable#View_nextFocusLeft 6199 */ 6200 public int getNextFocusLeftId() { 6201 return mNextFocusLeftId; 6202 } 6203 6204 /** 6205 * Sets the id of the view to use when the next focus is {@link #FOCUS_LEFT}. 6206 * @param nextFocusLeftId The next focus ID, or {@link #NO_ID} if the framework should 6207 * decide automatically. 6208 * 6209 * @attr ref android.R.styleable#View_nextFocusLeft 6210 */ 6211 public void setNextFocusLeftId(int nextFocusLeftId) { 6212 mNextFocusLeftId = nextFocusLeftId; 6213 } 6214 6215 /** 6216 * Gets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6217 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6218 * 6219 * @attr ref android.R.styleable#View_nextFocusRight 6220 */ 6221 public int getNextFocusRightId() { 6222 return mNextFocusRightId; 6223 } 6224 6225 /** 6226 * Sets the id of the view to use when the next focus is {@link #FOCUS_RIGHT}. 6227 * @param nextFocusRightId The next focus ID, or {@link #NO_ID} if the framework should 6228 * decide automatically. 6229 * 6230 * @attr ref android.R.styleable#View_nextFocusRight 6231 */ 6232 public void setNextFocusRightId(int nextFocusRightId) { 6233 mNextFocusRightId = nextFocusRightId; 6234 } 6235 6236 /** 6237 * Gets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6238 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6239 * 6240 * @attr ref android.R.styleable#View_nextFocusUp 6241 */ 6242 public int getNextFocusUpId() { 6243 return mNextFocusUpId; 6244 } 6245 6246 /** 6247 * Sets the id of the view to use when the next focus is {@link #FOCUS_UP}. 6248 * @param nextFocusUpId The next focus ID, or {@link #NO_ID} if the framework should 6249 * decide automatically. 6250 * 6251 * @attr ref android.R.styleable#View_nextFocusUp 6252 */ 6253 public void setNextFocusUpId(int nextFocusUpId) { 6254 mNextFocusUpId = nextFocusUpId; 6255 } 6256 6257 /** 6258 * Gets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6259 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6260 * 6261 * @attr ref android.R.styleable#View_nextFocusDown 6262 */ 6263 public int getNextFocusDownId() { 6264 return mNextFocusDownId; 6265 } 6266 6267 /** 6268 * Sets the id of the view to use when the next focus is {@link #FOCUS_DOWN}. 6269 * @param nextFocusDownId The next focus ID, or {@link #NO_ID} if the framework should 6270 * decide automatically. 6271 * 6272 * @attr ref android.R.styleable#View_nextFocusDown 6273 */ 6274 public void setNextFocusDownId(int nextFocusDownId) { 6275 mNextFocusDownId = nextFocusDownId; 6276 } 6277 6278 /** 6279 * Gets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6280 * @return The next focus ID, or {@link #NO_ID} if the framework should decide automatically. 6281 * 6282 * @attr ref android.R.styleable#View_nextFocusForward 6283 */ 6284 public int getNextFocusForwardId() { 6285 return mNextFocusForwardId; 6286 } 6287 6288 /** 6289 * Sets the id of the view to use when the next focus is {@link #FOCUS_FORWARD}. 6290 * @param nextFocusForwardId The next focus ID, or {@link #NO_ID} if the framework should 6291 * decide automatically. 6292 * 6293 * @attr ref android.R.styleable#View_nextFocusForward 6294 */ 6295 public void setNextFocusForwardId(int nextFocusForwardId) { 6296 mNextFocusForwardId = nextFocusForwardId; 6297 } 6298 6299 /** 6300 * Returns the visibility of this view and all of its ancestors 6301 * 6302 * @return True if this view and all of its ancestors are {@link #VISIBLE} 6303 */ 6304 public boolean isShown() { 6305 View current = this; 6306 //noinspection ConstantConditions 6307 do { 6308 if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) { 6309 return false; 6310 } 6311 ViewParent parent = current.mParent; 6312 if (parent == null) { 6313 return false; // We are not attached to the view root 6314 } 6315 if (!(parent instanceof View)) { 6316 return true; 6317 } 6318 current = (View) parent; 6319 } while (current != null); 6320 6321 return false; 6322 } 6323 6324 /** 6325 * Called by the view hierarchy when the content insets for a window have 6326 * changed, to allow it to adjust its content to fit within those windows. 6327 * The content insets tell you the space that the status bar, input method, 6328 * and other system windows infringe on the application's window. 6329 * 6330 * <p>You do not normally need to deal with this function, since the default 6331 * window decoration given to applications takes care of applying it to the 6332 * content of the window. If you use {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN} 6333 * or {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION} this will not be the case, 6334 * and your content can be placed under those system elements. You can then 6335 * use this method within your view hierarchy if you have parts of your UI 6336 * which you would like to ensure are not being covered. 6337 * 6338 * <p>The default implementation of this method simply applies the content 6339 * insets to the view's padding, consuming that content (modifying the 6340 * insets to be 0), and returning true. This behavior is off by default, but can 6341 * be enabled through {@link #setFitsSystemWindows(boolean)}. 6342 * 6343 * <p>This function's traversal down the hierarchy is depth-first. The same content 6344 * insets object is propagated down the hierarchy, so any changes made to it will 6345 * be seen by all following views (including potentially ones above in 6346 * the hierarchy since this is a depth-first traversal). The first view 6347 * that returns true will abort the entire traversal. 6348 * 6349 * <p>The default implementation works well for a situation where it is 6350 * used with a container that covers the entire window, allowing it to 6351 * apply the appropriate insets to its content on all edges. If you need 6352 * a more complicated layout (such as two different views fitting system 6353 * windows, one on the top of the window, and one on the bottom), 6354 * you can override the method and handle the insets however you would like. 6355 * Note that the insets provided by the framework are always relative to the 6356 * far edges of the window, not accounting for the location of the called view 6357 * within that window. (In fact when this method is called you do not yet know 6358 * where the layout will place the view, as it is done before layout happens.) 6359 * 6360 * <p>Note: unlike many View methods, there is no dispatch phase to this 6361 * call. If you are overriding it in a ViewGroup and want to allow the 6362 * call to continue to your children, you must be sure to call the super 6363 * implementation. 6364 * 6365 * <p>Here is a sample layout that makes use of fitting system windows 6366 * to have controls for a video view placed inside of the window decorations 6367 * that it hides and shows. This can be used with code like the second 6368 * sample (video player) shown in {@link #setSystemUiVisibility(int)}. 6369 * 6370 * {@sample development/samples/ApiDemos/res/layout/video_player.xml complete} 6371 * 6372 * @param insets Current content insets of the window. Prior to 6373 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN} you must not modify 6374 * the insets or else you and Android will be unhappy. 6375 * 6376 * @return {@code true} if this view applied the insets and it should not 6377 * continue propagating further down the hierarchy, {@code false} otherwise. 6378 * @see #getFitsSystemWindows() 6379 * @see #setFitsSystemWindows(boolean) 6380 * @see #setSystemUiVisibility(int) 6381 * 6382 * @deprecated As of API 20 use {@link #dispatchApplyWindowInsets(WindowInsets)} to apply 6383 * insets to views. Views should override {@link #onApplyWindowInsets(WindowInsets)} or use 6384 * {@link #setOnApplyWindowInsetsListener(android.view.View.OnApplyWindowInsetsListener)} 6385 * to implement handling their own insets. 6386 */ 6387 protected boolean fitSystemWindows(Rect insets) { 6388 if ((mPrivateFlags3 & PFLAG3_APPLYING_INSETS) == 0) { 6389 if (insets == null) { 6390 // Null insets by definition have already been consumed. 6391 // This call cannot apply insets since there are none to apply, 6392 // so return false. 6393 return false; 6394 } 6395 // If we're not in the process of dispatching the newer apply insets call, 6396 // that means we're not in the compatibility path. Dispatch into the newer 6397 // apply insets path and take things from there. 6398 try { 6399 mPrivateFlags3 |= PFLAG3_FITTING_SYSTEM_WINDOWS; 6400 return dispatchApplyWindowInsets(new WindowInsets(insets)).isConsumed(); 6401 } finally { 6402 mPrivateFlags3 &= ~PFLAG3_FITTING_SYSTEM_WINDOWS; 6403 } 6404 } else { 6405 // We're being called from the newer apply insets path. 6406 // Perform the standard fallback behavior. 6407 return fitSystemWindowsInt(insets); 6408 } 6409 } 6410 6411 private boolean fitSystemWindowsInt(Rect insets) { 6412 if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) { 6413 mUserPaddingStart = UNDEFINED_PADDING; 6414 mUserPaddingEnd = UNDEFINED_PADDING; 6415 Rect localInsets = sThreadLocal.get(); 6416 if (localInsets == null) { 6417 localInsets = new Rect(); 6418 sThreadLocal.set(localInsets); 6419 } 6420 boolean res = computeFitSystemWindows(insets, localInsets); 6421 mUserPaddingLeftInitial = localInsets.left; 6422 mUserPaddingRightInitial = localInsets.right; 6423 internalSetPadding(localInsets.left, localInsets.top, 6424 localInsets.right, localInsets.bottom); 6425 return res; 6426 } 6427 return false; 6428 } 6429 6430 /** 6431 * Called when the view should apply {@link WindowInsets} according to its internal policy. 6432 * 6433 * <p>This method should be overridden by views that wish to apply a policy different from or 6434 * in addition to the default behavior. Clients that wish to force a view subtree 6435 * to apply insets should call {@link #dispatchApplyWindowInsets(WindowInsets)}.</p> 6436 * 6437 * <p>Clients may supply an {@link OnApplyWindowInsetsListener} to a view. If one is set 6438 * it will be called during dispatch instead of this method. The listener may optionally 6439 * call this method from its own implementation if it wishes to apply the view's default 6440 * insets policy in addition to its own.</p> 6441 * 6442 * <p>Implementations of this method should either return the insets parameter unchanged 6443 * or a new {@link WindowInsets} cloned from the supplied insets with any insets consumed 6444 * that this view applied itself. This allows new inset types added in future platform 6445 * versions to pass through existing implementations unchanged without being erroneously 6446 * consumed.</p> 6447 * 6448 * <p>By default if a view's {@link #setFitsSystemWindows(boolean) fitsSystemWindows} 6449 * property is set then the view will consume the system window insets and apply them 6450 * as padding for the view.</p> 6451 * 6452 * @param insets Insets to apply 6453 * @return The supplied insets with any applied insets consumed 6454 */ 6455 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 6456 if ((mPrivateFlags3 & PFLAG3_FITTING_SYSTEM_WINDOWS) == 0) { 6457 // We weren't called from within a direct call to fitSystemWindows, 6458 // call into it as a fallback in case we're in a class that overrides it 6459 // and has logic to perform. 6460 if (fitSystemWindows(insets.getSystemWindowInsets())) { 6461 return insets.consumeSystemWindowInsets(); 6462 } 6463 } else { 6464 // We were called from within a direct call to fitSystemWindows. 6465 if (fitSystemWindowsInt(insets.getSystemWindowInsets())) { 6466 return insets.consumeSystemWindowInsets(); 6467 } 6468 } 6469 return insets; 6470 } 6471 6472 /** 6473 * Set an {@link OnApplyWindowInsetsListener} to take over the policy for applying 6474 * window insets to this view. The listener's 6475 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 6476 * method will be called instead of the view's 6477 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 6478 * 6479 * @param listener Listener to set 6480 * 6481 * @see #onApplyWindowInsets(WindowInsets) 6482 */ 6483 public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) { 6484 getListenerInfo().mOnApplyWindowInsetsListener = listener; 6485 } 6486 6487 /** 6488 * Request to apply the given window insets to this view or another view in its subtree. 6489 * 6490 * <p>This method should be called by clients wishing to apply insets corresponding to areas 6491 * obscured by window decorations or overlays. This can include the status and navigation bars, 6492 * action bars, input methods and more. New inset categories may be added in the future. 6493 * The method returns the insets provided minus any that were applied by this view or its 6494 * children.</p> 6495 * 6496 * <p>Clients wishing to provide custom behavior should override the 6497 * {@link #onApplyWindowInsets(WindowInsets)} method or alternatively provide a 6498 * {@link OnApplyWindowInsetsListener} via the 6499 * {@link #setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) setOnApplyWindowInsetsListener} 6500 * method.</p> 6501 * 6502 * <p>This method replaces the older {@link #fitSystemWindows(Rect) fitSystemWindows} method. 6503 * </p> 6504 * 6505 * @param insets Insets to apply 6506 * @return The provided insets minus the insets that were consumed 6507 */ 6508 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 6509 try { 6510 mPrivateFlags3 |= PFLAG3_APPLYING_INSETS; 6511 if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) { 6512 return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets); 6513 } else { 6514 return onApplyWindowInsets(insets); 6515 } 6516 } finally { 6517 mPrivateFlags3 &= ~PFLAG3_APPLYING_INSETS; 6518 } 6519 } 6520 6521 /** 6522 * @hide Compute the insets that should be consumed by this view and the ones 6523 * that should propagate to those under it. 6524 */ 6525 protected boolean computeFitSystemWindows(Rect inoutInsets, Rect outLocalInsets) { 6526 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6527 || mAttachInfo == null 6528 || ((mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0 6529 && !mAttachInfo.mOverscanRequested)) { 6530 outLocalInsets.set(inoutInsets); 6531 inoutInsets.set(0, 0, 0, 0); 6532 return true; 6533 } else { 6534 // The application wants to take care of fitting system window for 6535 // the content... however we still need to take care of any overscan here. 6536 final Rect overscan = mAttachInfo.mOverscanInsets; 6537 outLocalInsets.set(overscan); 6538 inoutInsets.left -= overscan.left; 6539 inoutInsets.top -= overscan.top; 6540 inoutInsets.right -= overscan.right; 6541 inoutInsets.bottom -= overscan.bottom; 6542 return false; 6543 } 6544 } 6545 6546 /** 6547 * Compute insets that should be consumed by this view and the ones that should propagate 6548 * to those under it. 6549 * 6550 * @param in Insets currently being processed by this View, likely received as a parameter 6551 * to {@link #onApplyWindowInsets(WindowInsets)}. 6552 * @param outLocalInsets A Rect that will receive the insets that should be consumed 6553 * by this view 6554 * @return Insets that should be passed along to views under this one 6555 */ 6556 public WindowInsets computeSystemWindowInsets(WindowInsets in, Rect outLocalInsets) { 6557 if ((mViewFlags & OPTIONAL_FITS_SYSTEM_WINDOWS) == 0 6558 || mAttachInfo == null 6559 || (mAttachInfo.mSystemUiVisibility & SYSTEM_UI_LAYOUT_FLAGS) == 0) { 6560 outLocalInsets.set(in.getSystemWindowInsets()); 6561 return in.consumeSystemWindowInsets(); 6562 } else { 6563 outLocalInsets.set(0, 0, 0, 0); 6564 return in; 6565 } 6566 } 6567 6568 /** 6569 * Sets whether or not this view should account for system screen decorations 6570 * such as the status bar and inset its content; that is, controlling whether 6571 * the default implementation of {@link #fitSystemWindows(Rect)} will be 6572 * executed. See that method for more details. 6573 * 6574 * <p>Note that if you are providing your own implementation of 6575 * {@link #fitSystemWindows(Rect)}, then there is no need to set this 6576 * flag to true -- your implementation will be overriding the default 6577 * implementation that checks this flag. 6578 * 6579 * @param fitSystemWindows If true, then the default implementation of 6580 * {@link #fitSystemWindows(Rect)} will be executed. 6581 * 6582 * @attr ref android.R.styleable#View_fitsSystemWindows 6583 * @see #getFitsSystemWindows() 6584 * @see #fitSystemWindows(Rect) 6585 * @see #setSystemUiVisibility(int) 6586 */ 6587 public void setFitsSystemWindows(boolean fitSystemWindows) { 6588 setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS); 6589 } 6590 6591 /** 6592 * Check for state of {@link #setFitsSystemWindows(boolean)}. If this method 6593 * returns {@code true}, the default implementation of {@link #fitSystemWindows(Rect)} 6594 * will be executed. 6595 * 6596 * @return {@code true} if the default implementation of 6597 * {@link #fitSystemWindows(Rect)} will be executed. 6598 * 6599 * @attr ref android.R.styleable#View_fitsSystemWindows 6600 * @see #setFitsSystemWindows(boolean) 6601 * @see #fitSystemWindows(Rect) 6602 * @see #setSystemUiVisibility(int) 6603 */ 6604 public boolean getFitsSystemWindows() { 6605 return (mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS; 6606 } 6607 6608 /** @hide */ 6609 public boolean fitsSystemWindows() { 6610 return getFitsSystemWindows(); 6611 } 6612 6613 /** 6614 * Ask that a new dispatch of {@link #fitSystemWindows(Rect)} be performed. 6615 * @deprecated Use {@link #requestApplyInsets()} for newer platform versions. 6616 */ 6617 public void requestFitSystemWindows() { 6618 if (mParent != null) { 6619 mParent.requestFitSystemWindows(); 6620 } 6621 } 6622 6623 /** 6624 * Ask that a new dispatch of {@link #onApplyWindowInsets(WindowInsets)} be performed. 6625 */ 6626 public void requestApplyInsets() { 6627 requestFitSystemWindows(); 6628 } 6629 6630 /** 6631 * For use by PhoneWindow to make its own system window fitting optional. 6632 * @hide 6633 */ 6634 public void makeOptionalFitsSystemWindows() { 6635 setFlags(OPTIONAL_FITS_SYSTEM_WINDOWS, OPTIONAL_FITS_SYSTEM_WINDOWS); 6636 } 6637 6638 /** 6639 * Returns the visibility status for this view. 6640 * 6641 * @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6642 * @attr ref android.R.styleable#View_visibility 6643 */ 6644 @ViewDebug.ExportedProperty(mapping = { 6645 @ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"), 6646 @ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"), 6647 @ViewDebug.IntToString(from = GONE, to = "GONE") 6648 }) 6649 @Visibility 6650 public int getVisibility() { 6651 return mViewFlags & VISIBILITY_MASK; 6652 } 6653 6654 /** 6655 * Set the enabled state of this view. 6656 * 6657 * @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}. 6658 * @attr ref android.R.styleable#View_visibility 6659 */ 6660 @RemotableViewMethod 6661 public void setVisibility(@Visibility int visibility) { 6662 setFlags(visibility, VISIBILITY_MASK); 6663 if (mBackground != null) mBackground.setVisible(visibility == VISIBLE, false); 6664 } 6665 6666 /** 6667 * Returns the enabled status for this view. The interpretation of the 6668 * enabled state varies by subclass. 6669 * 6670 * @return True if this view is enabled, false otherwise. 6671 */ 6672 @ViewDebug.ExportedProperty 6673 public boolean isEnabled() { 6674 return (mViewFlags & ENABLED_MASK) == ENABLED; 6675 } 6676 6677 /** 6678 * Set the enabled state of this view. The interpretation of the enabled 6679 * state varies by subclass. 6680 * 6681 * @param enabled True if this view is enabled, false otherwise. 6682 */ 6683 @RemotableViewMethod 6684 public void setEnabled(boolean enabled) { 6685 if (enabled == isEnabled()) return; 6686 6687 setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK); 6688 6689 /* 6690 * The View most likely has to change its appearance, so refresh 6691 * the drawable state. 6692 */ 6693 refreshDrawableState(); 6694 6695 // Invalidate too, since the default behavior for views is to be 6696 // be drawn at 50% alpha rather than to change the drawable. 6697 invalidate(true); 6698 6699 if (!enabled) { 6700 cancelPendingInputEvents(); 6701 } 6702 } 6703 6704 /** 6705 * Set whether this view can receive the focus. 6706 * 6707 * Setting this to false will also ensure that this view is not focusable 6708 * in touch mode. 6709 * 6710 * @param focusable If true, this view can receive the focus. 6711 * 6712 * @see #setFocusableInTouchMode(boolean) 6713 * @attr ref android.R.styleable#View_focusable 6714 */ 6715 public void setFocusable(boolean focusable) { 6716 if (!focusable) { 6717 setFlags(0, FOCUSABLE_IN_TOUCH_MODE); 6718 } 6719 setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK); 6720 } 6721 6722 /** 6723 * Set whether this view can receive focus while in touch mode. 6724 * 6725 * Setting this to true will also ensure that this view is focusable. 6726 * 6727 * @param focusableInTouchMode If true, this view can receive the focus while 6728 * in touch mode. 6729 * 6730 * @see #setFocusable(boolean) 6731 * @attr ref android.R.styleable#View_focusableInTouchMode 6732 */ 6733 public void setFocusableInTouchMode(boolean focusableInTouchMode) { 6734 // Focusable in touch mode should always be set before the focusable flag 6735 // otherwise, setting the focusable flag will trigger a focusableViewAvailable() 6736 // which, in touch mode, will not successfully request focus on this view 6737 // because the focusable in touch mode flag is not set 6738 setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE); 6739 if (focusableInTouchMode) { 6740 setFlags(FOCUSABLE, FOCUSABLE_MASK); 6741 } 6742 } 6743 6744 /** 6745 * Set whether this view should have sound effects enabled for events such as 6746 * clicking and touching. 6747 * 6748 * <p>You may wish to disable sound effects for a view if you already play sounds, 6749 * for instance, a dial key that plays dtmf tones. 6750 * 6751 * @param soundEffectsEnabled whether sound effects are enabled for this view. 6752 * @see #isSoundEffectsEnabled() 6753 * @see #playSoundEffect(int) 6754 * @attr ref android.R.styleable#View_soundEffectsEnabled 6755 */ 6756 public void setSoundEffectsEnabled(boolean soundEffectsEnabled) { 6757 setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED); 6758 } 6759 6760 /** 6761 * @return whether this view should have sound effects enabled for events such as 6762 * clicking and touching. 6763 * 6764 * @see #setSoundEffectsEnabled(boolean) 6765 * @see #playSoundEffect(int) 6766 * @attr ref android.R.styleable#View_soundEffectsEnabled 6767 */ 6768 @ViewDebug.ExportedProperty 6769 public boolean isSoundEffectsEnabled() { 6770 return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED); 6771 } 6772 6773 /** 6774 * Set whether this view should have haptic feedback for events such as 6775 * long presses. 6776 * 6777 * <p>You may wish to disable haptic feedback if your view already controls 6778 * its own haptic feedback. 6779 * 6780 * @param hapticFeedbackEnabled whether haptic feedback enabled for this view. 6781 * @see #isHapticFeedbackEnabled() 6782 * @see #performHapticFeedback(int) 6783 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6784 */ 6785 public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) { 6786 setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED); 6787 } 6788 6789 /** 6790 * @return whether this view should have haptic feedback enabled for events 6791 * long presses. 6792 * 6793 * @see #setHapticFeedbackEnabled(boolean) 6794 * @see #performHapticFeedback(int) 6795 * @attr ref android.R.styleable#View_hapticFeedbackEnabled 6796 */ 6797 @ViewDebug.ExportedProperty 6798 public boolean isHapticFeedbackEnabled() { 6799 return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED); 6800 } 6801 6802 /** 6803 * Returns the layout direction for this view. 6804 * 6805 * @return One of {@link #LAYOUT_DIRECTION_LTR}, 6806 * {@link #LAYOUT_DIRECTION_RTL}, 6807 * {@link #LAYOUT_DIRECTION_INHERIT} or 6808 * {@link #LAYOUT_DIRECTION_LOCALE}. 6809 * 6810 * @attr ref android.R.styleable#View_layoutDirection 6811 * 6812 * @hide 6813 */ 6814 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6815 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "LTR"), 6816 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RTL"), 6817 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_INHERIT, to = "INHERIT"), 6818 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LOCALE, to = "LOCALE") 6819 }) 6820 @LayoutDir 6821 public int getRawLayoutDirection() { 6822 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT; 6823 } 6824 6825 /** 6826 * Set the layout direction for this view. This will propagate a reset of layout direction 6827 * resolution to the view's children and resolve layout direction for this view. 6828 * 6829 * @param layoutDirection the layout direction to set. Should be one of: 6830 * 6831 * {@link #LAYOUT_DIRECTION_LTR}, 6832 * {@link #LAYOUT_DIRECTION_RTL}, 6833 * {@link #LAYOUT_DIRECTION_INHERIT}, 6834 * {@link #LAYOUT_DIRECTION_LOCALE}. 6835 * 6836 * Resolution will be done if the value is set to LAYOUT_DIRECTION_INHERIT. The resolution 6837 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 6838 * will return the default {@link #LAYOUT_DIRECTION_LTR}. 6839 * 6840 * @attr ref android.R.styleable#View_layoutDirection 6841 */ 6842 @RemotableViewMethod 6843 public void setLayoutDirection(@LayoutDir int layoutDirection) { 6844 if (getRawLayoutDirection() != layoutDirection) { 6845 // Reset the current layout direction and the resolved one 6846 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_MASK; 6847 resetRtlProperties(); 6848 // Set the new layout direction (filtered) 6849 mPrivateFlags2 |= 6850 ((layoutDirection << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) & PFLAG2_LAYOUT_DIRECTION_MASK); 6851 // We need to resolve all RTL properties as they all depend on layout direction 6852 resolveRtlPropertiesIfNeeded(); 6853 requestLayout(); 6854 invalidate(true); 6855 } 6856 } 6857 6858 /** 6859 * Returns the resolved layout direction for this view. 6860 * 6861 * @return {@link #LAYOUT_DIRECTION_RTL} if the layout direction is RTL or returns 6862 * {@link #LAYOUT_DIRECTION_LTR} if the layout direction is not RTL. 6863 * 6864 * For compatibility, this will return {@link #LAYOUT_DIRECTION_LTR} if API version 6865 * is lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}. 6866 * 6867 * @attr ref android.R.styleable#View_layoutDirection 6868 */ 6869 @ViewDebug.ExportedProperty(category = "layout", mapping = { 6870 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_LTR, to = "RESOLVED_DIRECTION_LTR"), 6871 @ViewDebug.IntToString(from = LAYOUT_DIRECTION_RTL, to = "RESOLVED_DIRECTION_RTL") 6872 }) 6873 @ResolvedLayoutDir 6874 public int getLayoutDirection() { 6875 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 6876 if (targetSdkVersion < JELLY_BEAN_MR1) { 6877 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 6878 return LAYOUT_DIRECTION_RESOLVED_DEFAULT; 6879 } 6880 return ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) == 6881 PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL) ? LAYOUT_DIRECTION_RTL : LAYOUT_DIRECTION_LTR; 6882 } 6883 6884 /** 6885 * Indicates whether or not this view's layout is right-to-left. This is resolved from 6886 * layout attribute and/or the inherited value from the parent 6887 * 6888 * @return true if the layout is right-to-left. 6889 * 6890 * @hide 6891 */ 6892 @ViewDebug.ExportedProperty(category = "layout") 6893 public boolean isLayoutRtl() { 6894 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 6895 } 6896 6897 /** 6898 * Indicates whether the view is currently tracking transient state that the 6899 * app should not need to concern itself with saving and restoring, but that 6900 * the framework should take special note to preserve when possible. 6901 * 6902 * <p>A view with transient state cannot be trivially rebound from an external 6903 * data source, such as an adapter binding item views in a list. This may be 6904 * because the view is performing an animation, tracking user selection 6905 * of content, or similar.</p> 6906 * 6907 * @return true if the view has transient state 6908 */ 6909 @ViewDebug.ExportedProperty(category = "layout") 6910 public boolean hasTransientState() { 6911 return (mPrivateFlags2 & PFLAG2_HAS_TRANSIENT_STATE) == PFLAG2_HAS_TRANSIENT_STATE; 6912 } 6913 6914 /** 6915 * Set whether this view is currently tracking transient state that the 6916 * framework should attempt to preserve when possible. This flag is reference counted, 6917 * so every call to setHasTransientState(true) should be paired with a later call 6918 * to setHasTransientState(false). 6919 * 6920 * <p>A view with transient state cannot be trivially rebound from an external 6921 * data source, such as an adapter binding item views in a list. This may be 6922 * because the view is performing an animation, tracking user selection 6923 * of content, or similar.</p> 6924 * 6925 * @param hasTransientState true if this view has transient state 6926 */ 6927 public void setHasTransientState(boolean hasTransientState) { 6928 mTransientStateCount = hasTransientState ? mTransientStateCount + 1 : 6929 mTransientStateCount - 1; 6930 if (mTransientStateCount < 0) { 6931 mTransientStateCount = 0; 6932 Log.e(VIEW_LOG_TAG, "hasTransientState decremented below 0: " + 6933 "unmatched pair of setHasTransientState calls"); 6934 } else if ((hasTransientState && mTransientStateCount == 1) || 6935 (!hasTransientState && mTransientStateCount == 0)) { 6936 // update flag if we've just incremented up from 0 or decremented down to 0 6937 mPrivateFlags2 = (mPrivateFlags2 & ~PFLAG2_HAS_TRANSIENT_STATE) | 6938 (hasTransientState ? PFLAG2_HAS_TRANSIENT_STATE : 0); 6939 if (mParent != null) { 6940 try { 6941 mParent.childHasTransientStateChanged(this, hasTransientState); 6942 } catch (AbstractMethodError e) { 6943 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 6944 " does not fully implement ViewParent", e); 6945 } 6946 } 6947 } 6948 } 6949 6950 /** 6951 * Returns true if this view is currently attached to a window. 6952 */ 6953 public boolean isAttachedToWindow() { 6954 return mAttachInfo != null; 6955 } 6956 6957 /** 6958 * Returns true if this view has been through at least one layout since it 6959 * was last attached to or detached from a window. 6960 */ 6961 public boolean isLaidOut() { 6962 return (mPrivateFlags3 & PFLAG3_IS_LAID_OUT) == PFLAG3_IS_LAID_OUT; 6963 } 6964 6965 /** 6966 * If this view doesn't do any drawing on its own, set this flag to 6967 * allow further optimizations. By default, this flag is not set on 6968 * View, but could be set on some View subclasses such as ViewGroup. 6969 * 6970 * Typically, if you override {@link #onDraw(android.graphics.Canvas)} 6971 * you should clear this flag. 6972 * 6973 * @param willNotDraw whether or not this View draw on its own 6974 */ 6975 public void setWillNotDraw(boolean willNotDraw) { 6976 setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK); 6977 } 6978 6979 /** 6980 * Returns whether or not this View draws on its own. 6981 * 6982 * @return true if this view has nothing to draw, false otherwise 6983 */ 6984 @ViewDebug.ExportedProperty(category = "drawing") 6985 public boolean willNotDraw() { 6986 return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW; 6987 } 6988 6989 /** 6990 * When a View's drawing cache is enabled, drawing is redirected to an 6991 * offscreen bitmap. Some views, like an ImageView, must be able to 6992 * bypass this mechanism if they already draw a single bitmap, to avoid 6993 * unnecessary usage of the memory. 6994 * 6995 * @param willNotCacheDrawing true if this view does not cache its 6996 * drawing, false otherwise 6997 */ 6998 public void setWillNotCacheDrawing(boolean willNotCacheDrawing) { 6999 setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING); 7000 } 7001 7002 /** 7003 * Returns whether or not this View can cache its drawing or not. 7004 * 7005 * @return true if this view does not cache its drawing, false otherwise 7006 */ 7007 @ViewDebug.ExportedProperty(category = "drawing") 7008 public boolean willNotCacheDrawing() { 7009 return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING; 7010 } 7011 7012 /** 7013 * Indicates whether this view reacts to click events or not. 7014 * 7015 * @return true if the view is clickable, false otherwise 7016 * 7017 * @see #setClickable(boolean) 7018 * @attr ref android.R.styleable#View_clickable 7019 */ 7020 @ViewDebug.ExportedProperty 7021 public boolean isClickable() { 7022 return (mViewFlags & CLICKABLE) == CLICKABLE; 7023 } 7024 7025 /** 7026 * Enables or disables click events for this view. When a view 7027 * is clickable it will change its state to "pressed" on every click. 7028 * Subclasses should set the view clickable to visually react to 7029 * user's clicks. 7030 * 7031 * @param clickable true to make the view clickable, false otherwise 7032 * 7033 * @see #isClickable() 7034 * @attr ref android.R.styleable#View_clickable 7035 */ 7036 public void setClickable(boolean clickable) { 7037 setFlags(clickable ? CLICKABLE : 0, CLICKABLE); 7038 } 7039 7040 /** 7041 * Indicates whether this view reacts to long click events or not. 7042 * 7043 * @return true if the view is long clickable, false otherwise 7044 * 7045 * @see #setLongClickable(boolean) 7046 * @attr ref android.R.styleable#View_longClickable 7047 */ 7048 public boolean isLongClickable() { 7049 return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 7050 } 7051 7052 /** 7053 * Enables or disables long click events for this view. When a view is long 7054 * clickable it reacts to the user holding down the button for a longer 7055 * duration than a tap. This event can either launch the listener or a 7056 * context menu. 7057 * 7058 * @param longClickable true to make the view long clickable, false otherwise 7059 * @see #isLongClickable() 7060 * @attr ref android.R.styleable#View_longClickable 7061 */ 7062 public void setLongClickable(boolean longClickable) { 7063 setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE); 7064 } 7065 7066 /** 7067 * Sets the pressed state for this view and provides a touch coordinate for 7068 * animation hinting. 7069 * 7070 * @param pressed Pass true to set the View's internal state to "pressed", 7071 * or false to reverts the View's internal state from a 7072 * previously set "pressed" state. 7073 * @param x The x coordinate of the touch that caused the press 7074 * @param y The y coordinate of the touch that caused the press 7075 */ 7076 private void setPressed(boolean pressed, float x, float y) { 7077 if (pressed) { 7078 drawableHotspotChanged(x, y); 7079 } 7080 7081 setPressed(pressed); 7082 } 7083 7084 /** 7085 * Sets the pressed state for this view. 7086 * 7087 * @see #isClickable() 7088 * @see #setClickable(boolean) 7089 * 7090 * @param pressed Pass true to set the View's internal state to "pressed", or false to reverts 7091 * the View's internal state from a previously set "pressed" state. 7092 */ 7093 public void setPressed(boolean pressed) { 7094 final boolean needsRefresh = pressed != ((mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED); 7095 7096 if (pressed) { 7097 mPrivateFlags |= PFLAG_PRESSED; 7098 } else { 7099 mPrivateFlags &= ~PFLAG_PRESSED; 7100 } 7101 7102 if (needsRefresh) { 7103 refreshDrawableState(); 7104 } 7105 dispatchSetPressed(pressed); 7106 } 7107 7108 /** 7109 * Dispatch setPressed to all of this View's children. 7110 * 7111 * @see #setPressed(boolean) 7112 * 7113 * @param pressed The new pressed state 7114 */ 7115 protected void dispatchSetPressed(boolean pressed) { 7116 } 7117 7118 /** 7119 * Indicates whether the view is currently in pressed state. Unless 7120 * {@link #setPressed(boolean)} is explicitly called, only clickable views can enter 7121 * the pressed state. 7122 * 7123 * @see #setPressed(boolean) 7124 * @see #isClickable() 7125 * @see #setClickable(boolean) 7126 * 7127 * @return true if the view is currently pressed, false otherwise 7128 */ 7129 @ViewDebug.ExportedProperty 7130 public boolean isPressed() { 7131 return (mPrivateFlags & PFLAG_PRESSED) == PFLAG_PRESSED; 7132 } 7133 7134 /** 7135 * Indicates whether this view will save its state (that is, 7136 * whether its {@link #onSaveInstanceState} method will be called). 7137 * 7138 * @return Returns true if the view state saving is enabled, else false. 7139 * 7140 * @see #setSaveEnabled(boolean) 7141 * @attr ref android.R.styleable#View_saveEnabled 7142 */ 7143 public boolean isSaveEnabled() { 7144 return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED; 7145 } 7146 7147 /** 7148 * Controls whether the saving of this view's state is 7149 * enabled (that is, whether its {@link #onSaveInstanceState} method 7150 * will be called). Note that even if freezing is enabled, the 7151 * view still must have an id assigned to it (via {@link #setId(int)}) 7152 * for its state to be saved. This flag can only disable the 7153 * saving of this view; any child views may still have their state saved. 7154 * 7155 * @param enabled Set to false to <em>disable</em> state saving, or true 7156 * (the default) to allow it. 7157 * 7158 * @see #isSaveEnabled() 7159 * @see #setId(int) 7160 * @see #onSaveInstanceState() 7161 * @attr ref android.R.styleable#View_saveEnabled 7162 */ 7163 public void setSaveEnabled(boolean enabled) { 7164 setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK); 7165 } 7166 7167 /** 7168 * Gets whether the framework should discard touches when the view's 7169 * window is obscured by another visible window. 7170 * Refer to the {@link View} security documentation for more details. 7171 * 7172 * @return True if touch filtering is enabled. 7173 * 7174 * @see #setFilterTouchesWhenObscured(boolean) 7175 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7176 */ 7177 @ViewDebug.ExportedProperty 7178 public boolean getFilterTouchesWhenObscured() { 7179 return (mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0; 7180 } 7181 7182 /** 7183 * Sets whether the framework should discard touches when the view's 7184 * window is obscured by another visible window. 7185 * Refer to the {@link View} security documentation for more details. 7186 * 7187 * @param enabled True if touch filtering should be enabled. 7188 * 7189 * @see #getFilterTouchesWhenObscured 7190 * @attr ref android.R.styleable#View_filterTouchesWhenObscured 7191 */ 7192 public void setFilterTouchesWhenObscured(boolean enabled) { 7193 setFlags(enabled ? FILTER_TOUCHES_WHEN_OBSCURED : 0, 7194 FILTER_TOUCHES_WHEN_OBSCURED); 7195 } 7196 7197 /** 7198 * Indicates whether the entire hierarchy under this view will save its 7199 * state when a state saving traversal occurs from its parent. The default 7200 * is true; if false, these views will not be saved unless 7201 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7202 * 7203 * @return Returns true if the view state saving from parent is enabled, else false. 7204 * 7205 * @see #setSaveFromParentEnabled(boolean) 7206 */ 7207 public boolean isSaveFromParentEnabled() { 7208 return (mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED; 7209 } 7210 7211 /** 7212 * Controls whether the entire hierarchy under this view will save its 7213 * state when a state saving traversal occurs from its parent. The default 7214 * is true; if false, these views will not be saved unless 7215 * {@link #saveHierarchyState(SparseArray)} is called directly on this view. 7216 * 7217 * @param enabled Set to false to <em>disable</em> state saving, or true 7218 * (the default) to allow it. 7219 * 7220 * @see #isSaveFromParentEnabled() 7221 * @see #setId(int) 7222 * @see #onSaveInstanceState() 7223 */ 7224 public void setSaveFromParentEnabled(boolean enabled) { 7225 setFlags(enabled ? 0 : PARENT_SAVE_DISABLED, PARENT_SAVE_DISABLED_MASK); 7226 } 7227 7228 7229 /** 7230 * Returns whether this View is able to take focus. 7231 * 7232 * @return True if this view can take focus, or false otherwise. 7233 * @attr ref android.R.styleable#View_focusable 7234 */ 7235 @ViewDebug.ExportedProperty(category = "focus") 7236 public final boolean isFocusable() { 7237 return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK); 7238 } 7239 7240 /** 7241 * When a view is focusable, it may not want to take focus when in touch mode. 7242 * For example, a button would like focus when the user is navigating via a D-pad 7243 * so that the user can click on it, but once the user starts touching the screen, 7244 * the button shouldn't take focus 7245 * @return Whether the view is focusable in touch mode. 7246 * @attr ref android.R.styleable#View_focusableInTouchMode 7247 */ 7248 @ViewDebug.ExportedProperty 7249 public final boolean isFocusableInTouchMode() { 7250 return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE); 7251 } 7252 7253 /** 7254 * Find the nearest view in the specified direction that can take focus. 7255 * This does not actually give focus to that view. 7256 * 7257 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7258 * 7259 * @return The nearest focusable in the specified direction, or null if none 7260 * can be found. 7261 */ 7262 public View focusSearch(@FocusRealDirection int direction) { 7263 if (mParent != null) { 7264 return mParent.focusSearch(this, direction); 7265 } else { 7266 return null; 7267 } 7268 } 7269 7270 /** 7271 * This method is the last chance for the focused view and its ancestors to 7272 * respond to an arrow key. This is called when the focused view did not 7273 * consume the key internally, nor could the view system find a new view in 7274 * the requested direction to give focus to. 7275 * 7276 * @param focused The currently focused view. 7277 * @param direction The direction focus wants to move. One of FOCUS_UP, 7278 * FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT. 7279 * @return True if the this view consumed this unhandled move. 7280 */ 7281 public boolean dispatchUnhandledMove(View focused, @FocusRealDirection int direction) { 7282 return false; 7283 } 7284 7285 /** 7286 * If a user manually specified the next view id for a particular direction, 7287 * use the root to look up the view. 7288 * @param root The root view of the hierarchy containing this view. 7289 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, 7290 * or FOCUS_BACKWARD. 7291 * @return The user specified next view, or null if there is none. 7292 */ 7293 View findUserSetNextFocus(View root, @FocusDirection int direction) { 7294 switch (direction) { 7295 case FOCUS_LEFT: 7296 if (mNextFocusLeftId == View.NO_ID) return null; 7297 return findViewInsideOutShouldExist(root, mNextFocusLeftId); 7298 case FOCUS_RIGHT: 7299 if (mNextFocusRightId == View.NO_ID) return null; 7300 return findViewInsideOutShouldExist(root, mNextFocusRightId); 7301 case FOCUS_UP: 7302 if (mNextFocusUpId == View.NO_ID) return null; 7303 return findViewInsideOutShouldExist(root, mNextFocusUpId); 7304 case FOCUS_DOWN: 7305 if (mNextFocusDownId == View.NO_ID) return null; 7306 return findViewInsideOutShouldExist(root, mNextFocusDownId); 7307 case FOCUS_FORWARD: 7308 if (mNextFocusForwardId == View.NO_ID) return null; 7309 return findViewInsideOutShouldExist(root, mNextFocusForwardId); 7310 case FOCUS_BACKWARD: { 7311 if (mID == View.NO_ID) return null; 7312 final int id = mID; 7313 return root.findViewByPredicateInsideOut(this, new Predicate<View>() { 7314 @Override 7315 public boolean apply(View t) { 7316 return t.mNextFocusForwardId == id; 7317 } 7318 }); 7319 } 7320 } 7321 return null; 7322 } 7323 7324 private View findViewInsideOutShouldExist(View root, int id) { 7325 if (mMatchIdPredicate == null) { 7326 mMatchIdPredicate = new MatchIdPredicate(); 7327 } 7328 mMatchIdPredicate.mId = id; 7329 View result = root.findViewByPredicateInsideOut(this, mMatchIdPredicate); 7330 if (result == null) { 7331 Log.w(VIEW_LOG_TAG, "couldn't find view with id " + id); 7332 } 7333 return result; 7334 } 7335 7336 /** 7337 * Find and return all focusable views that are descendants of this view, 7338 * possibly including this view if it is focusable itself. 7339 * 7340 * @param direction The direction of the focus 7341 * @return A list of focusable views 7342 */ 7343 public ArrayList<View> getFocusables(@FocusDirection int direction) { 7344 ArrayList<View> result = new ArrayList<View>(24); 7345 addFocusables(result, direction); 7346 return result; 7347 } 7348 7349 /** 7350 * Add any focusable views that are descendants of this view (possibly 7351 * including this view if it is focusable itself) to views. If we are in touch mode, 7352 * only add views that are also focusable in touch mode. 7353 * 7354 * @param views Focusable views found so far 7355 * @param direction The direction of the focus 7356 */ 7357 public void addFocusables(ArrayList<View> views, @FocusDirection int direction) { 7358 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 7359 } 7360 7361 /** 7362 * Adds any focusable views that are descendants of this view (possibly 7363 * including this view if it is focusable itself) to views. This method 7364 * adds all focusable views regardless if we are in touch mode or 7365 * only views focusable in touch mode if we are in touch mode or 7366 * only views that can take accessibility focus if accessibility is enabeld 7367 * depending on the focusable mode paramater. 7368 * 7369 * @param views Focusable views found so far or null if all we are interested is 7370 * the number of focusables. 7371 * @param direction The direction of the focus. 7372 * @param focusableMode The type of focusables to be added. 7373 * 7374 * @see #FOCUSABLES_ALL 7375 * @see #FOCUSABLES_TOUCH_MODE 7376 */ 7377 public void addFocusables(ArrayList<View> views, @FocusDirection int direction, 7378 @FocusableMode int focusableMode) { 7379 if (views == null) { 7380 return; 7381 } 7382 if (!isFocusable()) { 7383 return; 7384 } 7385 if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE 7386 && isInTouchMode() && !isFocusableInTouchMode()) { 7387 return; 7388 } 7389 views.add(this); 7390 } 7391 7392 /** 7393 * Finds the Views that contain given text. The containment is case insensitive. 7394 * The search is performed by either the text that the View renders or the content 7395 * description that describes the view for accessibility purposes and the view does 7396 * not render or both. Clients can specify how the search is to be performed via 7397 * passing the {@link #FIND_VIEWS_WITH_TEXT} and 7398 * {@link #FIND_VIEWS_WITH_CONTENT_DESCRIPTION} flags. 7399 * 7400 * @param outViews The output list of matching Views. 7401 * @param searched The text to match against. 7402 * 7403 * @see #FIND_VIEWS_WITH_TEXT 7404 * @see #FIND_VIEWS_WITH_CONTENT_DESCRIPTION 7405 * @see #setContentDescription(CharSequence) 7406 */ 7407 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, 7408 @FindViewFlags int flags) { 7409 if (getAccessibilityNodeProvider() != null) { 7410 if ((flags & FIND_VIEWS_WITH_ACCESSIBILITY_NODE_PROVIDERS) != 0) { 7411 outViews.add(this); 7412 } 7413 } else if ((flags & FIND_VIEWS_WITH_CONTENT_DESCRIPTION) != 0 7414 && (searched != null && searched.length() > 0) 7415 && (mContentDescription != null && mContentDescription.length() > 0)) { 7416 String searchedLowerCase = searched.toString().toLowerCase(); 7417 String contentDescriptionLowerCase = mContentDescription.toString().toLowerCase(); 7418 if (contentDescriptionLowerCase.contains(searchedLowerCase)) { 7419 outViews.add(this); 7420 } 7421 } 7422 } 7423 7424 /** 7425 * Find and return all touchable views that are descendants of this view, 7426 * possibly including this view if it is touchable itself. 7427 * 7428 * @return A list of touchable views 7429 */ 7430 public ArrayList<View> getTouchables() { 7431 ArrayList<View> result = new ArrayList<View>(); 7432 addTouchables(result); 7433 return result; 7434 } 7435 7436 /** 7437 * Add any touchable views that are descendants of this view (possibly 7438 * including this view if it is touchable itself) to views. 7439 * 7440 * @param views Touchable views found so far 7441 */ 7442 public void addTouchables(ArrayList<View> views) { 7443 final int viewFlags = mViewFlags; 7444 7445 if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 7446 && (viewFlags & ENABLED_MASK) == ENABLED) { 7447 views.add(this); 7448 } 7449 } 7450 7451 /** 7452 * Returns whether this View is accessibility focused. 7453 * 7454 * @return True if this View is accessibility focused. 7455 */ 7456 public boolean isAccessibilityFocused() { 7457 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0; 7458 } 7459 7460 /** 7461 * Call this to try to give accessibility focus to this view. 7462 * 7463 * A view will not actually take focus if {@link AccessibilityManager#isEnabled()} 7464 * returns false or the view is no visible or the view already has accessibility 7465 * focus. 7466 * 7467 * See also {@link #focusSearch(int)}, which is what you call to say that you 7468 * have focus, and you want your parent to look for the next one. 7469 * 7470 * @return Whether this view actually took accessibility focus. 7471 * 7472 * @hide 7473 */ 7474 public boolean requestAccessibilityFocus() { 7475 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 7476 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 7477 return false; 7478 } 7479 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7480 return false; 7481 } 7482 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) == 0) { 7483 mPrivateFlags2 |= PFLAG2_ACCESSIBILITY_FOCUSED; 7484 ViewRootImpl viewRootImpl = getViewRootImpl(); 7485 if (viewRootImpl != null) { 7486 viewRootImpl.setAccessibilityFocus(this, null); 7487 } 7488 invalidate(); 7489 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); 7490 return true; 7491 } 7492 return false; 7493 } 7494 7495 /** 7496 * Call this to try to clear accessibility focus of this view. 7497 * 7498 * See also {@link #focusSearch(int)}, which is what you call to say that you 7499 * have focus, and you want your parent to look for the next one. 7500 * 7501 * @hide 7502 */ 7503 public void clearAccessibilityFocus() { 7504 clearAccessibilityFocusNoCallbacks(); 7505 // Clear the global reference of accessibility focus if this 7506 // view or any of its descendants had accessibility focus. 7507 ViewRootImpl viewRootImpl = getViewRootImpl(); 7508 if (viewRootImpl != null) { 7509 View focusHost = viewRootImpl.getAccessibilityFocusedHost(); 7510 if (focusHost != null && ViewRootImpl.isViewDescendantOf(focusHost, this)) { 7511 viewRootImpl.setAccessibilityFocus(null, null); 7512 } 7513 } 7514 } 7515 7516 private void sendAccessibilityHoverEvent(int eventType) { 7517 // Since we are not delivering to a client accessibility events from not 7518 // important views (unless the clinet request that) we need to fire the 7519 // event from the deepest view exposed to the client. As a consequence if 7520 // the user crosses a not exposed view the client will see enter and exit 7521 // of the exposed predecessor followed by and enter and exit of that same 7522 // predecessor when entering and exiting the not exposed descendant. This 7523 // is fine since the client has a clear idea which view is hovered at the 7524 // price of a couple more events being sent. This is a simple and 7525 // working solution. 7526 View source = this; 7527 while (true) { 7528 if (source.includeForAccessibility()) { 7529 source.sendAccessibilityEvent(eventType); 7530 return; 7531 } 7532 ViewParent parent = source.getParent(); 7533 if (parent instanceof View) { 7534 source = (View) parent; 7535 } else { 7536 return; 7537 } 7538 } 7539 } 7540 7541 /** 7542 * Clears accessibility focus without calling any callback methods 7543 * normally invoked in {@link #clearAccessibilityFocus()}. This method 7544 * is used for clearing accessibility focus when giving this focus to 7545 * another view. 7546 */ 7547 void clearAccessibilityFocusNoCallbacks() { 7548 if ((mPrivateFlags2 & PFLAG2_ACCESSIBILITY_FOCUSED) != 0) { 7549 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_FOCUSED; 7550 invalidate(); 7551 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); 7552 } 7553 } 7554 7555 /** 7556 * Call this to try to give focus to a specific view or to one of its 7557 * descendants. 7558 * 7559 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7560 * false), or if it is focusable and it is not focusable in touch mode 7561 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7562 * 7563 * See also {@link #focusSearch(int)}, which is what you call to say that you 7564 * have focus, and you want your parent to look for the next one. 7565 * 7566 * This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments 7567 * {@link #FOCUS_DOWN} and <code>null</code>. 7568 * 7569 * @return Whether this view or one of its descendants actually took focus. 7570 */ 7571 public final boolean requestFocus() { 7572 return requestFocus(View.FOCUS_DOWN); 7573 } 7574 7575 /** 7576 * Call this to try to give focus to a specific view or to one of its 7577 * descendants and give it a hint about what direction focus is heading. 7578 * 7579 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7580 * false), or if it is focusable and it is not focusable in touch mode 7581 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7582 * 7583 * See also {@link #focusSearch(int)}, which is what you call to say that you 7584 * have focus, and you want your parent to look for the next one. 7585 * 7586 * This is equivalent to calling {@link #requestFocus(int, Rect)} with 7587 * <code>null</code> set for the previously focused rectangle. 7588 * 7589 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7590 * @return Whether this view or one of its descendants actually took focus. 7591 */ 7592 public final boolean requestFocus(int direction) { 7593 return requestFocus(direction, null); 7594 } 7595 7596 /** 7597 * Call this to try to give focus to a specific view or to one of its descendants 7598 * and give it hints about the direction and a specific rectangle that the focus 7599 * is coming from. The rectangle can help give larger views a finer grained hint 7600 * about where focus is coming from, and therefore, where to show selection, or 7601 * forward focus change internally. 7602 * 7603 * A view will not actually take focus if it is not focusable ({@link #isFocusable} returns 7604 * false), or if it is focusable and it is not focusable in touch mode 7605 * ({@link #isFocusableInTouchMode}) while the device is in touch mode. 7606 * 7607 * A View will not take focus if it is not visible. 7608 * 7609 * A View will not take focus if one of its parents has 7610 * {@link android.view.ViewGroup#getDescendantFocusability()} equal to 7611 * {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}. 7612 * 7613 * See also {@link #focusSearch(int)}, which is what you call to say that you 7614 * have focus, and you want your parent to look for the next one. 7615 * 7616 * You may wish to override this method if your custom {@link View} has an internal 7617 * {@link View} that it wishes to forward the request to. 7618 * 7619 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 7620 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 7621 * to give a finer grained hint about where focus is coming from. May be null 7622 * if there is no hint. 7623 * @return Whether this view or one of its descendants actually took focus. 7624 */ 7625 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 7626 return requestFocusNoSearch(direction, previouslyFocusedRect); 7627 } 7628 7629 private boolean requestFocusNoSearch(int direction, Rect previouslyFocusedRect) { 7630 // need to be focusable 7631 if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE || 7632 (mViewFlags & VISIBILITY_MASK) != VISIBLE) { 7633 return false; 7634 } 7635 7636 // need to be focusable in touch mode if in touch mode 7637 if (isInTouchMode() && 7638 (FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) { 7639 return false; 7640 } 7641 7642 // need to not have any parents blocking us 7643 if (hasAncestorThatBlocksDescendantFocus()) { 7644 return false; 7645 } 7646 7647 handleFocusGainInternal(direction, previouslyFocusedRect); 7648 return true; 7649 } 7650 7651 /** 7652 * Call this to try to give focus to a specific view or to one of its descendants. This is a 7653 * special variant of {@link #requestFocus() } that will allow views that are not focuable in 7654 * touch mode to request focus when they are touched. 7655 * 7656 * @return Whether this view or one of its descendants actually took focus. 7657 * 7658 * @see #isInTouchMode() 7659 * 7660 */ 7661 public final boolean requestFocusFromTouch() { 7662 // Leave touch mode if we need to 7663 if (isInTouchMode()) { 7664 ViewRootImpl viewRoot = getViewRootImpl(); 7665 if (viewRoot != null) { 7666 viewRoot.ensureTouchMode(false); 7667 } 7668 } 7669 return requestFocus(View.FOCUS_DOWN); 7670 } 7671 7672 /** 7673 * @return Whether any ancestor of this view blocks descendant focus. 7674 */ 7675 private boolean hasAncestorThatBlocksDescendantFocus() { 7676 final boolean focusableInTouchMode = isFocusableInTouchMode(); 7677 ViewParent ancestor = mParent; 7678 while (ancestor instanceof ViewGroup) { 7679 final ViewGroup vgAncestor = (ViewGroup) ancestor; 7680 if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS 7681 || (!focusableInTouchMode && vgAncestor.shouldBlockFocusForTouchscreen())) { 7682 return true; 7683 } else { 7684 ancestor = vgAncestor.getParent(); 7685 } 7686 } 7687 return false; 7688 } 7689 7690 /** 7691 * Gets the mode for determining whether this View is important for accessibility 7692 * which is if it fires accessibility events and if it is reported to 7693 * accessibility services that query the screen. 7694 * 7695 * @return The mode for determining whether a View is important for accessibility. 7696 * 7697 * @attr ref android.R.styleable#View_importantForAccessibility 7698 * 7699 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7700 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7701 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7702 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7703 */ 7704 @ViewDebug.ExportedProperty(category = "accessibility", mapping = { 7705 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_AUTO, to = "auto"), 7706 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_YES, to = "yes"), 7707 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO, to = "no"), 7708 @ViewDebug.IntToString(from = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS, 7709 to = "noHideDescendants") 7710 }) 7711 public int getImportantForAccessibility() { 7712 return (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7713 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7714 } 7715 7716 /** 7717 * Sets the live region mode for this view. This indicates to accessibility 7718 * services whether they should automatically notify the user about changes 7719 * to the view's content description or text, or to the content descriptions 7720 * or text of the view's children (where applicable). 7721 * <p> 7722 * For example, in a login screen with a TextView that displays an "incorrect 7723 * password" notification, that view should be marked as a live region with 7724 * mode {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7725 * <p> 7726 * To disable change notifications for this view, use 7727 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. This is the default live region 7728 * mode for most views. 7729 * <p> 7730 * To indicate that the user should be notified of changes, use 7731 * {@link #ACCESSIBILITY_LIVE_REGION_POLITE}. 7732 * <p> 7733 * If the view's changes should interrupt ongoing speech and notify the user 7734 * immediately, use {@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE}. 7735 * 7736 * @param mode The live region mode for this view, one of: 7737 * <ul> 7738 * <li>{@link #ACCESSIBILITY_LIVE_REGION_NONE} 7739 * <li>{@link #ACCESSIBILITY_LIVE_REGION_POLITE} 7740 * <li>{@link #ACCESSIBILITY_LIVE_REGION_ASSERTIVE} 7741 * </ul> 7742 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7743 */ 7744 public void setAccessibilityLiveRegion(int mode) { 7745 if (mode != getAccessibilityLiveRegion()) { 7746 mPrivateFlags2 &= ~PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7747 mPrivateFlags2 |= (mode << PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT) 7748 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK; 7749 notifyViewAccessibilityStateChangedIfNeeded( 7750 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7751 } 7752 } 7753 7754 /** 7755 * Gets the live region mode for this View. 7756 * 7757 * @return The live region mode for the view. 7758 * 7759 * @attr ref android.R.styleable#View_accessibilityLiveRegion 7760 * 7761 * @see #setAccessibilityLiveRegion(int) 7762 */ 7763 public int getAccessibilityLiveRegion() { 7764 return (mPrivateFlags2 & PFLAG2_ACCESSIBILITY_LIVE_REGION_MASK) 7765 >> PFLAG2_ACCESSIBILITY_LIVE_REGION_SHIFT; 7766 } 7767 7768 /** 7769 * Sets how to determine whether this view is important for accessibility 7770 * which is if it fires accessibility events and if it is reported to 7771 * accessibility services that query the screen. 7772 * 7773 * @param mode How to determine whether this view is important for accessibility. 7774 * 7775 * @attr ref android.R.styleable#View_importantForAccessibility 7776 * 7777 * @see #IMPORTANT_FOR_ACCESSIBILITY_YES 7778 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO 7779 * @see #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS 7780 * @see #IMPORTANT_FOR_ACCESSIBILITY_AUTO 7781 */ 7782 public void setImportantForAccessibility(int mode) { 7783 final int oldMode = getImportantForAccessibility(); 7784 if (mode != oldMode) { 7785 // If we're moving between AUTO and another state, we might not need 7786 // to send a subtree changed notification. We'll store the computed 7787 // importance, since we'll need to check it later to make sure. 7788 final boolean maySkipNotify = oldMode == IMPORTANT_FOR_ACCESSIBILITY_AUTO 7789 || mode == IMPORTANT_FOR_ACCESSIBILITY_AUTO; 7790 final boolean oldIncludeForAccessibility = maySkipNotify && includeForAccessibility(); 7791 mPrivateFlags2 &= ~PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7792 mPrivateFlags2 |= (mode << PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT) 7793 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK; 7794 if (!maySkipNotify || oldIncludeForAccessibility != includeForAccessibility()) { 7795 notifySubtreeAccessibilityStateChangedIfNeeded(); 7796 } else { 7797 notifyViewAccessibilityStateChangedIfNeeded( 7798 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 7799 } 7800 } 7801 } 7802 7803 /** 7804 * Computes whether this view should be exposed for accessibility. In 7805 * general, views that are interactive or provide information are exposed 7806 * while views that serve only as containers are hidden. 7807 * <p> 7808 * If an ancestor of this view has importance 7809 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, this method 7810 * returns <code>false</code>. 7811 * <p> 7812 * Otherwise, the value is computed according to the view's 7813 * {@link #getImportantForAccessibility()} value: 7814 * <ol> 7815 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_NO} or 7816 * {@link #IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS}, return <code>false 7817 * </code> 7818 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_YES}, return <code>true</code> 7819 * <li>{@link #IMPORTANT_FOR_ACCESSIBILITY_AUTO}, return <code>true</code> if 7820 * view satisfies any of the following: 7821 * <ul> 7822 * <li>Is actionable, e.g. {@link #isClickable()}, 7823 * {@link #isLongClickable()}, or {@link #isFocusable()} 7824 * <li>Has an {@link AccessibilityDelegate} 7825 * <li>Has an interaction listener, e.g. {@link OnTouchListener}, 7826 * {@link OnKeyListener}, etc. 7827 * <li>Is an accessibility live region, e.g. 7828 * {@link #getAccessibilityLiveRegion()} is not 7829 * {@link #ACCESSIBILITY_LIVE_REGION_NONE}. 7830 * </ul> 7831 * </ol> 7832 * 7833 * @return Whether the view is exposed for accessibility. 7834 * @see #setImportantForAccessibility(int) 7835 * @see #getImportantForAccessibility() 7836 */ 7837 public boolean isImportantForAccessibility() { 7838 final int mode = (mPrivateFlags2 & PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_MASK) 7839 >> PFLAG2_IMPORTANT_FOR_ACCESSIBILITY_SHIFT; 7840 if (mode == IMPORTANT_FOR_ACCESSIBILITY_NO 7841 || mode == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7842 return false; 7843 } 7844 7845 // Check parent mode to ensure we're not hidden. 7846 ViewParent parent = mParent; 7847 while (parent instanceof View) { 7848 if (((View) parent).getImportantForAccessibility() 7849 == IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) { 7850 return false; 7851 } 7852 parent = parent.getParent(); 7853 } 7854 7855 return mode == IMPORTANT_FOR_ACCESSIBILITY_YES || isActionableForAccessibility() 7856 || hasListenersForAccessibility() || getAccessibilityNodeProvider() != null 7857 || getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE; 7858 } 7859 7860 /** 7861 * Gets the parent for accessibility purposes. Note that the parent for 7862 * accessibility is not necessary the immediate parent. It is the first 7863 * predecessor that is important for accessibility. 7864 * 7865 * @return The parent for accessibility purposes. 7866 */ 7867 public ViewParent getParentForAccessibility() { 7868 if (mParent instanceof View) { 7869 View parentView = (View) mParent; 7870 if (parentView.includeForAccessibility()) { 7871 return mParent; 7872 } else { 7873 return mParent.getParentForAccessibility(); 7874 } 7875 } 7876 return null; 7877 } 7878 7879 /** 7880 * Adds the children of a given View for accessibility. Since some Views are 7881 * not important for accessibility the children for accessibility are not 7882 * necessarily direct children of the view, rather they are the first level of 7883 * descendants important for accessibility. 7884 * 7885 * @param children The list of children for accessibility. 7886 */ 7887 public void addChildrenForAccessibility(ArrayList<View> children) { 7888 7889 } 7890 7891 /** 7892 * Whether to regard this view for accessibility. A view is regarded for 7893 * accessibility if it is important for accessibility or the querying 7894 * accessibility service has explicitly requested that view not 7895 * important for accessibility are regarded. 7896 * 7897 * @return Whether to regard the view for accessibility. 7898 * 7899 * @hide 7900 */ 7901 public boolean includeForAccessibility() { 7902 if (mAttachInfo != null) { 7903 return (mAttachInfo.mAccessibilityFetchFlags 7904 & AccessibilityNodeInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS) != 0 7905 || isImportantForAccessibility(); 7906 } 7907 return false; 7908 } 7909 7910 /** 7911 * Returns whether the View is considered actionable from 7912 * accessibility perspective. Such view are important for 7913 * accessibility. 7914 * 7915 * @return True if the view is actionable for accessibility. 7916 * 7917 * @hide 7918 */ 7919 public boolean isActionableForAccessibility() { 7920 return (isClickable() || isLongClickable() || isFocusable()); 7921 } 7922 7923 /** 7924 * Returns whether the View has registered callbacks which makes it 7925 * important for accessibility. 7926 * 7927 * @return True if the view is actionable for accessibility. 7928 */ 7929 private boolean hasListenersForAccessibility() { 7930 ListenerInfo info = getListenerInfo(); 7931 return mTouchDelegate != null || info.mOnKeyListener != null 7932 || info.mOnTouchListener != null || info.mOnGenericMotionListener != null 7933 || info.mOnHoverListener != null || info.mOnDragListener != null; 7934 } 7935 7936 /** 7937 * Notifies that the accessibility state of this view changed. The change 7938 * is local to this view and does not represent structural changes such 7939 * as children and parent. For example, the view became focusable. The 7940 * notification is at at most once every 7941 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7942 * to avoid unnecessary load to the system. Also once a view has a pending 7943 * notification this method is a NOP until the notification has been sent. 7944 * 7945 * @hide 7946 */ 7947 public void notifyViewAccessibilityStateChangedIfNeeded(int changeType) { 7948 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7949 return; 7950 } 7951 if (mSendViewStateChangedAccessibilityEvent == null) { 7952 mSendViewStateChangedAccessibilityEvent = 7953 new SendViewStateChangedAccessibilityEvent(); 7954 } 7955 mSendViewStateChangedAccessibilityEvent.runOrPost(changeType); 7956 } 7957 7958 /** 7959 * Notifies that the accessibility state of this view changed. The change 7960 * is *not* local to this view and does represent structural changes such 7961 * as children and parent. For example, the view size changed. The 7962 * notification is at at most once every 7963 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()} 7964 * to avoid unnecessary load to the system. Also once a view has a pending 7965 * notification this method is a NOP until the notification has been sent. 7966 * 7967 * @hide 7968 */ 7969 public void notifySubtreeAccessibilityStateChangedIfNeeded() { 7970 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 7971 return; 7972 } 7973 if ((mPrivateFlags2 & PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED) == 0) { 7974 mPrivateFlags2 |= PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7975 if (mParent != null) { 7976 try { 7977 mParent.notifySubtreeAccessibilityStateChanged( 7978 this, this, AccessibilityEvent.CONTENT_CHANGE_TYPE_SUBTREE); 7979 } catch (AbstractMethodError e) { 7980 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 7981 " does not fully implement ViewParent", e); 7982 } 7983 } 7984 } 7985 } 7986 7987 /** 7988 * Reset the flag indicating the accessibility state of the subtree rooted 7989 * at this view changed. 7990 */ 7991 void resetSubtreeAccessibilityStateChanged() { 7992 mPrivateFlags2 &= ~PFLAG2_SUBTREE_ACCESSIBILITY_STATE_CHANGED; 7993 } 7994 7995 /** 7996 * Performs the specified accessibility action on the view. For 7997 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 7998 * <p> 7999 * If an {@link AccessibilityDelegate} has been specified via calling 8000 * {@link #setAccessibilityDelegate(AccessibilityDelegate)} its 8001 * {@link AccessibilityDelegate#performAccessibilityAction(View, int, Bundle)} 8002 * is responsible for handling this call. 8003 * </p> 8004 * 8005 * @param action The action to perform. 8006 * @param arguments Optional action arguments. 8007 * @return Whether the action was performed. 8008 */ 8009 public boolean performAccessibilityAction(int action, Bundle arguments) { 8010 if (mAccessibilityDelegate != null) { 8011 return mAccessibilityDelegate.performAccessibilityAction(this, action, arguments); 8012 } else { 8013 return performAccessibilityActionInternal(action, arguments); 8014 } 8015 } 8016 8017 /** 8018 * @see #performAccessibilityAction(int, Bundle) 8019 * 8020 * Note: Called from the default {@link AccessibilityDelegate}. 8021 */ 8022 boolean performAccessibilityActionInternal(int action, Bundle arguments) { 8023 switch (action) { 8024 case AccessibilityNodeInfo.ACTION_CLICK: { 8025 if (isClickable()) { 8026 performClick(); 8027 return true; 8028 } 8029 } break; 8030 case AccessibilityNodeInfo.ACTION_LONG_CLICK: { 8031 if (isLongClickable()) { 8032 performLongClick(); 8033 return true; 8034 } 8035 } break; 8036 case AccessibilityNodeInfo.ACTION_FOCUS: { 8037 if (!hasFocus()) { 8038 // Get out of touch mode since accessibility 8039 // wants to move focus around. 8040 getViewRootImpl().ensureTouchMode(false); 8041 return requestFocus(); 8042 } 8043 } break; 8044 case AccessibilityNodeInfo.ACTION_CLEAR_FOCUS: { 8045 if (hasFocus()) { 8046 clearFocus(); 8047 return !isFocused(); 8048 } 8049 } break; 8050 case AccessibilityNodeInfo.ACTION_SELECT: { 8051 if (!isSelected()) { 8052 setSelected(true); 8053 return isSelected(); 8054 } 8055 } break; 8056 case AccessibilityNodeInfo.ACTION_CLEAR_SELECTION: { 8057 if (isSelected()) { 8058 setSelected(false); 8059 return !isSelected(); 8060 } 8061 } break; 8062 case AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS: { 8063 if (!isAccessibilityFocused()) { 8064 return requestAccessibilityFocus(); 8065 } 8066 } break; 8067 case AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS: { 8068 if (isAccessibilityFocused()) { 8069 clearAccessibilityFocus(); 8070 return true; 8071 } 8072 } break; 8073 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: { 8074 if (arguments != null) { 8075 final int granularity = arguments.getInt( 8076 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8077 final boolean extendSelection = arguments.getBoolean( 8078 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8079 return traverseAtGranularity(granularity, true, extendSelection); 8080 } 8081 } break; 8082 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 8083 if (arguments != null) { 8084 final int granularity = arguments.getInt( 8085 AccessibilityNodeInfo.ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT); 8086 final boolean extendSelection = arguments.getBoolean( 8087 AccessibilityNodeInfo.ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN); 8088 return traverseAtGranularity(granularity, false, extendSelection); 8089 } 8090 } break; 8091 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 8092 CharSequence text = getIterableTextForAccessibility(); 8093 if (text == null) { 8094 return false; 8095 } 8096 final int start = (arguments != null) ? arguments.getInt( 8097 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 8098 final int end = (arguments != null) ? arguments.getInt( 8099 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 8100 // Only cursor position can be specified (selection length == 0) 8101 if ((getAccessibilitySelectionStart() != start 8102 || getAccessibilitySelectionEnd() != end) 8103 && (start == end)) { 8104 setAccessibilitySelection(start, end); 8105 notifyViewAccessibilityStateChangedIfNeeded( 8106 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 8107 return true; 8108 } 8109 } break; 8110 } 8111 return false; 8112 } 8113 8114 private boolean traverseAtGranularity(int granularity, boolean forward, 8115 boolean extendSelection) { 8116 CharSequence text = getIterableTextForAccessibility(); 8117 if (text == null || text.length() == 0) { 8118 return false; 8119 } 8120 TextSegmentIterator iterator = getIteratorForGranularity(granularity); 8121 if (iterator == null) { 8122 return false; 8123 } 8124 int current = getAccessibilitySelectionEnd(); 8125 if (current == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8126 current = forward ? 0 : text.length(); 8127 } 8128 final int[] range = forward ? iterator.following(current) : iterator.preceding(current); 8129 if (range == null) { 8130 return false; 8131 } 8132 final int segmentStart = range[0]; 8133 final int segmentEnd = range[1]; 8134 int selectionStart; 8135 int selectionEnd; 8136 if (extendSelection && isAccessibilitySelectionExtendable()) { 8137 selectionStart = getAccessibilitySelectionStart(); 8138 if (selectionStart == ACCESSIBILITY_CURSOR_POSITION_UNDEFINED) { 8139 selectionStart = forward ? segmentStart : segmentEnd; 8140 } 8141 selectionEnd = forward ? segmentEnd : segmentStart; 8142 } else { 8143 selectionStart = selectionEnd= forward ? segmentEnd : segmentStart; 8144 } 8145 setAccessibilitySelection(selectionStart, selectionEnd); 8146 final int action = forward ? AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY 8147 : AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY; 8148 sendViewTextTraversedAtGranularityEvent(action, granularity, segmentStart, segmentEnd); 8149 return true; 8150 } 8151 8152 /** 8153 * Gets the text reported for accessibility purposes. 8154 * 8155 * @return The accessibility text. 8156 * 8157 * @hide 8158 */ 8159 public CharSequence getIterableTextForAccessibility() { 8160 return getContentDescription(); 8161 } 8162 8163 /** 8164 * Gets whether accessibility selection can be extended. 8165 * 8166 * @return If selection is extensible. 8167 * 8168 * @hide 8169 */ 8170 public boolean isAccessibilitySelectionExtendable() { 8171 return false; 8172 } 8173 8174 /** 8175 * @hide 8176 */ 8177 public int getAccessibilitySelectionStart() { 8178 return mAccessibilityCursorPosition; 8179 } 8180 8181 /** 8182 * @hide 8183 */ 8184 public int getAccessibilitySelectionEnd() { 8185 return getAccessibilitySelectionStart(); 8186 } 8187 8188 /** 8189 * @hide 8190 */ 8191 public void setAccessibilitySelection(int start, int end) { 8192 if (start == end && end == mAccessibilityCursorPosition) { 8193 return; 8194 } 8195 if (start >= 0 && start == end && end <= getIterableTextForAccessibility().length()) { 8196 mAccessibilityCursorPosition = start; 8197 } else { 8198 mAccessibilityCursorPosition = ACCESSIBILITY_CURSOR_POSITION_UNDEFINED; 8199 } 8200 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 8201 } 8202 8203 private void sendViewTextTraversedAtGranularityEvent(int action, int granularity, 8204 int fromIndex, int toIndex) { 8205 if (mParent == null) { 8206 return; 8207 } 8208 AccessibilityEvent event = AccessibilityEvent.obtain( 8209 AccessibilityEvent.TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY); 8210 onInitializeAccessibilityEvent(event); 8211 onPopulateAccessibilityEvent(event); 8212 event.setFromIndex(fromIndex); 8213 event.setToIndex(toIndex); 8214 event.setAction(action); 8215 event.setMovementGranularity(granularity); 8216 mParent.requestSendAccessibilityEvent(this, event); 8217 } 8218 8219 /** 8220 * @hide 8221 */ 8222 public TextSegmentIterator getIteratorForGranularity(int granularity) { 8223 switch (granularity) { 8224 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER: { 8225 CharSequence text = getIterableTextForAccessibility(); 8226 if (text != null && text.length() > 0) { 8227 CharacterTextSegmentIterator iterator = 8228 CharacterTextSegmentIterator.getInstance( 8229 mContext.getResources().getConfiguration().locale); 8230 iterator.initialize(text.toString()); 8231 return iterator; 8232 } 8233 } break; 8234 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD: { 8235 CharSequence text = getIterableTextForAccessibility(); 8236 if (text != null && text.length() > 0) { 8237 WordTextSegmentIterator iterator = 8238 WordTextSegmentIterator.getInstance( 8239 mContext.getResources().getConfiguration().locale); 8240 iterator.initialize(text.toString()); 8241 return iterator; 8242 } 8243 } break; 8244 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH: { 8245 CharSequence text = getIterableTextForAccessibility(); 8246 if (text != null && text.length() > 0) { 8247 ParagraphTextSegmentIterator iterator = 8248 ParagraphTextSegmentIterator.getInstance(); 8249 iterator.initialize(text.toString()); 8250 return iterator; 8251 } 8252 } break; 8253 } 8254 return null; 8255 } 8256 8257 /** 8258 * @hide 8259 */ 8260 public void dispatchStartTemporaryDetach() { 8261 onStartTemporaryDetach(); 8262 } 8263 8264 /** 8265 * This is called when a container is going to temporarily detach a child, with 8266 * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. 8267 * It will either be followed by {@link #onFinishTemporaryDetach()} or 8268 * {@link #onDetachedFromWindow()} when the container is done. 8269 */ 8270 public void onStartTemporaryDetach() { 8271 removeUnsetPressCallback(); 8272 mPrivateFlags |= PFLAG_CANCEL_NEXT_UP_EVENT; 8273 } 8274 8275 /** 8276 * @hide 8277 */ 8278 public void dispatchFinishTemporaryDetach() { 8279 onFinishTemporaryDetach(); 8280 } 8281 8282 /** 8283 * Called after {@link #onStartTemporaryDetach} when the container is done 8284 * changing the view. 8285 */ 8286 public void onFinishTemporaryDetach() { 8287 } 8288 8289 /** 8290 * Return the global {@link KeyEvent.DispatcherState KeyEvent.DispatcherState} 8291 * for this view's window. Returns null if the view is not currently attached 8292 * to the window. Normally you will not need to use this directly, but 8293 * just use the standard high-level event callbacks like 8294 * {@link #onKeyDown(int, KeyEvent)}. 8295 */ 8296 public KeyEvent.DispatcherState getKeyDispatcherState() { 8297 return mAttachInfo != null ? mAttachInfo.mKeyDispatchState : null; 8298 } 8299 8300 /** 8301 * Dispatch a key event before it is processed by any input method 8302 * associated with the view hierarchy. This can be used to intercept 8303 * key events in special situations before the IME consumes them; a 8304 * typical example would be handling the BACK key to update the application's 8305 * UI instead of allowing the IME to see it and close itself. 8306 * 8307 * @param event The key event to be dispatched. 8308 * @return True if the event was handled, false otherwise. 8309 */ 8310 public boolean dispatchKeyEventPreIme(KeyEvent event) { 8311 return onKeyPreIme(event.getKeyCode(), event); 8312 } 8313 8314 /** 8315 * Dispatch a key event to the next view on the focus path. This path runs 8316 * from the top of the view tree down to the currently focused view. If this 8317 * view has focus, it will dispatch to itself. Otherwise it will dispatch 8318 * the next node down the focus path. This method also fires any key 8319 * listeners. 8320 * 8321 * @param event The key event to be dispatched. 8322 * @return True if the event was handled, false otherwise. 8323 */ 8324 public boolean dispatchKeyEvent(KeyEvent event) { 8325 if (mInputEventConsistencyVerifier != null) { 8326 mInputEventConsistencyVerifier.onKeyEvent(event, 0); 8327 } 8328 8329 // Give any attached key listener a first crack at the event. 8330 //noinspection SimplifiableIfStatement 8331 ListenerInfo li = mListenerInfo; 8332 if (li != null && li.mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 8333 && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { 8334 return true; 8335 } 8336 8337 if (event.dispatch(this, mAttachInfo != null 8338 ? mAttachInfo.mKeyDispatchState : null, this)) { 8339 return true; 8340 } 8341 8342 if (mInputEventConsistencyVerifier != null) { 8343 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8344 } 8345 return false; 8346 } 8347 8348 /** 8349 * Dispatches a key shortcut event. 8350 * 8351 * @param event The key event to be dispatched. 8352 * @return True if the event was handled by the view, false otherwise. 8353 */ 8354 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 8355 return onKeyShortcut(event.getKeyCode(), event); 8356 } 8357 8358 /** 8359 * Pass the touch screen motion event down to the target view, or this 8360 * view if it is the target. 8361 * 8362 * @param event The motion event to be dispatched. 8363 * @return True if the event was handled by the view, false otherwise. 8364 */ 8365 public boolean dispatchTouchEvent(MotionEvent event) { 8366 boolean result = false; 8367 8368 if (mInputEventConsistencyVerifier != null) { 8369 mInputEventConsistencyVerifier.onTouchEvent(event, 0); 8370 } 8371 8372 final int actionMasked = event.getActionMasked(); 8373 if (actionMasked == MotionEvent.ACTION_DOWN) { 8374 // Defensive cleanup for new gesture 8375 stopNestedScroll(); 8376 } 8377 8378 if (onFilterTouchEventForSecurity(event)) { 8379 //noinspection SimplifiableIfStatement 8380 ListenerInfo li = mListenerInfo; 8381 if (li != null && li.mOnTouchListener != null 8382 && (mViewFlags & ENABLED_MASK) == ENABLED 8383 && li.mOnTouchListener.onTouch(this, event)) { 8384 result = true; 8385 } 8386 8387 if (!result && onTouchEvent(event)) { 8388 result = true; 8389 } 8390 } 8391 8392 if (!result && mInputEventConsistencyVerifier != null) { 8393 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8394 } 8395 8396 // Clean up after nested scrolls if this is the end of a gesture; 8397 // also cancel it if we tried an ACTION_DOWN but we didn't want the rest 8398 // of the gesture. 8399 if (actionMasked == MotionEvent.ACTION_UP || 8400 actionMasked == MotionEvent.ACTION_CANCEL || 8401 (actionMasked == MotionEvent.ACTION_DOWN && !result)) { 8402 stopNestedScroll(); 8403 } 8404 8405 return result; 8406 } 8407 8408 /** 8409 * Filter the touch event to apply security policies. 8410 * 8411 * @param event The motion event to be filtered. 8412 * @return True if the event should be dispatched, false if the event should be dropped. 8413 * 8414 * @see #getFilterTouchesWhenObscured 8415 */ 8416 public boolean onFilterTouchEventForSecurity(MotionEvent event) { 8417 //noinspection RedundantIfStatement 8418 if ((mViewFlags & FILTER_TOUCHES_WHEN_OBSCURED) != 0 8419 && (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0) { 8420 // Window is obscured, drop this touch. 8421 return false; 8422 } 8423 return true; 8424 } 8425 8426 /** 8427 * Pass a trackball motion event down to the focused view. 8428 * 8429 * @param event The motion event to be dispatched. 8430 * @return True if the event was handled by the view, false otherwise. 8431 */ 8432 public boolean dispatchTrackballEvent(MotionEvent event) { 8433 if (mInputEventConsistencyVerifier != null) { 8434 mInputEventConsistencyVerifier.onTrackballEvent(event, 0); 8435 } 8436 8437 return onTrackballEvent(event); 8438 } 8439 8440 /** 8441 * Dispatch a generic motion event. 8442 * <p> 8443 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 8444 * are delivered to the view under the pointer. All other generic motion events are 8445 * delivered to the focused view. Hover events are handled specially and are delivered 8446 * to {@link #onHoverEvent(MotionEvent)}. 8447 * </p> 8448 * 8449 * @param event The motion event to be dispatched. 8450 * @return True if the event was handled by the view, false otherwise. 8451 */ 8452 public boolean dispatchGenericMotionEvent(MotionEvent event) { 8453 if (mInputEventConsistencyVerifier != null) { 8454 mInputEventConsistencyVerifier.onGenericMotionEvent(event, 0); 8455 } 8456 8457 final int source = event.getSource(); 8458 if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) { 8459 final int action = event.getAction(); 8460 if (action == MotionEvent.ACTION_HOVER_ENTER 8461 || action == MotionEvent.ACTION_HOVER_MOVE 8462 || action == MotionEvent.ACTION_HOVER_EXIT) { 8463 if (dispatchHoverEvent(event)) { 8464 return true; 8465 } 8466 } else if (dispatchGenericPointerEvent(event)) { 8467 return true; 8468 } 8469 } else if (dispatchGenericFocusedEvent(event)) { 8470 return true; 8471 } 8472 8473 if (dispatchGenericMotionEventInternal(event)) { 8474 return true; 8475 } 8476 8477 if (mInputEventConsistencyVerifier != null) { 8478 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8479 } 8480 return false; 8481 } 8482 8483 private boolean dispatchGenericMotionEventInternal(MotionEvent event) { 8484 //noinspection SimplifiableIfStatement 8485 ListenerInfo li = mListenerInfo; 8486 if (li != null && li.mOnGenericMotionListener != null 8487 && (mViewFlags & ENABLED_MASK) == ENABLED 8488 && li.mOnGenericMotionListener.onGenericMotion(this, event)) { 8489 return true; 8490 } 8491 8492 if (onGenericMotionEvent(event)) { 8493 return true; 8494 } 8495 8496 if (mInputEventConsistencyVerifier != null) { 8497 mInputEventConsistencyVerifier.onUnhandledEvent(event, 0); 8498 } 8499 return false; 8500 } 8501 8502 /** 8503 * Dispatch a hover event. 8504 * <p> 8505 * Do not call this method directly. 8506 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8507 * </p> 8508 * 8509 * @param event The motion event to be dispatched. 8510 * @return True if the event was handled by the view, false otherwise. 8511 */ 8512 protected boolean dispatchHoverEvent(MotionEvent event) { 8513 ListenerInfo li = mListenerInfo; 8514 //noinspection SimplifiableIfStatement 8515 if (li != null && li.mOnHoverListener != null 8516 && (mViewFlags & ENABLED_MASK) == ENABLED 8517 && li.mOnHoverListener.onHover(this, event)) { 8518 return true; 8519 } 8520 8521 return onHoverEvent(event); 8522 } 8523 8524 /** 8525 * Returns true if the view has a child to which it has recently sent 8526 * {@link MotionEvent#ACTION_HOVER_ENTER}. If this view is hovered and 8527 * it does not have a hovered child, then it must be the innermost hovered view. 8528 * @hide 8529 */ 8530 protected boolean hasHoveredChild() { 8531 return false; 8532 } 8533 8534 /** 8535 * Dispatch a generic motion event to the view under the first pointer. 8536 * <p> 8537 * Do not call this method directly. 8538 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8539 * </p> 8540 * 8541 * @param event The motion event to be dispatched. 8542 * @return True if the event was handled by the view, false otherwise. 8543 */ 8544 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 8545 return false; 8546 } 8547 8548 /** 8549 * Dispatch a generic motion event to the currently focused view. 8550 * <p> 8551 * Do not call this method directly. 8552 * Call {@link #dispatchGenericMotionEvent(MotionEvent)} instead. 8553 * </p> 8554 * 8555 * @param event The motion event to be dispatched. 8556 * @return True if the event was handled by the view, false otherwise. 8557 */ 8558 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 8559 return false; 8560 } 8561 8562 /** 8563 * Dispatch a pointer event. 8564 * <p> 8565 * Dispatches touch related pointer events to {@link #onTouchEvent(MotionEvent)} and all 8566 * other events to {@link #onGenericMotionEvent(MotionEvent)}. This separation of concerns 8567 * reinforces the invariant that {@link #onTouchEvent(MotionEvent)} is really about touches 8568 * and should not be expected to handle other pointing device features. 8569 * </p> 8570 * 8571 * @param event The motion event to be dispatched. 8572 * @return True if the event was handled by the view, false otherwise. 8573 * @hide 8574 */ 8575 public final boolean dispatchPointerEvent(MotionEvent event) { 8576 if (event.isTouchEvent()) { 8577 return dispatchTouchEvent(event); 8578 } else { 8579 return dispatchGenericMotionEvent(event); 8580 } 8581 } 8582 8583 /** 8584 * Called when the window containing this view gains or loses window focus. 8585 * ViewGroups should override to route to their children. 8586 * 8587 * @param hasFocus True if the window containing this view now has focus, 8588 * false otherwise. 8589 */ 8590 public void dispatchWindowFocusChanged(boolean hasFocus) { 8591 onWindowFocusChanged(hasFocus); 8592 } 8593 8594 /** 8595 * Called when the window containing this view gains or loses focus. Note 8596 * that this is separate from view focus: to receive key events, both 8597 * your view and its window must have focus. If a window is displayed 8598 * on top of yours that takes input focus, then your own window will lose 8599 * focus but the view focus will remain unchanged. 8600 * 8601 * @param hasWindowFocus True if the window containing this view now has 8602 * focus, false otherwise. 8603 */ 8604 public void onWindowFocusChanged(boolean hasWindowFocus) { 8605 InputMethodManager imm = InputMethodManager.peekInstance(); 8606 if (!hasWindowFocus) { 8607 if (isPressed()) { 8608 setPressed(false); 8609 } 8610 if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8611 imm.focusOut(this); 8612 } 8613 removeLongPressCallback(); 8614 removeTapCallback(); 8615 onFocusLost(); 8616 } else if (imm != null && (mPrivateFlags & PFLAG_FOCUSED) != 0) { 8617 imm.focusIn(this); 8618 } 8619 refreshDrawableState(); 8620 } 8621 8622 /** 8623 * Returns true if this view is in a window that currently has window focus. 8624 * Note that this is not the same as the view itself having focus. 8625 * 8626 * @return True if this view is in a window that currently has window focus. 8627 */ 8628 public boolean hasWindowFocus() { 8629 return mAttachInfo != null && mAttachInfo.mHasWindowFocus; 8630 } 8631 8632 /** 8633 * Dispatch a view visibility change down the view hierarchy. 8634 * ViewGroups should override to route to their children. 8635 * @param changedView The view whose visibility changed. Could be 'this' or 8636 * an ancestor view. 8637 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8638 * {@link #INVISIBLE} or {@link #GONE}. 8639 */ 8640 protected void dispatchVisibilityChanged(@NonNull View changedView, 8641 @Visibility int visibility) { 8642 onVisibilityChanged(changedView, visibility); 8643 } 8644 8645 /** 8646 * Called when the visibility of the view or an ancestor of the view is changed. 8647 * @param changedView The view whose visibility changed. Could be 'this' or 8648 * an ancestor view. 8649 * @param visibility The new visibility of changedView: {@link #VISIBLE}, 8650 * {@link #INVISIBLE} or {@link #GONE}. 8651 */ 8652 protected void onVisibilityChanged(@NonNull View changedView, @Visibility int visibility) { 8653 if (visibility == VISIBLE) { 8654 if (mAttachInfo != null) { 8655 initialAwakenScrollBars(); 8656 } else { 8657 mPrivateFlags |= PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 8658 } 8659 } 8660 } 8661 8662 /** 8663 * Dispatch a hint about whether this view is displayed. For instance, when 8664 * a View moves out of the screen, it might receives a display hint indicating 8665 * the view is not displayed. Applications should not <em>rely</em> on this hint 8666 * as there is no guarantee that they will receive one. 8667 * 8668 * @param hint A hint about whether or not this view is displayed: 8669 * {@link #VISIBLE} or {@link #INVISIBLE}. 8670 */ 8671 public void dispatchDisplayHint(@Visibility int hint) { 8672 onDisplayHint(hint); 8673 } 8674 8675 /** 8676 * Gives this view a hint about whether is displayed or not. For instance, when 8677 * a View moves out of the screen, it might receives a display hint indicating 8678 * the view is not displayed. Applications should not <em>rely</em> on this hint 8679 * as there is no guarantee that they will receive one. 8680 * 8681 * @param hint A hint about whether or not this view is displayed: 8682 * {@link #VISIBLE} or {@link #INVISIBLE}. 8683 */ 8684 protected void onDisplayHint(@Visibility int hint) { 8685 } 8686 8687 /** 8688 * Dispatch a window visibility change down the view hierarchy. 8689 * ViewGroups should override to route to their children. 8690 * 8691 * @param visibility The new visibility of the window. 8692 * 8693 * @see #onWindowVisibilityChanged(int) 8694 */ 8695 public void dispatchWindowVisibilityChanged(@Visibility int visibility) { 8696 onWindowVisibilityChanged(visibility); 8697 } 8698 8699 /** 8700 * Called when the window containing has change its visibility 8701 * (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note 8702 * that this tells you whether or not your window is being made visible 8703 * to the window manager; this does <em>not</em> tell you whether or not 8704 * your window is obscured by other windows on the screen, even if it 8705 * is itself visible. 8706 * 8707 * @param visibility The new visibility of the window. 8708 */ 8709 protected void onWindowVisibilityChanged(@Visibility int visibility) { 8710 if (visibility == VISIBLE) { 8711 initialAwakenScrollBars(); 8712 } 8713 } 8714 8715 /** 8716 * Returns the current visibility of the window this view is attached to 8717 * (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}). 8718 * 8719 * @return Returns the current visibility of the view's window. 8720 */ 8721 @Visibility 8722 public int getWindowVisibility() { 8723 return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE; 8724 } 8725 8726 /** 8727 * Retrieve the overall visible display size in which the window this view is 8728 * attached to has been positioned in. This takes into account screen 8729 * decorations above the window, for both cases where the window itself 8730 * is being position inside of them or the window is being placed under 8731 * then and covered insets are used for the window to position its content 8732 * inside. In effect, this tells you the available area where content can 8733 * be placed and remain visible to users. 8734 * 8735 * <p>This function requires an IPC back to the window manager to retrieve 8736 * the requested information, so should not be used in performance critical 8737 * code like drawing. 8738 * 8739 * @param outRect Filled in with the visible display frame. If the view 8740 * is not attached to a window, this is simply the raw display size. 8741 */ 8742 public void getWindowVisibleDisplayFrame(Rect outRect) { 8743 if (mAttachInfo != null) { 8744 try { 8745 mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect); 8746 } catch (RemoteException e) { 8747 return; 8748 } 8749 // XXX This is really broken, and probably all needs to be done 8750 // in the window manager, and we need to know more about whether 8751 // we want the area behind or in front of the IME. 8752 final Rect insets = mAttachInfo.mVisibleInsets; 8753 outRect.left += insets.left; 8754 outRect.top += insets.top; 8755 outRect.right -= insets.right; 8756 outRect.bottom -= insets.bottom; 8757 return; 8758 } 8759 // The view is not attached to a display so we don't have a context. 8760 // Make a best guess about the display size. 8761 Display d = DisplayManagerGlobal.getInstance().getRealDisplay(Display.DEFAULT_DISPLAY); 8762 d.getRectSize(outRect); 8763 } 8764 8765 /** 8766 * Dispatch a notification about a resource configuration change down 8767 * the view hierarchy. 8768 * ViewGroups should override to route to their children. 8769 * 8770 * @param newConfig The new resource configuration. 8771 * 8772 * @see #onConfigurationChanged(android.content.res.Configuration) 8773 */ 8774 public void dispatchConfigurationChanged(Configuration newConfig) { 8775 onConfigurationChanged(newConfig); 8776 } 8777 8778 /** 8779 * Called when the current configuration of the resources being used 8780 * by the application have changed. You can use this to decide when 8781 * to reload resources that can changed based on orientation and other 8782 * configuration characterstics. You only need to use this if you are 8783 * not relying on the normal {@link android.app.Activity} mechanism of 8784 * recreating the activity instance upon a configuration change. 8785 * 8786 * @param newConfig The new resource configuration. 8787 */ 8788 protected void onConfigurationChanged(Configuration newConfig) { 8789 } 8790 8791 /** 8792 * Private function to aggregate all per-view attributes in to the view 8793 * root. 8794 */ 8795 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8796 performCollectViewAttributes(attachInfo, visibility); 8797 } 8798 8799 void performCollectViewAttributes(AttachInfo attachInfo, int visibility) { 8800 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 8801 if ((mViewFlags & KEEP_SCREEN_ON) == KEEP_SCREEN_ON) { 8802 attachInfo.mKeepScreenOn = true; 8803 } 8804 attachInfo.mSystemUiVisibility |= mSystemUiVisibility; 8805 ListenerInfo li = mListenerInfo; 8806 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 8807 attachInfo.mHasSystemUiListeners = true; 8808 } 8809 } 8810 } 8811 8812 void needGlobalAttributesUpdate(boolean force) { 8813 final AttachInfo ai = mAttachInfo; 8814 if (ai != null && !ai.mRecomputeGlobalAttributes) { 8815 if (force || ai.mKeepScreenOn || (ai.mSystemUiVisibility != 0) 8816 || ai.mHasSystemUiListeners) { 8817 ai.mRecomputeGlobalAttributes = true; 8818 } 8819 } 8820 } 8821 8822 /** 8823 * Returns whether the device is currently in touch mode. Touch mode is entered 8824 * once the user begins interacting with the device by touch, and affects various 8825 * things like whether focus is always visible to the user. 8826 * 8827 * @return Whether the device is in touch mode. 8828 */ 8829 @ViewDebug.ExportedProperty 8830 public boolean isInTouchMode() { 8831 if (mAttachInfo != null) { 8832 return mAttachInfo.mInTouchMode; 8833 } else { 8834 return ViewRootImpl.isInTouchMode(); 8835 } 8836 } 8837 8838 /** 8839 * Returns the context the view is running in, through which it can 8840 * access the current theme, resources, etc. 8841 * 8842 * @return The view's Context. 8843 */ 8844 @ViewDebug.CapturedViewProperty 8845 public final Context getContext() { 8846 return mContext; 8847 } 8848 8849 /** 8850 * Handle a key event before it is processed by any input method 8851 * associated with the view hierarchy. This can be used to intercept 8852 * key events in special situations before the IME consumes them; a 8853 * typical example would be handling the BACK key to update the application's 8854 * UI instead of allowing the IME to see it and close itself. 8855 * 8856 * @param keyCode The value in event.getKeyCode(). 8857 * @param event Description of the key event. 8858 * @return If you handled the event, return true. If you want to allow the 8859 * event to be handled by the next receiver, return false. 8860 */ 8861 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 8862 return false; 8863 } 8864 8865 /** 8866 * Default implementation of {@link KeyEvent.Callback#onKeyDown(int, KeyEvent) 8867 * KeyEvent.Callback.onKeyDown()}: perform press of the view 8868 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER} 8869 * is released, if the view is enabled and clickable. 8870 * 8871 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8872 * although some may elect to do so in some situations. Do not rely on this to 8873 * catch software key presses. 8874 * 8875 * @param keyCode A key code that represents the button pressed, from 8876 * {@link android.view.KeyEvent}. 8877 * @param event The KeyEvent object that defines the button action. 8878 */ 8879 public boolean onKeyDown(int keyCode, KeyEvent event) { 8880 boolean result = false; 8881 8882 if (KeyEvent.isConfirmKey(keyCode)) { 8883 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8884 return true; 8885 } 8886 // Long clickable items don't necessarily have to be clickable 8887 if (((mViewFlags & CLICKABLE) == CLICKABLE || 8888 (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) && 8889 (event.getRepeatCount() == 0)) { 8890 setPressed(true); 8891 checkForLongClick(0); 8892 return true; 8893 } 8894 } 8895 return result; 8896 } 8897 8898 /** 8899 * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) 8900 * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle 8901 * the event). 8902 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8903 * although some may elect to do so in some situations. Do not rely on this to 8904 * catch software key presses. 8905 */ 8906 public boolean onKeyLongPress(int keyCode, KeyEvent event) { 8907 return false; 8908 } 8909 8910 /** 8911 * Default implementation of {@link KeyEvent.Callback#onKeyUp(int, KeyEvent) 8912 * KeyEvent.Callback.onKeyUp()}: perform clicking of the view 8913 * when {@link KeyEvent#KEYCODE_DPAD_CENTER} or 8914 * {@link KeyEvent#KEYCODE_ENTER} is released. 8915 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8916 * although some may elect to do so in some situations. Do not rely on this to 8917 * catch software key presses. 8918 * 8919 * @param keyCode A key code that represents the button pressed, from 8920 * {@link android.view.KeyEvent}. 8921 * @param event The KeyEvent object that defines the button action. 8922 */ 8923 public boolean onKeyUp(int keyCode, KeyEvent event) { 8924 if (KeyEvent.isConfirmKey(keyCode)) { 8925 if ((mViewFlags & ENABLED_MASK) == DISABLED) { 8926 return true; 8927 } 8928 if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) { 8929 setPressed(false); 8930 8931 if (!mHasPerformedLongPress) { 8932 // This is a tap, so remove the longpress check 8933 removeLongPressCallback(); 8934 return performClick(); 8935 } 8936 } 8937 } 8938 return false; 8939 } 8940 8941 /** 8942 * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent) 8943 * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle 8944 * the event). 8945 * <p>Key presses in software keyboards will generally NOT trigger this listener, 8946 * although some may elect to do so in some situations. Do not rely on this to 8947 * catch software key presses. 8948 * 8949 * @param keyCode A key code that represents the button pressed, from 8950 * {@link android.view.KeyEvent}. 8951 * @param repeatCount The number of times the action was made. 8952 * @param event The KeyEvent object that defines the button action. 8953 */ 8954 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 8955 return false; 8956 } 8957 8958 /** 8959 * Called on the focused view when a key shortcut event is not handled. 8960 * Override this method to implement local key shortcuts for the View. 8961 * Key shortcuts can also be implemented by setting the 8962 * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items. 8963 * 8964 * @param keyCode The value in event.getKeyCode(). 8965 * @param event Description of the key event. 8966 * @return If you handled the event, return true. If you want to allow the 8967 * event to be handled by the next receiver, return false. 8968 */ 8969 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8970 return false; 8971 } 8972 8973 /** 8974 * Check whether the called view is a text editor, in which case it 8975 * would make sense to automatically display a soft input window for 8976 * it. Subclasses should override this if they implement 8977 * {@link #onCreateInputConnection(EditorInfo)} to return true if 8978 * a call on that method would return a non-null InputConnection, and 8979 * they are really a first-class editor that the user would normally 8980 * start typing on when the go into a window containing your view. 8981 * 8982 * <p>The default implementation always returns false. This does 8983 * <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)} 8984 * will not be called or the user can not otherwise perform edits on your 8985 * view; it is just a hint to the system that this is not the primary 8986 * purpose of this view. 8987 * 8988 * @return Returns true if this view is a text editor, else false. 8989 */ 8990 public boolean onCheckIsTextEditor() { 8991 return false; 8992 } 8993 8994 /** 8995 * Create a new InputConnection for an InputMethod to interact 8996 * with the view. The default implementation returns null, since it doesn't 8997 * support input methods. You can override this to implement such support. 8998 * This is only needed for views that take focus and text input. 8999 * 9000 * <p>When implementing this, you probably also want to implement 9001 * {@link #onCheckIsTextEditor()} to indicate you will return a 9002 * non-null InputConnection.</p> 9003 * 9004 * <p>Also, take good care to fill in the {@link android.view.inputmethod.EditorInfo} 9005 * object correctly and in its entirety, so that the connected IME can rely 9006 * on its values. For example, {@link android.view.inputmethod.EditorInfo#initialSelStart} 9007 * and {@link android.view.inputmethod.EditorInfo#initialSelEnd} members 9008 * must be filled in with the correct cursor position for IMEs to work correctly 9009 * with your application.</p> 9010 * 9011 * @param outAttrs Fill in with attribute information about the connection. 9012 */ 9013 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 9014 return null; 9015 } 9016 9017 /** 9018 * Called by the {@link android.view.inputmethod.InputMethodManager} 9019 * when a view who is not the current 9020 * input connection target is trying to make a call on the manager. The 9021 * default implementation returns false; you can override this to return 9022 * true for certain views if you are performing InputConnection proxying 9023 * to them. 9024 * @param view The View that is making the InputMethodManager call. 9025 * @return Return true to allow the call, false to reject. 9026 */ 9027 public boolean checkInputConnectionProxy(View view) { 9028 return false; 9029 } 9030 9031 /** 9032 * Show the context menu for this view. It is not safe to hold on to the 9033 * menu after returning from this method. 9034 * 9035 * You should normally not overload this method. Overload 9036 * {@link #onCreateContextMenu(ContextMenu)} or define an 9037 * {@link OnCreateContextMenuListener} to add items to the context menu. 9038 * 9039 * @param menu The context menu to populate 9040 */ 9041 public void createContextMenu(ContextMenu menu) { 9042 ContextMenuInfo menuInfo = getContextMenuInfo(); 9043 9044 // Sets the current menu info so all items added to menu will have 9045 // my extra info set. 9046 ((MenuBuilder)menu).setCurrentMenuInfo(menuInfo); 9047 9048 onCreateContextMenu(menu); 9049 ListenerInfo li = mListenerInfo; 9050 if (li != null && li.mOnCreateContextMenuListener != null) { 9051 li.mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo); 9052 } 9053 9054 // Clear the extra information so subsequent items that aren't mine don't 9055 // have my extra info. 9056 ((MenuBuilder)menu).setCurrentMenuInfo(null); 9057 9058 if (mParent != null) { 9059 mParent.createContextMenu(menu); 9060 } 9061 } 9062 9063 /** 9064 * Views should implement this if they have extra information to associate 9065 * with the context menu. The return result is supplied as a parameter to 9066 * the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} 9067 * callback. 9068 * 9069 * @return Extra information about the item for which the context menu 9070 * should be shown. This information will vary across different 9071 * subclasses of View. 9072 */ 9073 protected ContextMenuInfo getContextMenuInfo() { 9074 return null; 9075 } 9076 9077 /** 9078 * Views should implement this if the view itself is going to add items to 9079 * the context menu. 9080 * 9081 * @param menu the context menu to populate 9082 */ 9083 protected void onCreateContextMenu(ContextMenu menu) { 9084 } 9085 9086 /** 9087 * Implement this method to handle trackball motion events. The 9088 * <em>relative</em> movement of the trackball since the last event 9089 * can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and 9090 * {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so 9091 * that a movement of 1 corresponds to the user pressing one DPAD key (so 9092 * they will often be fractional values, representing the more fine-grained 9093 * movement information available from a trackball). 9094 * 9095 * @param event The motion event. 9096 * @return True if the event was handled, false otherwise. 9097 */ 9098 public boolean onTrackballEvent(MotionEvent event) { 9099 return false; 9100 } 9101 9102 /** 9103 * Implement this method to handle generic motion events. 9104 * <p> 9105 * Generic motion events describe joystick movements, mouse hovers, track pad 9106 * touches, scroll wheel movements and other input events. The 9107 * {@link MotionEvent#getSource() source} of the motion event specifies 9108 * the class of input that was received. Implementations of this method 9109 * must examine the bits in the source before processing the event. 9110 * The following code example shows how this is done. 9111 * </p><p> 9112 * Generic motion events with source class {@link InputDevice#SOURCE_CLASS_POINTER} 9113 * are delivered to the view under the pointer. All other generic motion events are 9114 * delivered to the focused view. 9115 * </p> 9116 * <pre> public boolean onGenericMotionEvent(MotionEvent event) { 9117 * if (event.isFromSource(InputDevice.SOURCE_CLASS_JOYSTICK)) { 9118 * if (event.getAction() == MotionEvent.ACTION_MOVE) { 9119 * // process the joystick movement... 9120 * return true; 9121 * } 9122 * } 9123 * if (event.isFromSource(InputDevice.SOURCE_CLASS_POINTER)) { 9124 * switch (event.getAction()) { 9125 * case MotionEvent.ACTION_HOVER_MOVE: 9126 * // process the mouse hover movement... 9127 * return true; 9128 * case MotionEvent.ACTION_SCROLL: 9129 * // process the scroll wheel movement... 9130 * return true; 9131 * } 9132 * } 9133 * return super.onGenericMotionEvent(event); 9134 * }</pre> 9135 * 9136 * @param event The generic motion event being processed. 9137 * @return True if the event was handled, false otherwise. 9138 */ 9139 public boolean onGenericMotionEvent(MotionEvent event) { 9140 return false; 9141 } 9142 9143 /** 9144 * Implement this method to handle hover events. 9145 * <p> 9146 * This method is called whenever a pointer is hovering into, over, or out of the 9147 * bounds of a view and the view is not currently being touched. 9148 * Hover events are represented as pointer events with action 9149 * {@link MotionEvent#ACTION_HOVER_ENTER}, {@link MotionEvent#ACTION_HOVER_MOVE}, 9150 * or {@link MotionEvent#ACTION_HOVER_EXIT}. 9151 * </p> 9152 * <ul> 9153 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_ENTER} 9154 * when the pointer enters the bounds of the view.</li> 9155 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_MOVE} 9156 * when the pointer has already entered the bounds of the view and has moved.</li> 9157 * <li>The view receives a hover event with action {@link MotionEvent#ACTION_HOVER_EXIT} 9158 * when the pointer has exited the bounds of the view or when the pointer is 9159 * about to go down due to a button click, tap, or similar user action that 9160 * causes the view to be touched.</li> 9161 * </ul> 9162 * <p> 9163 * The view should implement this method to return true to indicate that it is 9164 * handling the hover event, such as by changing its drawable state. 9165 * </p><p> 9166 * The default implementation calls {@link #setHovered} to update the hovered state 9167 * of the view when a hover enter or hover exit event is received, if the view 9168 * is enabled and is clickable. The default implementation also sends hover 9169 * accessibility events. 9170 * </p> 9171 * 9172 * @param event The motion event that describes the hover. 9173 * @return True if the view handled the hover event. 9174 * 9175 * @see #isHovered 9176 * @see #setHovered 9177 * @see #onHoverChanged 9178 */ 9179 public boolean onHoverEvent(MotionEvent event) { 9180 // The root view may receive hover (or touch) events that are outside the bounds of 9181 // the window. This code ensures that we only send accessibility events for 9182 // hovers that are actually within the bounds of the root view. 9183 final int action = event.getActionMasked(); 9184 if (!mSendingHoverAccessibilityEvents) { 9185 if ((action == MotionEvent.ACTION_HOVER_ENTER 9186 || action == MotionEvent.ACTION_HOVER_MOVE) 9187 && !hasHoveredChild() 9188 && pointInView(event.getX(), event.getY())) { 9189 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_ENTER); 9190 mSendingHoverAccessibilityEvents = true; 9191 } 9192 } else { 9193 if (action == MotionEvent.ACTION_HOVER_EXIT 9194 || (action == MotionEvent.ACTION_MOVE 9195 && !pointInView(event.getX(), event.getY()))) { 9196 mSendingHoverAccessibilityEvents = false; 9197 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT); 9198 } 9199 } 9200 9201 if (isHoverable()) { 9202 switch (action) { 9203 case MotionEvent.ACTION_HOVER_ENTER: 9204 setHovered(true); 9205 break; 9206 case MotionEvent.ACTION_HOVER_EXIT: 9207 setHovered(false); 9208 break; 9209 } 9210 9211 // Dispatch the event to onGenericMotionEvent before returning true. 9212 // This is to provide compatibility with existing applications that 9213 // handled HOVER_MOVE events in onGenericMotionEvent and that would 9214 // break because of the new default handling for hoverable views 9215 // in onHoverEvent. 9216 // Note that onGenericMotionEvent will be called by default when 9217 // onHoverEvent returns false (refer to dispatchGenericMotionEvent). 9218 dispatchGenericMotionEventInternal(event); 9219 // The event was already handled by calling setHovered(), so always 9220 // return true. 9221 return true; 9222 } 9223 9224 return false; 9225 } 9226 9227 /** 9228 * Returns true if the view should handle {@link #onHoverEvent} 9229 * by calling {@link #setHovered} to change its hovered state. 9230 * 9231 * @return True if the view is hoverable. 9232 */ 9233 private boolean isHoverable() { 9234 final int viewFlags = mViewFlags; 9235 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9236 return false; 9237 } 9238 9239 return (viewFlags & CLICKABLE) == CLICKABLE 9240 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE; 9241 } 9242 9243 /** 9244 * Returns true if the view is currently hovered. 9245 * 9246 * @return True if the view is currently hovered. 9247 * 9248 * @see #setHovered 9249 * @see #onHoverChanged 9250 */ 9251 @ViewDebug.ExportedProperty 9252 public boolean isHovered() { 9253 return (mPrivateFlags & PFLAG_HOVERED) != 0; 9254 } 9255 9256 /** 9257 * Sets whether the view is currently hovered. 9258 * <p> 9259 * Calling this method also changes the drawable state of the view. This 9260 * enables the view to react to hover by using different drawable resources 9261 * to change its appearance. 9262 * </p><p> 9263 * The {@link #onHoverChanged} method is called when the hovered state changes. 9264 * </p> 9265 * 9266 * @param hovered True if the view is hovered. 9267 * 9268 * @see #isHovered 9269 * @see #onHoverChanged 9270 */ 9271 public void setHovered(boolean hovered) { 9272 if (hovered) { 9273 if ((mPrivateFlags & PFLAG_HOVERED) == 0) { 9274 mPrivateFlags |= PFLAG_HOVERED; 9275 refreshDrawableState(); 9276 onHoverChanged(true); 9277 } 9278 } else { 9279 if ((mPrivateFlags & PFLAG_HOVERED) != 0) { 9280 mPrivateFlags &= ~PFLAG_HOVERED; 9281 refreshDrawableState(); 9282 onHoverChanged(false); 9283 } 9284 } 9285 } 9286 9287 /** 9288 * Implement this method to handle hover state changes. 9289 * <p> 9290 * This method is called whenever the hover state changes as a result of a 9291 * call to {@link #setHovered}. 9292 * </p> 9293 * 9294 * @param hovered The current hover state, as returned by {@link #isHovered}. 9295 * 9296 * @see #isHovered 9297 * @see #setHovered 9298 */ 9299 public void onHoverChanged(boolean hovered) { 9300 } 9301 9302 /** 9303 * Implement this method to handle touch screen motion events. 9304 * <p> 9305 * If this method is used to detect click actions, it is recommended that 9306 * the actions be performed by implementing and calling 9307 * {@link #performClick()}. This will ensure consistent system behavior, 9308 * including: 9309 * <ul> 9310 * <li>obeying click sound preferences 9311 * <li>dispatching OnClickListener calls 9312 * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when 9313 * accessibility features are enabled 9314 * </ul> 9315 * 9316 * @param event The motion event. 9317 * @return True if the event was handled, false otherwise. 9318 */ 9319 public boolean onTouchEvent(MotionEvent event) { 9320 final float x = event.getX(); 9321 final float y = event.getY(); 9322 final int viewFlags = mViewFlags; 9323 9324 if ((viewFlags & ENABLED_MASK) == DISABLED) { 9325 if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9326 setPressed(false); 9327 } 9328 // A disabled view that is clickable still consumes the touch 9329 // events, it just doesn't respond to them. 9330 return (((viewFlags & CLICKABLE) == CLICKABLE || 9331 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)); 9332 } 9333 9334 if (mTouchDelegate != null) { 9335 if (mTouchDelegate.onTouchEvent(event)) { 9336 return true; 9337 } 9338 } 9339 9340 if (((viewFlags & CLICKABLE) == CLICKABLE || 9341 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) { 9342 switch (event.getAction()) { 9343 case MotionEvent.ACTION_UP: 9344 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 9345 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 9346 // take focus if we don't have it already and we should in 9347 // touch mode. 9348 boolean focusTaken = false; 9349 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 9350 focusTaken = requestFocus(); 9351 } 9352 9353 if (prepressed) { 9354 // The button is being released before we actually 9355 // showed it as pressed. Make it show the pressed 9356 // state now (before scheduling the click) to ensure 9357 // the user sees it. 9358 setPressed(true, x, y); 9359 } 9360 9361 if (!mHasPerformedLongPress) { 9362 // This is a tap, so remove the longpress check 9363 removeLongPressCallback(); 9364 9365 // Only perform take click actions if we were in the pressed state 9366 if (!focusTaken) { 9367 // Use a Runnable and post this rather than calling 9368 // performClick directly. This lets other visual state 9369 // of the view update before click actions start. 9370 if (mPerformClick == null) { 9371 mPerformClick = new PerformClick(); 9372 } 9373 if (!post(mPerformClick)) { 9374 performClick(); 9375 } 9376 } 9377 } 9378 9379 if (mUnsetPressedState == null) { 9380 mUnsetPressedState = new UnsetPressedState(); 9381 } 9382 9383 if (prepressed) { 9384 postDelayed(mUnsetPressedState, 9385 ViewConfiguration.getPressedStateDuration()); 9386 } else if (!post(mUnsetPressedState)) { 9387 // If the post failed, unpress right now 9388 mUnsetPressedState.run(); 9389 } 9390 9391 removeTapCallback(); 9392 } 9393 break; 9394 9395 case MotionEvent.ACTION_DOWN: 9396 mHasPerformedLongPress = false; 9397 9398 if (performButtonActionOnTouchDown(event)) { 9399 break; 9400 } 9401 9402 // Walk up the hierarchy to determine if we're inside a scrolling container. 9403 boolean isInScrollingContainer = isInScrollingContainer(); 9404 9405 // For views inside a scrolling container, delay the pressed feedback for 9406 // a short period in case this is a scroll. 9407 if (isInScrollingContainer) { 9408 mPrivateFlags |= PFLAG_PREPRESSED; 9409 if (mPendingCheckForTap == null) { 9410 mPendingCheckForTap = new CheckForTap(); 9411 } 9412 mPendingCheckForTap.x = event.getX(); 9413 mPendingCheckForTap.y = event.getY(); 9414 postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout()); 9415 } else { 9416 // Not inside a scrolling container, so show the feedback right away 9417 setPressed(true, x, y); 9418 checkForLongClick(0); 9419 } 9420 break; 9421 9422 case MotionEvent.ACTION_CANCEL: 9423 setPressed(false); 9424 removeTapCallback(); 9425 removeLongPressCallback(); 9426 break; 9427 9428 case MotionEvent.ACTION_MOVE: 9429 drawableHotspotChanged(x, y); 9430 9431 // Be lenient about moving outside of buttons 9432 if (!pointInView(x, y, mTouchSlop)) { 9433 // Outside button 9434 removeTapCallback(); 9435 if ((mPrivateFlags & PFLAG_PRESSED) != 0) { 9436 // Remove any future long press/tap checks 9437 removeLongPressCallback(); 9438 9439 setPressed(false); 9440 } 9441 } 9442 break; 9443 } 9444 9445 return true; 9446 } 9447 9448 return false; 9449 } 9450 9451 /** 9452 * @hide 9453 */ 9454 public boolean isInScrollingContainer() { 9455 ViewParent p = getParent(); 9456 while (p != null && p instanceof ViewGroup) { 9457 if (((ViewGroup) p).shouldDelayChildPressedState()) { 9458 return true; 9459 } 9460 p = p.getParent(); 9461 } 9462 return false; 9463 } 9464 9465 /** 9466 * Remove the longpress detection timer. 9467 */ 9468 private void removeLongPressCallback() { 9469 if (mPendingCheckForLongPress != null) { 9470 removeCallbacks(mPendingCheckForLongPress); 9471 } 9472 } 9473 9474 /** 9475 * Remove the pending click action 9476 */ 9477 private void removePerformClickCallback() { 9478 if (mPerformClick != null) { 9479 removeCallbacks(mPerformClick); 9480 } 9481 } 9482 9483 /** 9484 * Remove the prepress detection timer. 9485 */ 9486 private void removeUnsetPressCallback() { 9487 if ((mPrivateFlags & PFLAG_PRESSED) != 0 && mUnsetPressedState != null) { 9488 setPressed(false); 9489 removeCallbacks(mUnsetPressedState); 9490 } 9491 } 9492 9493 /** 9494 * Remove the tap detection timer. 9495 */ 9496 private void removeTapCallback() { 9497 if (mPendingCheckForTap != null) { 9498 mPrivateFlags &= ~PFLAG_PREPRESSED; 9499 removeCallbacks(mPendingCheckForTap); 9500 } 9501 } 9502 9503 /** 9504 * Cancels a pending long press. Your subclass can use this if you 9505 * want the context menu to come up if the user presses and holds 9506 * at the same place, but you don't want it to come up if they press 9507 * and then move around enough to cause scrolling. 9508 */ 9509 public void cancelLongPress() { 9510 removeLongPressCallback(); 9511 9512 /* 9513 * The prepressed state handled by the tap callback is a display 9514 * construct, but the tap callback will post a long press callback 9515 * less its own timeout. Remove it here. 9516 */ 9517 removeTapCallback(); 9518 } 9519 9520 /** 9521 * Remove the pending callback for sending a 9522 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 9523 */ 9524 private void removeSendViewScrolledAccessibilityEventCallback() { 9525 if (mSendViewScrolledAccessibilityEvent != null) { 9526 removeCallbacks(mSendViewScrolledAccessibilityEvent); 9527 mSendViewScrolledAccessibilityEvent.mIsPending = false; 9528 } 9529 } 9530 9531 /** 9532 * Sets the TouchDelegate for this View. 9533 */ 9534 public void setTouchDelegate(TouchDelegate delegate) { 9535 mTouchDelegate = delegate; 9536 } 9537 9538 /** 9539 * Gets the TouchDelegate for this View. 9540 */ 9541 public TouchDelegate getTouchDelegate() { 9542 return mTouchDelegate; 9543 } 9544 9545 /** 9546 * Request unbuffered dispatch of the given stream of MotionEvents to this View. 9547 * 9548 * Until this View receives a corresponding {@link MotionEvent#ACTION_UP}, ask that the input 9549 * system not batch {@link MotionEvent}s but instead deliver them as soon as they're 9550 * available. This method should only be called for touch events. 9551 * 9552 * <p class="note">This api is not intended for most applications. Buffered dispatch 9553 * provides many of benefits, and just requesting unbuffered dispatch on most MotionEvent 9554 * streams will not improve your input latency. Side effects include: increased latency, 9555 * jittery scrolls and inability to take advantage of system resampling. Talk to your input 9556 * professional to see if {@link #requestUnbufferedDispatch(MotionEvent)} is right for 9557 * you.</p> 9558 */ 9559 public final void requestUnbufferedDispatch(MotionEvent event) { 9560 final int action = event.getAction(); 9561 if (mAttachInfo == null 9562 || action != MotionEvent.ACTION_DOWN && action != MotionEvent.ACTION_MOVE 9563 || !event.isTouchEvent()) { 9564 return; 9565 } 9566 mAttachInfo.mUnbufferedDispatchRequested = true; 9567 } 9568 9569 /** 9570 * Set flags controlling behavior of this view. 9571 * 9572 * @param flags Constant indicating the value which should be set 9573 * @param mask Constant indicating the bit range that should be changed 9574 */ 9575 void setFlags(int flags, int mask) { 9576 final boolean accessibilityEnabled = 9577 AccessibilityManager.getInstance(mContext).isEnabled(); 9578 final boolean oldIncludeForAccessibility = accessibilityEnabled && includeForAccessibility(); 9579 9580 int old = mViewFlags; 9581 mViewFlags = (mViewFlags & ~mask) | (flags & mask); 9582 9583 int changed = mViewFlags ^ old; 9584 if (changed == 0) { 9585 return; 9586 } 9587 int privateFlags = mPrivateFlags; 9588 9589 /* Check if the FOCUSABLE bit has changed */ 9590 if (((changed & FOCUSABLE_MASK) != 0) && 9591 ((privateFlags & PFLAG_HAS_BOUNDS) !=0)) { 9592 if (((old & FOCUSABLE_MASK) == FOCUSABLE) 9593 && ((privateFlags & PFLAG_FOCUSED) != 0)) { 9594 /* Give up focus if we are no longer focusable */ 9595 clearFocus(); 9596 } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE) 9597 && ((privateFlags & PFLAG_FOCUSED) == 0)) { 9598 /* 9599 * Tell the view system that we are now available to take focus 9600 * if no one else already has it. 9601 */ 9602 if (mParent != null) mParent.focusableViewAvailable(this); 9603 } 9604 } 9605 9606 final int newVisibility = flags & VISIBILITY_MASK; 9607 if (newVisibility == VISIBLE) { 9608 if ((changed & VISIBILITY_MASK) != 0) { 9609 /* 9610 * If this view is becoming visible, invalidate it in case it changed while 9611 * it was not visible. Marking it drawn ensures that the invalidation will 9612 * go through. 9613 */ 9614 mPrivateFlags |= PFLAG_DRAWN; 9615 invalidate(true); 9616 9617 needGlobalAttributesUpdate(true); 9618 9619 // a view becoming visible is worth notifying the parent 9620 // about in case nothing has focus. even if this specific view 9621 // isn't focusable, it may contain something that is, so let 9622 // the root view try to give this focus if nothing else does. 9623 if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) { 9624 mParent.focusableViewAvailable(this); 9625 } 9626 } 9627 } 9628 9629 /* Check if the GONE bit has changed */ 9630 if ((changed & GONE) != 0) { 9631 needGlobalAttributesUpdate(false); 9632 requestLayout(); 9633 9634 if (((mViewFlags & VISIBILITY_MASK) == GONE)) { 9635 if (hasFocus()) clearFocus(); 9636 clearAccessibilityFocus(); 9637 destroyDrawingCache(); 9638 if (mParent instanceof View) { 9639 // GONE views noop invalidation, so invalidate the parent 9640 ((View) mParent).invalidate(true); 9641 } 9642 // Mark the view drawn to ensure that it gets invalidated properly the next 9643 // time it is visible and gets invalidated 9644 mPrivateFlags |= PFLAG_DRAWN; 9645 } 9646 if (mAttachInfo != null) { 9647 mAttachInfo.mViewVisibilityChanged = true; 9648 } 9649 } 9650 9651 /* Check if the VISIBLE bit has changed */ 9652 if ((changed & INVISIBLE) != 0) { 9653 needGlobalAttributesUpdate(false); 9654 /* 9655 * If this view is becoming invisible, set the DRAWN flag so that 9656 * the next invalidate() will not be skipped. 9657 */ 9658 mPrivateFlags |= PFLAG_DRAWN; 9659 9660 if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { 9661 // root view becoming invisible shouldn't clear focus and accessibility focus 9662 if (getRootView() != this) { 9663 if (hasFocus()) clearFocus(); 9664 clearAccessibilityFocus(); 9665 } 9666 } 9667 if (mAttachInfo != null) { 9668 mAttachInfo.mViewVisibilityChanged = true; 9669 } 9670 } 9671 9672 if ((changed & VISIBILITY_MASK) != 0) { 9673 // If the view is invisible, cleanup its display list to free up resources 9674 if (newVisibility != VISIBLE && mAttachInfo != null) { 9675 cleanupDraw(); 9676 } 9677 9678 if (mParent instanceof ViewGroup) { 9679 ((ViewGroup) mParent).onChildVisibilityChanged(this, 9680 (changed & VISIBILITY_MASK), newVisibility); 9681 ((View) mParent).invalidate(true); 9682 } else if (mParent != null) { 9683 mParent.invalidateChild(this, null); 9684 } 9685 dispatchVisibilityChanged(this, newVisibility); 9686 9687 notifySubtreeAccessibilityStateChangedIfNeeded(); 9688 } 9689 9690 if ((changed & WILL_NOT_CACHE_DRAWING) != 0) { 9691 destroyDrawingCache(); 9692 } 9693 9694 if ((changed & DRAWING_CACHE_ENABLED) != 0) { 9695 destroyDrawingCache(); 9696 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9697 invalidateParentCaches(); 9698 } 9699 9700 if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { 9701 destroyDrawingCache(); 9702 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 9703 } 9704 9705 if ((changed & DRAW_MASK) != 0) { 9706 if ((mViewFlags & WILL_NOT_DRAW) != 0) { 9707 if (mBackground != null) { 9708 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9709 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 9710 } else { 9711 mPrivateFlags |= PFLAG_SKIP_DRAW; 9712 } 9713 } else { 9714 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 9715 } 9716 requestLayout(); 9717 invalidate(true); 9718 } 9719 9720 if ((changed & KEEP_SCREEN_ON) != 0) { 9721 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 9722 mParent.recomputeViewAttributes(this); 9723 } 9724 } 9725 9726 if (accessibilityEnabled) { 9727 if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0 9728 || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) { 9729 if (oldIncludeForAccessibility != includeForAccessibility()) { 9730 notifySubtreeAccessibilityStateChangedIfNeeded(); 9731 } else { 9732 notifyViewAccessibilityStateChangedIfNeeded( 9733 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9734 } 9735 } else if ((changed & ENABLED_MASK) != 0) { 9736 notifyViewAccessibilityStateChangedIfNeeded( 9737 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 9738 } 9739 } 9740 } 9741 9742 /** 9743 * Change the view's z order in the tree, so it's on top of other sibling 9744 * views. This ordering change may affect layout, if the parent container 9745 * uses an order-dependent layout scheme (e.g., LinearLayout). Prior 9746 * to {@link android.os.Build.VERSION_CODES#KITKAT} this 9747 * method should be followed by calls to {@link #requestLayout()} and 9748 * {@link View#invalidate()} on the view's parent to force the parent to redraw 9749 * with the new child ordering. 9750 * 9751 * @see ViewGroup#bringChildToFront(View) 9752 */ 9753 public void bringToFront() { 9754 if (mParent != null) { 9755 mParent.bringChildToFront(this); 9756 } 9757 } 9758 9759 /** 9760 * This is called in response to an internal scroll in this view (i.e., the 9761 * view scrolled its own contents). This is typically as a result of 9762 * {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been 9763 * called. 9764 * 9765 * @param l Current horizontal scroll origin. 9766 * @param t Current vertical scroll origin. 9767 * @param oldl Previous horizontal scroll origin. 9768 * @param oldt Previous vertical scroll origin. 9769 */ 9770 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 9771 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 9772 postSendViewScrolledAccessibilityEventCallback(); 9773 } 9774 9775 mBackgroundSizeChanged = true; 9776 9777 final AttachInfo ai = mAttachInfo; 9778 if (ai != null) { 9779 ai.mViewScrollChanged = true; 9780 } 9781 } 9782 9783 /** 9784 * Interface definition for a callback to be invoked when the layout bounds of a view 9785 * changes due to layout processing. 9786 */ 9787 public interface OnLayoutChangeListener { 9788 /** 9789 * Called when the layout bounds of a view changes due to layout processing. 9790 * 9791 * @param v The view whose bounds have changed. 9792 * @param left The new value of the view's left property. 9793 * @param top The new value of the view's top property. 9794 * @param right The new value of the view's right property. 9795 * @param bottom The new value of the view's bottom property. 9796 * @param oldLeft The previous value of the view's left property. 9797 * @param oldTop The previous value of the view's top property. 9798 * @param oldRight The previous value of the view's right property. 9799 * @param oldBottom The previous value of the view's bottom property. 9800 */ 9801 void onLayoutChange(View v, int left, int top, int right, int bottom, 9802 int oldLeft, int oldTop, int oldRight, int oldBottom); 9803 } 9804 9805 /** 9806 * This is called during layout when the size of this view has changed. If 9807 * you were just added to the view hierarchy, you're called with the old 9808 * values of 0. 9809 * 9810 * @param w Current width of this view. 9811 * @param h Current height of this view. 9812 * @param oldw Old width of this view. 9813 * @param oldh Old height of this view. 9814 */ 9815 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 9816 } 9817 9818 /** 9819 * Called by draw to draw the child views. This may be overridden 9820 * by derived classes to gain control just before its children are drawn 9821 * (but after its own view has been drawn). 9822 * @param canvas the canvas on which to draw the view 9823 */ 9824 protected void dispatchDraw(Canvas canvas) { 9825 9826 } 9827 9828 /** 9829 * Gets the parent of this view. Note that the parent is a 9830 * ViewParent and not necessarily a View. 9831 * 9832 * @return Parent of this view. 9833 */ 9834 public final ViewParent getParent() { 9835 return mParent; 9836 } 9837 9838 /** 9839 * Set the horizontal scrolled position of your view. This will cause a call to 9840 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9841 * invalidated. 9842 * @param value the x position to scroll to 9843 */ 9844 public void setScrollX(int value) { 9845 scrollTo(value, mScrollY); 9846 } 9847 9848 /** 9849 * Set the vertical scrolled position of your view. This will cause a call to 9850 * {@link #onScrollChanged(int, int, int, int)} and the view will be 9851 * invalidated. 9852 * @param value the y position to scroll to 9853 */ 9854 public void setScrollY(int value) { 9855 scrollTo(mScrollX, value); 9856 } 9857 9858 /** 9859 * Return the scrolled left position of this view. This is the left edge of 9860 * the displayed part of your view. You do not need to draw any pixels 9861 * farther left, since those are outside of the frame of your view on 9862 * screen. 9863 * 9864 * @return The left edge of the displayed part of your view, in pixels. 9865 */ 9866 public final int getScrollX() { 9867 return mScrollX; 9868 } 9869 9870 /** 9871 * Return the scrolled top position of this view. This is the top edge of 9872 * the displayed part of your view. You do not need to draw any pixels above 9873 * it, since those are outside of the frame of your view on screen. 9874 * 9875 * @return The top edge of the displayed part of your view, in pixels. 9876 */ 9877 public final int getScrollY() { 9878 return mScrollY; 9879 } 9880 9881 /** 9882 * Return the width of the your view. 9883 * 9884 * @return The width of your view, in pixels. 9885 */ 9886 @ViewDebug.ExportedProperty(category = "layout") 9887 public final int getWidth() { 9888 return mRight - mLeft; 9889 } 9890 9891 /** 9892 * Return the height of your view. 9893 * 9894 * @return The height of your view, in pixels. 9895 */ 9896 @ViewDebug.ExportedProperty(category = "layout") 9897 public final int getHeight() { 9898 return mBottom - mTop; 9899 } 9900 9901 /** 9902 * Return the visible drawing bounds of your view. Fills in the output 9903 * rectangle with the values from getScrollX(), getScrollY(), 9904 * getWidth(), and getHeight(). These bounds do not account for any 9905 * transformation properties currently set on the view, such as 9906 * {@link #setScaleX(float)} or {@link #setRotation(float)}. 9907 * 9908 * @param outRect The (scrolled) drawing bounds of the view. 9909 */ 9910 public void getDrawingRect(Rect outRect) { 9911 outRect.left = mScrollX; 9912 outRect.top = mScrollY; 9913 outRect.right = mScrollX + (mRight - mLeft); 9914 outRect.bottom = mScrollY + (mBottom - mTop); 9915 } 9916 9917 /** 9918 * Like {@link #getMeasuredWidthAndState()}, but only returns the 9919 * raw width component (that is the result is masked by 9920 * {@link #MEASURED_SIZE_MASK}). 9921 * 9922 * @return The raw measured width of this view. 9923 */ 9924 public final int getMeasuredWidth() { 9925 return mMeasuredWidth & MEASURED_SIZE_MASK; 9926 } 9927 9928 /** 9929 * Return the full width measurement information for this view as computed 9930 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9931 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9932 * This should be used during measurement and layout calculations only. Use 9933 * {@link #getWidth()} to see how wide a view is after layout. 9934 * 9935 * @return The measured width of this view as a bit mask. 9936 */ 9937 public final int getMeasuredWidthAndState() { 9938 return mMeasuredWidth; 9939 } 9940 9941 /** 9942 * Like {@link #getMeasuredHeightAndState()}, but only returns the 9943 * raw width component (that is the result is masked by 9944 * {@link #MEASURED_SIZE_MASK}). 9945 * 9946 * @return The raw measured height of this view. 9947 */ 9948 public final int getMeasuredHeight() { 9949 return mMeasuredHeight & MEASURED_SIZE_MASK; 9950 } 9951 9952 /** 9953 * Return the full height measurement information for this view as computed 9954 * by the most recent call to {@link #measure(int, int)}. This result is a bit mask 9955 * as defined by {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 9956 * This should be used during measurement and layout calculations only. Use 9957 * {@link #getHeight()} to see how wide a view is after layout. 9958 * 9959 * @return The measured width of this view as a bit mask. 9960 */ 9961 public final int getMeasuredHeightAndState() { 9962 return mMeasuredHeight; 9963 } 9964 9965 /** 9966 * Return only the state bits of {@link #getMeasuredWidthAndState()} 9967 * and {@link #getMeasuredHeightAndState()}, combined into one integer. 9968 * The width component is in the regular bits {@link #MEASURED_STATE_MASK} 9969 * and the height component is at the shifted bits 9970 * {@link #MEASURED_HEIGHT_STATE_SHIFT}>>{@link #MEASURED_STATE_MASK}. 9971 */ 9972 public final int getMeasuredState() { 9973 return (mMeasuredWidth&MEASURED_STATE_MASK) 9974 | ((mMeasuredHeight>>MEASURED_HEIGHT_STATE_SHIFT) 9975 & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT)); 9976 } 9977 9978 /** 9979 * The transform matrix of this view, which is calculated based on the current 9980 * rotation, scale, and pivot properties. 9981 * 9982 * @see #getRotation() 9983 * @see #getScaleX() 9984 * @see #getScaleY() 9985 * @see #getPivotX() 9986 * @see #getPivotY() 9987 * @return The current transform matrix for the view 9988 */ 9989 public Matrix getMatrix() { 9990 ensureTransformationInfo(); 9991 final Matrix matrix = mTransformationInfo.mMatrix; 9992 mRenderNode.getMatrix(matrix); 9993 return matrix; 9994 } 9995 9996 /** 9997 * Returns true if the transform matrix is the identity matrix. 9998 * Recomputes the matrix if necessary. 9999 * 10000 * @return True if the transform matrix is the identity matrix, false otherwise. 10001 */ 10002 final boolean hasIdentityMatrix() { 10003 return mRenderNode.hasIdentityMatrix(); 10004 } 10005 10006 void ensureTransformationInfo() { 10007 if (mTransformationInfo == null) { 10008 mTransformationInfo = new TransformationInfo(); 10009 } 10010 } 10011 10012 /** 10013 * Utility method to retrieve the inverse of the current mMatrix property. 10014 * We cache the matrix to avoid recalculating it when transform properties 10015 * have not changed. 10016 * 10017 * @return The inverse of the current matrix of this view. 10018 * @hide 10019 */ 10020 public final Matrix getInverseMatrix() { 10021 ensureTransformationInfo(); 10022 if (mTransformationInfo.mInverseMatrix == null) { 10023 mTransformationInfo.mInverseMatrix = new Matrix(); 10024 } 10025 final Matrix matrix = mTransformationInfo.mInverseMatrix; 10026 mRenderNode.getInverseMatrix(matrix); 10027 return matrix; 10028 } 10029 10030 /** 10031 * Gets the distance along the Z axis from the camera to this view. 10032 * 10033 * @see #setCameraDistance(float) 10034 * 10035 * @return The distance along the Z axis. 10036 */ 10037 public float getCameraDistance() { 10038 final float dpi = mResources.getDisplayMetrics().densityDpi; 10039 return -(mRenderNode.getCameraDistance() * dpi); 10040 } 10041 10042 /** 10043 * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which 10044 * views are drawn) from the camera to this view. The camera's distance 10045 * affects 3D transformations, for instance rotations around the X and Y 10046 * axis. If the rotationX or rotationY properties are changed and this view is 10047 * large (more than half the size of the screen), it is recommended to always 10048 * use a camera distance that's greater than the height (X axis rotation) or 10049 * the width (Y axis rotation) of this view.</p> 10050 * 10051 * <p>The distance of the camera from the view plane can have an affect on the 10052 * perspective distortion of the view when it is rotated around the x or y axis. 10053 * For example, a large distance will result in a large viewing angle, and there 10054 * will not be much perspective distortion of the view as it rotates. A short 10055 * distance may cause much more perspective distortion upon rotation, and can 10056 * also result in some drawing artifacts if the rotated view ends up partially 10057 * behind the camera (which is why the recommendation is to use a distance at 10058 * least as far as the size of the view, if the view is to be rotated.)</p> 10059 * 10060 * <p>The distance is expressed in "depth pixels." The default distance depends 10061 * on the screen density. For instance, on a medium density display, the 10062 * default distance is 1280. On a high density display, the default distance 10063 * is 1920.</p> 10064 * 10065 * <p>If you want to specify a distance that leads to visually consistent 10066 * results across various densities, use the following formula:</p> 10067 * <pre> 10068 * float scale = context.getResources().getDisplayMetrics().density; 10069 * view.setCameraDistance(distance * scale); 10070 * </pre> 10071 * 10072 * <p>The density scale factor of a high density display is 1.5, 10073 * and 1920 = 1280 * 1.5.</p> 10074 * 10075 * @param distance The distance in "depth pixels", if negative the opposite 10076 * value is used 10077 * 10078 * @see #setRotationX(float) 10079 * @see #setRotationY(float) 10080 */ 10081 public void setCameraDistance(float distance) { 10082 final float dpi = mResources.getDisplayMetrics().densityDpi; 10083 10084 invalidateViewProperty(true, false); 10085 mRenderNode.setCameraDistance(-Math.abs(distance) / dpi); 10086 invalidateViewProperty(false, false); 10087 10088 invalidateParentIfNeededAndWasQuickRejected(); 10089 } 10090 10091 /** 10092 * The degrees that the view is rotated around the pivot point. 10093 * 10094 * @see #setRotation(float) 10095 * @see #getPivotX() 10096 * @see #getPivotY() 10097 * 10098 * @return The degrees of rotation. 10099 */ 10100 @ViewDebug.ExportedProperty(category = "drawing") 10101 public float getRotation() { 10102 return mRenderNode.getRotation(); 10103 } 10104 10105 /** 10106 * Sets the degrees that the view is rotated around the pivot point. Increasing values 10107 * result in clockwise rotation. 10108 * 10109 * @param rotation The degrees of rotation. 10110 * 10111 * @see #getRotation() 10112 * @see #getPivotX() 10113 * @see #getPivotY() 10114 * @see #setRotationX(float) 10115 * @see #setRotationY(float) 10116 * 10117 * @attr ref android.R.styleable#View_rotation 10118 */ 10119 public void setRotation(float rotation) { 10120 if (rotation != getRotation()) { 10121 // Double-invalidation is necessary to capture view's old and new areas 10122 invalidateViewProperty(true, false); 10123 mRenderNode.setRotation(rotation); 10124 invalidateViewProperty(false, true); 10125 10126 invalidateParentIfNeededAndWasQuickRejected(); 10127 notifySubtreeAccessibilityStateChangedIfNeeded(); 10128 } 10129 } 10130 10131 /** 10132 * The degrees that the view is rotated around the vertical axis through the pivot point. 10133 * 10134 * @see #getPivotX() 10135 * @see #getPivotY() 10136 * @see #setRotationY(float) 10137 * 10138 * @return The degrees of Y rotation. 10139 */ 10140 @ViewDebug.ExportedProperty(category = "drawing") 10141 public float getRotationY() { 10142 return mRenderNode.getRotationY(); 10143 } 10144 10145 /** 10146 * Sets the degrees that the view is rotated around the vertical axis through the pivot point. 10147 * Increasing values result in counter-clockwise rotation from the viewpoint of looking 10148 * down the y axis. 10149 * 10150 * When rotating large views, it is recommended to adjust the camera distance 10151 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10152 * 10153 * @param rotationY The degrees of Y rotation. 10154 * 10155 * @see #getRotationY() 10156 * @see #getPivotX() 10157 * @see #getPivotY() 10158 * @see #setRotation(float) 10159 * @see #setRotationX(float) 10160 * @see #setCameraDistance(float) 10161 * 10162 * @attr ref android.R.styleable#View_rotationY 10163 */ 10164 public void setRotationY(float rotationY) { 10165 if (rotationY != getRotationY()) { 10166 invalidateViewProperty(true, false); 10167 mRenderNode.setRotationY(rotationY); 10168 invalidateViewProperty(false, true); 10169 10170 invalidateParentIfNeededAndWasQuickRejected(); 10171 notifySubtreeAccessibilityStateChangedIfNeeded(); 10172 } 10173 } 10174 10175 /** 10176 * The degrees that the view is rotated around the horizontal axis through the pivot point. 10177 * 10178 * @see #getPivotX() 10179 * @see #getPivotY() 10180 * @see #setRotationX(float) 10181 * 10182 * @return The degrees of X rotation. 10183 */ 10184 @ViewDebug.ExportedProperty(category = "drawing") 10185 public float getRotationX() { 10186 return mRenderNode.getRotationX(); 10187 } 10188 10189 /** 10190 * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. 10191 * Increasing values result in clockwise rotation from the viewpoint of looking down the 10192 * x axis. 10193 * 10194 * When rotating large views, it is recommended to adjust the camera distance 10195 * accordingly. Refer to {@link #setCameraDistance(float)} for more information. 10196 * 10197 * @param rotationX The degrees of X rotation. 10198 * 10199 * @see #getRotationX() 10200 * @see #getPivotX() 10201 * @see #getPivotY() 10202 * @see #setRotation(float) 10203 * @see #setRotationY(float) 10204 * @see #setCameraDistance(float) 10205 * 10206 * @attr ref android.R.styleable#View_rotationX 10207 */ 10208 public void setRotationX(float rotationX) { 10209 if (rotationX != getRotationX()) { 10210 invalidateViewProperty(true, false); 10211 mRenderNode.setRotationX(rotationX); 10212 invalidateViewProperty(false, true); 10213 10214 invalidateParentIfNeededAndWasQuickRejected(); 10215 notifySubtreeAccessibilityStateChangedIfNeeded(); 10216 } 10217 } 10218 10219 /** 10220 * The amount that the view is scaled in x around the pivot point, as a proportion of 10221 * the view's unscaled width. A value of 1, the default, means that no scaling is applied. 10222 * 10223 * <p>By default, this is 1.0f. 10224 * 10225 * @see #getPivotX() 10226 * @see #getPivotY() 10227 * @return The scaling factor. 10228 */ 10229 @ViewDebug.ExportedProperty(category = "drawing") 10230 public float getScaleX() { 10231 return mRenderNode.getScaleX(); 10232 } 10233 10234 /** 10235 * Sets the amount that the view is scaled in x around the pivot point, as a proportion of 10236 * the view's unscaled width. A value of 1 means that no scaling is applied. 10237 * 10238 * @param scaleX The scaling factor. 10239 * @see #getPivotX() 10240 * @see #getPivotY() 10241 * 10242 * @attr ref android.R.styleable#View_scaleX 10243 */ 10244 public void setScaleX(float scaleX) { 10245 if (scaleX != getScaleX()) { 10246 invalidateViewProperty(true, false); 10247 mRenderNode.setScaleX(scaleX); 10248 invalidateViewProperty(false, true); 10249 10250 invalidateParentIfNeededAndWasQuickRejected(); 10251 notifySubtreeAccessibilityStateChangedIfNeeded(); 10252 } 10253 } 10254 10255 /** 10256 * The amount that the view is scaled in y around the pivot point, as a proportion of 10257 * the view's unscaled height. A value of 1, the default, means that no scaling is applied. 10258 * 10259 * <p>By default, this is 1.0f. 10260 * 10261 * @see #getPivotX() 10262 * @see #getPivotY() 10263 * @return The scaling factor. 10264 */ 10265 @ViewDebug.ExportedProperty(category = "drawing") 10266 public float getScaleY() { 10267 return mRenderNode.getScaleY(); 10268 } 10269 10270 /** 10271 * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of 10272 * the view's unscaled width. A value of 1 means that no scaling is applied. 10273 * 10274 * @param scaleY The scaling factor. 10275 * @see #getPivotX() 10276 * @see #getPivotY() 10277 * 10278 * @attr ref android.R.styleable#View_scaleY 10279 */ 10280 public void setScaleY(float scaleY) { 10281 if (scaleY != getScaleY()) { 10282 invalidateViewProperty(true, false); 10283 mRenderNode.setScaleY(scaleY); 10284 invalidateViewProperty(false, true); 10285 10286 invalidateParentIfNeededAndWasQuickRejected(); 10287 notifySubtreeAccessibilityStateChangedIfNeeded(); 10288 } 10289 } 10290 10291 /** 10292 * The x location of the point around which the view is {@link #setRotation(float) rotated} 10293 * and {@link #setScaleX(float) scaled}. 10294 * 10295 * @see #getRotation() 10296 * @see #getScaleX() 10297 * @see #getScaleY() 10298 * @see #getPivotY() 10299 * @return The x location of the pivot point. 10300 * 10301 * @attr ref android.R.styleable#View_transformPivotX 10302 */ 10303 @ViewDebug.ExportedProperty(category = "drawing") 10304 public float getPivotX() { 10305 return mRenderNode.getPivotX(); 10306 } 10307 10308 /** 10309 * Sets the x location of the point around which the view is 10310 * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. 10311 * By default, the pivot point is centered on the object. 10312 * Setting this property disables this behavior and causes the view to use only the 10313 * explicitly set pivotX and pivotY values. 10314 * 10315 * @param pivotX The x location of the pivot point. 10316 * @see #getRotation() 10317 * @see #getScaleX() 10318 * @see #getScaleY() 10319 * @see #getPivotY() 10320 * 10321 * @attr ref android.R.styleable#View_transformPivotX 10322 */ 10323 public void setPivotX(float pivotX) { 10324 if (!mRenderNode.isPivotExplicitlySet() || pivotX != getPivotX()) { 10325 invalidateViewProperty(true, false); 10326 mRenderNode.setPivotX(pivotX); 10327 invalidateViewProperty(false, true); 10328 10329 invalidateParentIfNeededAndWasQuickRejected(); 10330 } 10331 } 10332 10333 /** 10334 * The y location of the point around which the view is {@link #setRotation(float) rotated} 10335 * and {@link #setScaleY(float) scaled}. 10336 * 10337 * @see #getRotation() 10338 * @see #getScaleX() 10339 * @see #getScaleY() 10340 * @see #getPivotY() 10341 * @return The y location of the pivot point. 10342 * 10343 * @attr ref android.R.styleable#View_transformPivotY 10344 */ 10345 @ViewDebug.ExportedProperty(category = "drawing") 10346 public float getPivotY() { 10347 return mRenderNode.getPivotY(); 10348 } 10349 10350 /** 10351 * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} 10352 * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. 10353 * Setting this property disables this behavior and causes the view to use only the 10354 * explicitly set pivotX and pivotY values. 10355 * 10356 * @param pivotY The y location of the pivot point. 10357 * @see #getRotation() 10358 * @see #getScaleX() 10359 * @see #getScaleY() 10360 * @see #getPivotY() 10361 * 10362 * @attr ref android.R.styleable#View_transformPivotY 10363 */ 10364 public void setPivotY(float pivotY) { 10365 if (!mRenderNode.isPivotExplicitlySet() || pivotY != getPivotY()) { 10366 invalidateViewProperty(true, false); 10367 mRenderNode.setPivotY(pivotY); 10368 invalidateViewProperty(false, true); 10369 10370 invalidateParentIfNeededAndWasQuickRejected(); 10371 } 10372 } 10373 10374 /** 10375 * The opacity of the view. This is a value from 0 to 1, where 0 means the view is 10376 * completely transparent and 1 means the view is completely opaque. 10377 * 10378 * <p>By default this is 1.0f. 10379 * @return The opacity of the view. 10380 */ 10381 @ViewDebug.ExportedProperty(category = "drawing") 10382 public float getAlpha() { 10383 return mTransformationInfo != null ? mTransformationInfo.mAlpha : 1; 10384 } 10385 10386 /** 10387 * Returns whether this View has content which overlaps. 10388 * 10389 * <p>This function, intended to be overridden by specific View types, is an optimization when 10390 * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to 10391 * an offscreen buffer and then composited into place, which can be expensive. If the view has 10392 * no overlapping rendering, the view can draw each primitive with the appropriate alpha value 10393 * directly. An example of overlapping rendering is a TextView with a background image, such as 10394 * a Button. An example of non-overlapping rendering is a TextView with no background, or an 10395 * ImageView with only the foreground image. The default implementation returns true; subclasses 10396 * should override if they have cases which can be optimized.</p> 10397 * 10398 * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} 10399 * necessitates that a View return true if it uses the methods internally without passing the 10400 * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> 10401 * 10402 * @return true if the content in this view might overlap, false otherwise. 10403 */ 10404 @ViewDebug.ExportedProperty(category = "drawing") 10405 public boolean hasOverlappingRendering() { 10406 return true; 10407 } 10408 10409 /** 10410 * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is 10411 * completely transparent and 1 means the view is completely opaque.</p> 10412 * 10413 * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant 10414 * performance implications, especially for large views. It is best to use the alpha property 10415 * sparingly and transiently, as in the case of fading animations.</p> 10416 * 10417 * <p>For a view with a frequently changing alpha, such as during a fading animation, it is 10418 * strongly recommended for performance reasons to either override 10419 * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a 10420 * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> 10421 * 10422 * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is 10423 * responsible for applying the opacity itself.</p> 10424 * 10425 * <p>Note that if the view is backed by a 10426 * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a 10427 * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than 10428 * 1.0 will supercede the alpha of the layer paint.</p> 10429 * 10430 * @param alpha The opacity of the view. 10431 * 10432 * @see #hasOverlappingRendering() 10433 * @see #setLayerType(int, android.graphics.Paint) 10434 * 10435 * @attr ref android.R.styleable#View_alpha 10436 */ 10437 public void setAlpha(float alpha) { 10438 ensureTransformationInfo(); 10439 if (mTransformationInfo.mAlpha != alpha) { 10440 mTransformationInfo.mAlpha = alpha; 10441 if (onSetAlpha((int) (alpha * 255))) { 10442 mPrivateFlags |= PFLAG_ALPHA_SET; 10443 // subclass is handling alpha - don't optimize rendering cache invalidation 10444 invalidateParentCaches(); 10445 invalidate(true); 10446 } else { 10447 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10448 invalidateViewProperty(true, false); 10449 mRenderNode.setAlpha(getFinalAlpha()); 10450 notifyViewAccessibilityStateChangedIfNeeded( 10451 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 10452 } 10453 } 10454 } 10455 10456 /** 10457 * Faster version of setAlpha() which performs the same steps except there are 10458 * no calls to invalidate(). The caller of this function should perform proper invalidation 10459 * on the parent and this object. The return value indicates whether the subclass handles 10460 * alpha (the return value for onSetAlpha()). 10461 * 10462 * @param alpha The new value for the alpha property 10463 * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and 10464 * the new value for the alpha property is different from the old value 10465 */ 10466 boolean setAlphaNoInvalidation(float alpha) { 10467 ensureTransformationInfo(); 10468 if (mTransformationInfo.mAlpha != alpha) { 10469 mTransformationInfo.mAlpha = alpha; 10470 boolean subclassHandlesAlpha = onSetAlpha((int) (alpha * 255)); 10471 if (subclassHandlesAlpha) { 10472 mPrivateFlags |= PFLAG_ALPHA_SET; 10473 return true; 10474 } else { 10475 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10476 mRenderNode.setAlpha(getFinalAlpha()); 10477 } 10478 } 10479 return false; 10480 } 10481 10482 /** 10483 * This property is hidden and intended only for use by the Fade transition, which 10484 * animates it to produce a visual translucency that does not side-effect (or get 10485 * affected by) the real alpha property. This value is composited with the other 10486 * alpha value (and the AlphaAnimation value, when that is present) to produce 10487 * a final visual translucency result, which is what is passed into the DisplayList. 10488 * 10489 * @hide 10490 */ 10491 public void setTransitionAlpha(float alpha) { 10492 ensureTransformationInfo(); 10493 if (mTransformationInfo.mTransitionAlpha != alpha) { 10494 mTransformationInfo.mTransitionAlpha = alpha; 10495 mPrivateFlags &= ~PFLAG_ALPHA_SET; 10496 invalidateViewProperty(true, false); 10497 mRenderNode.setAlpha(getFinalAlpha()); 10498 } 10499 } 10500 10501 /** 10502 * Calculates the visual alpha of this view, which is a combination of the actual 10503 * alpha value and the transitionAlpha value (if set). 10504 */ 10505 private float getFinalAlpha() { 10506 if (mTransformationInfo != null) { 10507 return mTransformationInfo.mAlpha * mTransformationInfo.mTransitionAlpha; 10508 } 10509 return 1; 10510 } 10511 10512 /** 10513 * This property is hidden and intended only for use by the Fade transition, which 10514 * animates it to produce a visual translucency that does not side-effect (or get 10515 * affected by) the real alpha property. This value is composited with the other 10516 * alpha value (and the AlphaAnimation value, when that is present) to produce 10517 * a final visual translucency result, which is what is passed into the DisplayList. 10518 * 10519 * @hide 10520 */ 10521 @ViewDebug.ExportedProperty(category = "drawing") 10522 public float getTransitionAlpha() { 10523 return mTransformationInfo != null ? mTransformationInfo.mTransitionAlpha : 1; 10524 } 10525 10526 /** 10527 * Top position of this view relative to its parent. 10528 * 10529 * @return The top of this view, in pixels. 10530 */ 10531 @ViewDebug.CapturedViewProperty 10532 public final int getTop() { 10533 return mTop; 10534 } 10535 10536 /** 10537 * Sets the top position of this view relative to its parent. This method is meant to be called 10538 * by the layout system and should not generally be called otherwise, because the property 10539 * may be changed at any time by the layout. 10540 * 10541 * @param top The top of this view, in pixels. 10542 */ 10543 public final void setTop(int top) { 10544 if (top != mTop) { 10545 final boolean matrixIsIdentity = hasIdentityMatrix(); 10546 if (matrixIsIdentity) { 10547 if (mAttachInfo != null) { 10548 int minTop; 10549 int yLoc; 10550 if (top < mTop) { 10551 minTop = top; 10552 yLoc = top - mTop; 10553 } else { 10554 minTop = mTop; 10555 yLoc = 0; 10556 } 10557 invalidate(0, yLoc, mRight - mLeft, mBottom - minTop); 10558 } 10559 } else { 10560 // Double-invalidation is necessary to capture view's old and new areas 10561 invalidate(true); 10562 } 10563 10564 int width = mRight - mLeft; 10565 int oldHeight = mBottom - mTop; 10566 10567 mTop = top; 10568 mRenderNode.setTop(mTop); 10569 10570 sizeChange(width, mBottom - mTop, width, oldHeight); 10571 10572 if (!matrixIsIdentity) { 10573 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10574 invalidate(true); 10575 } 10576 mBackgroundSizeChanged = true; 10577 invalidateParentIfNeeded(); 10578 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10579 // View was rejected last time it was drawn by its parent; this may have changed 10580 invalidateParentIfNeeded(); 10581 } 10582 } 10583 } 10584 10585 /** 10586 * Bottom position of this view relative to its parent. 10587 * 10588 * @return The bottom of this view, in pixels. 10589 */ 10590 @ViewDebug.CapturedViewProperty 10591 public final int getBottom() { 10592 return mBottom; 10593 } 10594 10595 /** 10596 * True if this view has changed since the last time being drawn. 10597 * 10598 * @return The dirty state of this view. 10599 */ 10600 public boolean isDirty() { 10601 return (mPrivateFlags & PFLAG_DIRTY_MASK) != 0; 10602 } 10603 10604 /** 10605 * Sets the bottom position of this view relative to its parent. This method is meant to be 10606 * called by the layout system and should not generally be called otherwise, because the 10607 * property may be changed at any time by the layout. 10608 * 10609 * @param bottom The bottom of this view, in pixels. 10610 */ 10611 public final void setBottom(int bottom) { 10612 if (bottom != mBottom) { 10613 final boolean matrixIsIdentity = hasIdentityMatrix(); 10614 if (matrixIsIdentity) { 10615 if (mAttachInfo != null) { 10616 int maxBottom; 10617 if (bottom < mBottom) { 10618 maxBottom = mBottom; 10619 } else { 10620 maxBottom = bottom; 10621 } 10622 invalidate(0, 0, mRight - mLeft, maxBottom - mTop); 10623 } 10624 } else { 10625 // Double-invalidation is necessary to capture view's old and new areas 10626 invalidate(true); 10627 } 10628 10629 int width = mRight - mLeft; 10630 int oldHeight = mBottom - mTop; 10631 10632 mBottom = bottom; 10633 mRenderNode.setBottom(mBottom); 10634 10635 sizeChange(width, mBottom - mTop, width, oldHeight); 10636 10637 if (!matrixIsIdentity) { 10638 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10639 invalidate(true); 10640 } 10641 mBackgroundSizeChanged = true; 10642 invalidateParentIfNeeded(); 10643 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10644 // View was rejected last time it was drawn by its parent; this may have changed 10645 invalidateParentIfNeeded(); 10646 } 10647 } 10648 } 10649 10650 /** 10651 * Left position of this view relative to its parent. 10652 * 10653 * @return The left edge of this view, in pixels. 10654 */ 10655 @ViewDebug.CapturedViewProperty 10656 public final int getLeft() { 10657 return mLeft; 10658 } 10659 10660 /** 10661 * Sets the left position of this view relative to its parent. This method is meant to be called 10662 * by the layout system and should not generally be called otherwise, because the property 10663 * may be changed at any time by the layout. 10664 * 10665 * @param left The left of this view, in pixels. 10666 */ 10667 public final void setLeft(int left) { 10668 if (left != mLeft) { 10669 final boolean matrixIsIdentity = hasIdentityMatrix(); 10670 if (matrixIsIdentity) { 10671 if (mAttachInfo != null) { 10672 int minLeft; 10673 int xLoc; 10674 if (left < mLeft) { 10675 minLeft = left; 10676 xLoc = left - mLeft; 10677 } else { 10678 minLeft = mLeft; 10679 xLoc = 0; 10680 } 10681 invalidate(xLoc, 0, mRight - minLeft, mBottom - mTop); 10682 } 10683 } else { 10684 // Double-invalidation is necessary to capture view's old and new areas 10685 invalidate(true); 10686 } 10687 10688 int oldWidth = mRight - mLeft; 10689 int height = mBottom - mTop; 10690 10691 mLeft = left; 10692 mRenderNode.setLeft(left); 10693 10694 sizeChange(mRight - mLeft, height, oldWidth, height); 10695 10696 if (!matrixIsIdentity) { 10697 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10698 invalidate(true); 10699 } 10700 mBackgroundSizeChanged = true; 10701 invalidateParentIfNeeded(); 10702 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10703 // View was rejected last time it was drawn by its parent; this may have changed 10704 invalidateParentIfNeeded(); 10705 } 10706 } 10707 } 10708 10709 /** 10710 * Right position of this view relative to its parent. 10711 * 10712 * @return The right edge of this view, in pixels. 10713 */ 10714 @ViewDebug.CapturedViewProperty 10715 public final int getRight() { 10716 return mRight; 10717 } 10718 10719 /** 10720 * Sets the right position of this view relative to its parent. This method is meant to be called 10721 * by the layout system and should not generally be called otherwise, because the property 10722 * may be changed at any time by the layout. 10723 * 10724 * @param right The right of this view, in pixels. 10725 */ 10726 public final void setRight(int right) { 10727 if (right != mRight) { 10728 final boolean matrixIsIdentity = hasIdentityMatrix(); 10729 if (matrixIsIdentity) { 10730 if (mAttachInfo != null) { 10731 int maxRight; 10732 if (right < mRight) { 10733 maxRight = mRight; 10734 } else { 10735 maxRight = right; 10736 } 10737 invalidate(0, 0, maxRight - mLeft, mBottom - mTop); 10738 } 10739 } else { 10740 // Double-invalidation is necessary to capture view's old and new areas 10741 invalidate(true); 10742 } 10743 10744 int oldWidth = mRight - mLeft; 10745 int height = mBottom - mTop; 10746 10747 mRight = right; 10748 mRenderNode.setRight(mRight); 10749 10750 sizeChange(mRight - mLeft, height, oldWidth, height); 10751 10752 if (!matrixIsIdentity) { 10753 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 10754 invalidate(true); 10755 } 10756 mBackgroundSizeChanged = true; 10757 invalidateParentIfNeeded(); 10758 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) == PFLAG2_VIEW_QUICK_REJECTED) { 10759 // View was rejected last time it was drawn by its parent; this may have changed 10760 invalidateParentIfNeeded(); 10761 } 10762 } 10763 } 10764 10765 /** 10766 * The visual x position of this view, in pixels. This is equivalent to the 10767 * {@link #setTranslationX(float) translationX} property plus the current 10768 * {@link #getLeft() left} property. 10769 * 10770 * @return The visual x position of this view, in pixels. 10771 */ 10772 @ViewDebug.ExportedProperty(category = "drawing") 10773 public float getX() { 10774 return mLeft + getTranslationX(); 10775 } 10776 10777 /** 10778 * Sets the visual x position of this view, in pixels. This is equivalent to setting the 10779 * {@link #setTranslationX(float) translationX} property to be the difference between 10780 * the x value passed in and the current {@link #getLeft() left} property. 10781 * 10782 * @param x The visual x position of this view, in pixels. 10783 */ 10784 public void setX(float x) { 10785 setTranslationX(x - mLeft); 10786 } 10787 10788 /** 10789 * The visual y position of this view, in pixels. This is equivalent to the 10790 * {@link #setTranslationY(float) translationY} property plus the current 10791 * {@link #getTop() top} property. 10792 * 10793 * @return The visual y position of this view, in pixels. 10794 */ 10795 @ViewDebug.ExportedProperty(category = "drawing") 10796 public float getY() { 10797 return mTop + getTranslationY(); 10798 } 10799 10800 /** 10801 * Sets the visual y position of this view, in pixels. This is equivalent to setting the 10802 * {@link #setTranslationY(float) translationY} property to be the difference between 10803 * the y value passed in and the current {@link #getTop() top} property. 10804 * 10805 * @param y The visual y position of this view, in pixels. 10806 */ 10807 public void setY(float y) { 10808 setTranslationY(y - mTop); 10809 } 10810 10811 /** 10812 * The visual z position of this view, in pixels. This is equivalent to the 10813 * {@link #setTranslationZ(float) translationZ} property plus the current 10814 * {@link #getElevation() elevation} property. 10815 * 10816 * @return The visual z position of this view, in pixels. 10817 */ 10818 @ViewDebug.ExportedProperty(category = "drawing") 10819 public float getZ() { 10820 return getElevation() + getTranslationZ(); 10821 } 10822 10823 /** 10824 * Sets the visual z position of this view, in pixels. This is equivalent to setting the 10825 * {@link #setTranslationZ(float) translationZ} property to be the difference between 10826 * the x value passed in and the current {@link #getElevation() elevation} property. 10827 * 10828 * @param z The visual z position of this view, in pixels. 10829 */ 10830 public void setZ(float z) { 10831 setTranslationZ(z - getElevation()); 10832 } 10833 10834 /** 10835 * The base elevation of this view relative to its parent, in pixels. 10836 * 10837 * @return The base depth position of the view, in pixels. 10838 */ 10839 @ViewDebug.ExportedProperty(category = "drawing") 10840 public float getElevation() { 10841 return mRenderNode.getElevation(); 10842 } 10843 10844 /** 10845 * Sets the base elevation of this view, in pixels. 10846 * 10847 * @attr ref android.R.styleable#View_elevation 10848 */ 10849 public void setElevation(float elevation) { 10850 if (elevation != getElevation()) { 10851 invalidateViewProperty(true, false); 10852 mRenderNode.setElevation(elevation); 10853 invalidateViewProperty(false, true); 10854 10855 invalidateParentIfNeededAndWasQuickRejected(); 10856 } 10857 } 10858 10859 /** 10860 * The horizontal location of this view relative to its {@link #getLeft() left} position. 10861 * This position is post-layout, in addition to wherever the object's 10862 * layout placed it. 10863 * 10864 * @return The horizontal position of this view relative to its left position, in pixels. 10865 */ 10866 @ViewDebug.ExportedProperty(category = "drawing") 10867 public float getTranslationX() { 10868 return mRenderNode.getTranslationX(); 10869 } 10870 10871 /** 10872 * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. 10873 * This effectively positions the object post-layout, in addition to wherever the object's 10874 * layout placed it. 10875 * 10876 * @param translationX The horizontal position of this view relative to its left position, 10877 * in pixels. 10878 * 10879 * @attr ref android.R.styleable#View_translationX 10880 */ 10881 public void setTranslationX(float translationX) { 10882 if (translationX != getTranslationX()) { 10883 invalidateViewProperty(true, false); 10884 mRenderNode.setTranslationX(translationX); 10885 invalidateViewProperty(false, true); 10886 10887 invalidateParentIfNeededAndWasQuickRejected(); 10888 notifySubtreeAccessibilityStateChangedIfNeeded(); 10889 } 10890 } 10891 10892 /** 10893 * The vertical location of this view relative to its {@link #getTop() top} position. 10894 * This position is post-layout, in addition to wherever the object's 10895 * layout placed it. 10896 * 10897 * @return The vertical position of this view relative to its top position, 10898 * in pixels. 10899 */ 10900 @ViewDebug.ExportedProperty(category = "drawing") 10901 public float getTranslationY() { 10902 return mRenderNode.getTranslationY(); 10903 } 10904 10905 /** 10906 * Sets the vertical location of this view relative to its {@link #getTop() top} position. 10907 * This effectively positions the object post-layout, in addition to wherever the object's 10908 * layout placed it. 10909 * 10910 * @param translationY The vertical position of this view relative to its top position, 10911 * in pixels. 10912 * 10913 * @attr ref android.R.styleable#View_translationY 10914 */ 10915 public void setTranslationY(float translationY) { 10916 if (translationY != getTranslationY()) { 10917 invalidateViewProperty(true, false); 10918 mRenderNode.setTranslationY(translationY); 10919 invalidateViewProperty(false, true); 10920 10921 invalidateParentIfNeededAndWasQuickRejected(); 10922 } 10923 } 10924 10925 /** 10926 * The depth location of this view relative to its {@link #getElevation() elevation}. 10927 * 10928 * @return The depth of this view relative to its elevation. 10929 */ 10930 @ViewDebug.ExportedProperty(category = "drawing") 10931 public float getTranslationZ() { 10932 return mRenderNode.getTranslationZ(); 10933 } 10934 10935 /** 10936 * Sets the depth location of this view relative to its {@link #getElevation() elevation}. 10937 * 10938 * @attr ref android.R.styleable#View_translationZ 10939 */ 10940 public void setTranslationZ(float translationZ) { 10941 if (translationZ != getTranslationZ()) { 10942 invalidateViewProperty(true, false); 10943 mRenderNode.setTranslationZ(translationZ); 10944 invalidateViewProperty(false, true); 10945 10946 invalidateParentIfNeededAndWasQuickRejected(); 10947 } 10948 } 10949 10950 /** @hide */ 10951 public void setAnimationMatrix(Matrix matrix) { 10952 invalidateViewProperty(true, false); 10953 mRenderNode.setAnimationMatrix(matrix); 10954 invalidateViewProperty(false, true); 10955 10956 invalidateParentIfNeededAndWasQuickRejected(); 10957 } 10958 10959 /** 10960 * Returns the current StateListAnimator if exists. 10961 * 10962 * @return StateListAnimator or null if it does not exists 10963 * @see #setStateListAnimator(android.animation.StateListAnimator) 10964 */ 10965 public StateListAnimator getStateListAnimator() { 10966 return mStateListAnimator; 10967 } 10968 10969 /** 10970 * Attaches the provided StateListAnimator to this View. 10971 * <p> 10972 * Any previously attached StateListAnimator will be detached. 10973 * 10974 * @param stateListAnimator The StateListAnimator to update the view 10975 * @see {@link android.animation.StateListAnimator} 10976 */ 10977 public void setStateListAnimator(StateListAnimator stateListAnimator) { 10978 if (mStateListAnimator == stateListAnimator) { 10979 return; 10980 } 10981 if (mStateListAnimator != null) { 10982 mStateListAnimator.setTarget(null); 10983 } 10984 mStateListAnimator = stateListAnimator; 10985 if (stateListAnimator != null) { 10986 stateListAnimator.setTarget(this); 10987 if (isAttachedToWindow()) { 10988 stateListAnimator.setState(getDrawableState()); 10989 } 10990 } 10991 } 10992 10993 /** 10994 * Returns whether the Outline should be used to clip the contents of the View. 10995 * <p> 10996 * Note that this flag will only be respected if the View's Outline returns true from 10997 * {@link Outline#canClip()}. 10998 * 10999 * @see #setOutlineProvider(ViewOutlineProvider) 11000 * @see #setClipToOutline(boolean) 11001 */ 11002 public final boolean getClipToOutline() { 11003 return mRenderNode.getClipToOutline(); 11004 } 11005 11006 /** 11007 * Sets whether the View's Outline should be used to clip the contents of the View. 11008 * <p> 11009 * Only a single non-rectangular clip can be applied on a View at any time. 11010 * Circular clips from a {@link ViewAnimationUtils#createCircularReveal(View, int, int, float, float) 11011 * circular reveal} animation take priority over Outline clipping, and 11012 * child Outline clipping takes priority over Outline clipping done by a 11013 * parent. 11014 * <p> 11015 * Note that this flag will only be respected if the View's Outline returns true from 11016 * {@link Outline#canClip()}. 11017 * 11018 * @see #setOutlineProvider(ViewOutlineProvider) 11019 * @see #getClipToOutline() 11020 */ 11021 public void setClipToOutline(boolean clipToOutline) { 11022 damageInParent(); 11023 if (getClipToOutline() != clipToOutline) { 11024 mRenderNode.setClipToOutline(clipToOutline); 11025 } 11026 } 11027 11028 // correspond to the enum values of View_outlineProvider 11029 private static final int PROVIDER_BACKGROUND = 0; 11030 private static final int PROVIDER_NONE = 1; 11031 private static final int PROVIDER_BOUNDS = 2; 11032 private static final int PROVIDER_PADDED_BOUNDS = 3; 11033 private void setOutlineProviderFromAttribute(int providerInt) { 11034 switch (providerInt) { 11035 case PROVIDER_BACKGROUND: 11036 setOutlineProvider(ViewOutlineProvider.BACKGROUND); 11037 break; 11038 case PROVIDER_NONE: 11039 setOutlineProvider(null); 11040 break; 11041 case PROVIDER_BOUNDS: 11042 setOutlineProvider(ViewOutlineProvider.BOUNDS); 11043 break; 11044 case PROVIDER_PADDED_BOUNDS: 11045 setOutlineProvider(ViewOutlineProvider.PADDED_BOUNDS); 11046 break; 11047 } 11048 } 11049 11050 /** 11051 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines 11052 * the shape of the shadow it casts, and enables outline clipping. 11053 * <p> 11054 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline 11055 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the 11056 * outline provider with this method allows this behavior to be overridden. 11057 * <p> 11058 * If the ViewOutlineProvider is null, if querying it for an outline returns false, 11059 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast. 11060 * <p> 11061 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping. 11062 * 11063 * @see #setClipToOutline(boolean) 11064 * @see #getClipToOutline() 11065 * @see #getOutlineProvider() 11066 */ 11067 public void setOutlineProvider(ViewOutlineProvider provider) { 11068 mOutlineProvider = provider; 11069 invalidateOutline(); 11070 } 11071 11072 /** 11073 * Returns the current {@link ViewOutlineProvider} of the view, which generates the Outline 11074 * that defines the shape of the shadow it casts, and enables outline clipping. 11075 * 11076 * @see #setOutlineProvider(ViewOutlineProvider) 11077 */ 11078 public ViewOutlineProvider getOutlineProvider() { 11079 return mOutlineProvider; 11080 } 11081 11082 /** 11083 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider} 11084 * 11085 * @see #setOutlineProvider(ViewOutlineProvider) 11086 */ 11087 public void invalidateOutline() { 11088 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 11089 11090 notifySubtreeAccessibilityStateChangedIfNeeded(); 11091 invalidateViewProperty(false, false); 11092 } 11093 11094 /** 11095 * Internal version of {@link #invalidateOutline()} which invalidates the 11096 * outline without invalidating the view itself. This is intended to be called from 11097 * within methods in the View class itself which are the result of the view being 11098 * invalidated already. For example, when we are drawing the background of a View, 11099 * we invalidate the outline in case it changed in the meantime, but we do not 11100 * need to invalidate the view because we're already drawing the background as part 11101 * of drawing the view in response to an earlier invalidation of the view. 11102 */ 11103 private void rebuildOutline() { 11104 // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow() 11105 if (mAttachInfo == null) return; 11106 11107 if (mOutlineProvider == null) { 11108 // no provider, remove outline 11109 mRenderNode.setOutline(null); 11110 } else { 11111 final Outline outline = mAttachInfo.mTmpOutline; 11112 outline.setEmpty(); 11113 outline.setAlpha(1.0f); 11114 11115 mOutlineProvider.getOutline(this, outline); 11116 mRenderNode.setOutline(outline); 11117 } 11118 } 11119 11120 /** 11121 * HierarchyViewer only 11122 * 11123 * @hide 11124 */ 11125 @ViewDebug.ExportedProperty(category = "drawing") 11126 public boolean hasShadow() { 11127 return mRenderNode.hasShadow(); 11128 } 11129 11130 11131 /** @hide */ 11132 public void setRevealClip(boolean shouldClip, float x, float y, float radius) { 11133 mRenderNode.setRevealClip(shouldClip, x, y, radius); 11134 invalidateViewProperty(false, false); 11135 } 11136 11137 /** 11138 * Hit rectangle in parent's coordinates 11139 * 11140 * @param outRect The hit rectangle of the view. 11141 */ 11142 public void getHitRect(Rect outRect) { 11143 if (hasIdentityMatrix() || mAttachInfo == null) { 11144 outRect.set(mLeft, mTop, mRight, mBottom); 11145 } else { 11146 final RectF tmpRect = mAttachInfo.mTmpTransformRect; 11147 tmpRect.set(0, 0, getWidth(), getHeight()); 11148 getMatrix().mapRect(tmpRect); // TODO: mRenderNode.mapRect(tmpRect) 11149 outRect.set((int) tmpRect.left + mLeft, (int) tmpRect.top + mTop, 11150 (int) tmpRect.right + mLeft, (int) tmpRect.bottom + mTop); 11151 } 11152 } 11153 11154 /** 11155 * Determines whether the given point, in local coordinates is inside the view. 11156 */ 11157 /*package*/ final boolean pointInView(float localX, float localY) { 11158 return localX >= 0 && localX < (mRight - mLeft) 11159 && localY >= 0 && localY < (mBottom - mTop); 11160 } 11161 11162 /** 11163 * Utility method to determine whether the given point, in local coordinates, 11164 * is inside the view, where the area of the view is expanded by the slop factor. 11165 * This method is called while processing touch-move events to determine if the event 11166 * is still within the view. 11167 * 11168 * @hide 11169 */ 11170 public boolean pointInView(float localX, float localY, float slop) { 11171 return localX >= -slop && localY >= -slop && localX < ((mRight - mLeft) + slop) && 11172 localY < ((mBottom - mTop) + slop); 11173 } 11174 11175 /** 11176 * When a view has focus and the user navigates away from it, the next view is searched for 11177 * starting from the rectangle filled in by this method. 11178 * 11179 * By default, the rectangle is the {@link #getDrawingRect(android.graphics.Rect)}) 11180 * of the view. However, if your view maintains some idea of internal selection, 11181 * such as a cursor, or a selected row or column, you should override this method and 11182 * fill in a more specific rectangle. 11183 * 11184 * @param r The rectangle to fill in, in this view's coordinates. 11185 */ 11186 public void getFocusedRect(Rect r) { 11187 getDrawingRect(r); 11188 } 11189 11190 /** 11191 * If some part of this view is not clipped by any of its parents, then 11192 * return that area in r in global (root) coordinates. To convert r to local 11193 * coordinates (without taking possible View rotations into account), offset 11194 * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). 11195 * If the view is completely clipped or translated out, return false. 11196 * 11197 * @param r If true is returned, r holds the global coordinates of the 11198 * visible portion of this view. 11199 * @param globalOffset If true is returned, globalOffset holds the dx,dy 11200 * between this view and its root. globalOffet may be null. 11201 * @return true if r is non-empty (i.e. part of the view is visible at the 11202 * root level. 11203 */ 11204 public boolean getGlobalVisibleRect(Rect r, Point globalOffset) { 11205 int width = mRight - mLeft; 11206 int height = mBottom - mTop; 11207 if (width > 0 && height > 0) { 11208 r.set(0, 0, width, height); 11209 if (globalOffset != null) { 11210 globalOffset.set(-mScrollX, -mScrollY); 11211 } 11212 return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset); 11213 } 11214 return false; 11215 } 11216 11217 public final boolean getGlobalVisibleRect(Rect r) { 11218 return getGlobalVisibleRect(r, null); 11219 } 11220 11221 public final boolean getLocalVisibleRect(Rect r) { 11222 final Point offset = mAttachInfo != null ? mAttachInfo.mPoint : new Point(); 11223 if (getGlobalVisibleRect(r, offset)) { 11224 r.offset(-offset.x, -offset.y); // make r local 11225 return true; 11226 } 11227 return false; 11228 } 11229 11230 /** 11231 * Offset this view's vertical location by the specified number of pixels. 11232 * 11233 * @param offset the number of pixels to offset the view by 11234 */ 11235 public void offsetTopAndBottom(int offset) { 11236 if (offset != 0) { 11237 final boolean matrixIsIdentity = hasIdentityMatrix(); 11238 if (matrixIsIdentity) { 11239 if (isHardwareAccelerated()) { 11240 invalidateViewProperty(false, false); 11241 } else { 11242 final ViewParent p = mParent; 11243 if (p != null && mAttachInfo != null) { 11244 final Rect r = mAttachInfo.mTmpInvalRect; 11245 int minTop; 11246 int maxBottom; 11247 int yLoc; 11248 if (offset < 0) { 11249 minTop = mTop + offset; 11250 maxBottom = mBottom; 11251 yLoc = offset; 11252 } else { 11253 minTop = mTop; 11254 maxBottom = mBottom + offset; 11255 yLoc = 0; 11256 } 11257 r.set(0, yLoc, mRight - mLeft, maxBottom - minTop); 11258 p.invalidateChild(this, r); 11259 } 11260 } 11261 } else { 11262 invalidateViewProperty(false, false); 11263 } 11264 11265 mTop += offset; 11266 mBottom += offset; 11267 mRenderNode.offsetTopAndBottom(offset); 11268 if (isHardwareAccelerated()) { 11269 invalidateViewProperty(false, false); 11270 } else { 11271 if (!matrixIsIdentity) { 11272 invalidateViewProperty(false, true); 11273 } 11274 invalidateParentIfNeeded(); 11275 } 11276 notifySubtreeAccessibilityStateChangedIfNeeded(); 11277 } 11278 } 11279 11280 /** 11281 * Offset this view's horizontal location by the specified amount of pixels. 11282 * 11283 * @param offset the number of pixels to offset the view by 11284 */ 11285 public void offsetLeftAndRight(int offset) { 11286 if (offset != 0) { 11287 final boolean matrixIsIdentity = hasIdentityMatrix(); 11288 if (matrixIsIdentity) { 11289 if (isHardwareAccelerated()) { 11290 invalidateViewProperty(false, false); 11291 } else { 11292 final ViewParent p = mParent; 11293 if (p != null && mAttachInfo != null) { 11294 final Rect r = mAttachInfo.mTmpInvalRect; 11295 int minLeft; 11296 int maxRight; 11297 if (offset < 0) { 11298 minLeft = mLeft + offset; 11299 maxRight = mRight; 11300 } else { 11301 minLeft = mLeft; 11302 maxRight = mRight + offset; 11303 } 11304 r.set(0, 0, maxRight - minLeft, mBottom - mTop); 11305 p.invalidateChild(this, r); 11306 } 11307 } 11308 } else { 11309 invalidateViewProperty(false, false); 11310 } 11311 11312 mLeft += offset; 11313 mRight += offset; 11314 mRenderNode.offsetLeftAndRight(offset); 11315 if (isHardwareAccelerated()) { 11316 invalidateViewProperty(false, false); 11317 } else { 11318 if (!matrixIsIdentity) { 11319 invalidateViewProperty(false, true); 11320 } 11321 invalidateParentIfNeeded(); 11322 } 11323 notifySubtreeAccessibilityStateChangedIfNeeded(); 11324 } 11325 } 11326 11327 /** 11328 * Get the LayoutParams associated with this view. All views should have 11329 * layout parameters. These supply parameters to the <i>parent</i> of this 11330 * view specifying how it should be arranged. There are many subclasses of 11331 * ViewGroup.LayoutParams, and these correspond to the different subclasses 11332 * of ViewGroup that are responsible for arranging their children. 11333 * 11334 * This method may return null if this View is not attached to a parent 11335 * ViewGroup or {@link #setLayoutParams(android.view.ViewGroup.LayoutParams)} 11336 * was not invoked successfully. When a View is attached to a parent 11337 * ViewGroup, this method must not return null. 11338 * 11339 * @return The LayoutParams associated with this view, or null if no 11340 * parameters have been set yet 11341 */ 11342 @ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_") 11343 public ViewGroup.LayoutParams getLayoutParams() { 11344 return mLayoutParams; 11345 } 11346 11347 /** 11348 * Set the layout parameters associated with this view. These supply 11349 * parameters to the <i>parent</i> of this view specifying how it should be 11350 * arranged. There are many subclasses of ViewGroup.LayoutParams, and these 11351 * correspond to the different subclasses of ViewGroup that are responsible 11352 * for arranging their children. 11353 * 11354 * @param params The layout parameters for this view, cannot be null 11355 */ 11356 public void setLayoutParams(ViewGroup.LayoutParams params) { 11357 if (params == null) { 11358 throw new NullPointerException("Layout parameters cannot be null"); 11359 } 11360 mLayoutParams = params; 11361 resolveLayoutParams(); 11362 if (mParent instanceof ViewGroup) { 11363 ((ViewGroup) mParent).onSetLayoutParams(this, params); 11364 } 11365 requestLayout(); 11366 } 11367 11368 /** 11369 * Resolve the layout parameters depending on the resolved layout direction 11370 * 11371 * @hide 11372 */ 11373 public void resolveLayoutParams() { 11374 if (mLayoutParams != null) { 11375 mLayoutParams.resolveLayoutDirection(getLayoutDirection()); 11376 } 11377 } 11378 11379 /** 11380 * Set the scrolled position of your view. This will cause a call to 11381 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11382 * invalidated. 11383 * @param x the x position to scroll to 11384 * @param y the y position to scroll to 11385 */ 11386 public void scrollTo(int x, int y) { 11387 if (mScrollX != x || mScrollY != y) { 11388 int oldX = mScrollX; 11389 int oldY = mScrollY; 11390 mScrollX = x; 11391 mScrollY = y; 11392 invalidateParentCaches(); 11393 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 11394 if (!awakenScrollBars()) { 11395 postInvalidateOnAnimation(); 11396 } 11397 } 11398 } 11399 11400 /** 11401 * Move the scrolled position of your view. This will cause a call to 11402 * {@link #onScrollChanged(int, int, int, int)} and the view will be 11403 * invalidated. 11404 * @param x the amount of pixels to scroll by horizontally 11405 * @param y the amount of pixels to scroll by vertically 11406 */ 11407 public void scrollBy(int x, int y) { 11408 scrollTo(mScrollX + x, mScrollY + y); 11409 } 11410 11411 /** 11412 * <p>Trigger the scrollbars to draw. When invoked this method starts an 11413 * animation to fade the scrollbars out after a default delay. If a subclass 11414 * provides animated scrolling, the start delay should equal the duration 11415 * of the scrolling animation.</p> 11416 * 11417 * <p>The animation starts only if at least one of the scrollbars is 11418 * enabled, as specified by {@link #isHorizontalScrollBarEnabled()} and 11419 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11420 * this method returns true, and false otherwise. If the animation is 11421 * started, this method calls {@link #invalidate()}; in that case the 11422 * caller should not call {@link #invalidate()}.</p> 11423 * 11424 * <p>This method should be invoked every time a subclass directly updates 11425 * the scroll parameters.</p> 11426 * 11427 * <p>This method is automatically invoked by {@link #scrollBy(int, int)} 11428 * and {@link #scrollTo(int, int)}.</p> 11429 * 11430 * @return true if the animation is played, false otherwise 11431 * 11432 * @see #awakenScrollBars(int) 11433 * @see #scrollBy(int, int) 11434 * @see #scrollTo(int, int) 11435 * @see #isHorizontalScrollBarEnabled() 11436 * @see #isVerticalScrollBarEnabled() 11437 * @see #setHorizontalScrollBarEnabled(boolean) 11438 * @see #setVerticalScrollBarEnabled(boolean) 11439 */ 11440 protected boolean awakenScrollBars() { 11441 return mScrollCache != null && 11442 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade, true); 11443 } 11444 11445 /** 11446 * Trigger the scrollbars to draw. 11447 * This method differs from awakenScrollBars() only in its default duration. 11448 * initialAwakenScrollBars() will show the scroll bars for longer than 11449 * usual to give the user more of a chance to notice them. 11450 * 11451 * @return true if the animation is played, false otherwise. 11452 */ 11453 private boolean initialAwakenScrollBars() { 11454 return mScrollCache != null && 11455 awakenScrollBars(mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); 11456 } 11457 11458 /** 11459 * <p> 11460 * Trigger the scrollbars to draw. When invoked this method starts an 11461 * animation to fade the scrollbars out after a fixed delay. If a subclass 11462 * provides animated scrolling, the start delay should equal the duration of 11463 * the scrolling animation. 11464 * </p> 11465 * 11466 * <p> 11467 * The animation starts only if at least one of the scrollbars is enabled, 11468 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11469 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11470 * this method returns true, and false otherwise. If the animation is 11471 * started, this method calls {@link #invalidate()}; in that case the caller 11472 * should not call {@link #invalidate()}. 11473 * </p> 11474 * 11475 * <p> 11476 * This method should be invoked everytime a subclass directly updates the 11477 * scroll parameters. 11478 * </p> 11479 * 11480 * @param startDelay the delay, in milliseconds, after which the animation 11481 * should start; when the delay is 0, the animation starts 11482 * immediately 11483 * @return true if the animation is played, false otherwise 11484 * 11485 * @see #scrollBy(int, int) 11486 * @see #scrollTo(int, int) 11487 * @see #isHorizontalScrollBarEnabled() 11488 * @see #isVerticalScrollBarEnabled() 11489 * @see #setHorizontalScrollBarEnabled(boolean) 11490 * @see #setVerticalScrollBarEnabled(boolean) 11491 */ 11492 protected boolean awakenScrollBars(int startDelay) { 11493 return awakenScrollBars(startDelay, true); 11494 } 11495 11496 /** 11497 * <p> 11498 * Trigger the scrollbars to draw. When invoked this method starts an 11499 * animation to fade the scrollbars out after a fixed delay. If a subclass 11500 * provides animated scrolling, the start delay should equal the duration of 11501 * the scrolling animation. 11502 * </p> 11503 * 11504 * <p> 11505 * The animation starts only if at least one of the scrollbars is enabled, 11506 * as specified by {@link #isHorizontalScrollBarEnabled()} and 11507 * {@link #isVerticalScrollBarEnabled()}. When the animation is started, 11508 * this method returns true, and false otherwise. If the animation is 11509 * started, this method calls {@link #invalidate()} if the invalidate parameter 11510 * is set to true; in that case the caller 11511 * should not call {@link #invalidate()}. 11512 * </p> 11513 * 11514 * <p> 11515 * This method should be invoked everytime a subclass directly updates the 11516 * scroll parameters. 11517 * </p> 11518 * 11519 * @param startDelay the delay, in milliseconds, after which the animation 11520 * should start; when the delay is 0, the animation starts 11521 * immediately 11522 * 11523 * @param invalidate Wheter this method should call invalidate 11524 * 11525 * @return true if the animation is played, false otherwise 11526 * 11527 * @see #scrollBy(int, int) 11528 * @see #scrollTo(int, int) 11529 * @see #isHorizontalScrollBarEnabled() 11530 * @see #isVerticalScrollBarEnabled() 11531 * @see #setHorizontalScrollBarEnabled(boolean) 11532 * @see #setVerticalScrollBarEnabled(boolean) 11533 */ 11534 protected boolean awakenScrollBars(int startDelay, boolean invalidate) { 11535 final ScrollabilityCache scrollCache = mScrollCache; 11536 11537 if (scrollCache == null || !scrollCache.fadeScrollBars) { 11538 return false; 11539 } 11540 11541 if (scrollCache.scrollBar == null) { 11542 scrollCache.scrollBar = new ScrollBarDrawable(); 11543 } 11544 11545 if (isHorizontalScrollBarEnabled() || isVerticalScrollBarEnabled()) { 11546 11547 if (invalidate) { 11548 // Invalidate to show the scrollbars 11549 postInvalidateOnAnimation(); 11550 } 11551 11552 if (scrollCache.state == ScrollabilityCache.OFF) { 11553 // FIXME: this is copied from WindowManagerService. 11554 // We should get this value from the system when it 11555 // is possible to do so. 11556 final int KEY_REPEAT_FIRST_DELAY = 750; 11557 startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); 11558 } 11559 11560 // Tell mScrollCache when we should start fading. This may 11561 // extend the fade start time if one was already scheduled 11562 long fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; 11563 scrollCache.fadeStartTime = fadeStartTime; 11564 scrollCache.state = ScrollabilityCache.ON; 11565 11566 // Schedule our fader to run, unscheduling any old ones first 11567 if (mAttachInfo != null) { 11568 mAttachInfo.mHandler.removeCallbacks(scrollCache); 11569 mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); 11570 } 11571 11572 return true; 11573 } 11574 11575 return false; 11576 } 11577 11578 /** 11579 * Do not invalidate views which are not visible and which are not running an animation. They 11580 * will not get drawn and they should not set dirty flags as if they will be drawn 11581 */ 11582 private boolean skipInvalidate() { 11583 return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null && 11584 (!(mParent instanceof ViewGroup) || 11585 !((ViewGroup) mParent).isViewTransitioning(this)); 11586 } 11587 11588 /** 11589 * Mark the area defined by dirty as needing to be drawn. If the view is 11590 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11591 * point in the future. 11592 * <p> 11593 * This must be called from a UI thread. To call from a non-UI thread, call 11594 * {@link #postInvalidate()}. 11595 * <p> 11596 * <b>WARNING:</b> In API 19 and below, this method may be destructive to 11597 * {@code dirty}. 11598 * 11599 * @param dirty the rectangle representing the bounds of the dirty region 11600 */ 11601 public void invalidate(Rect dirty) { 11602 final int scrollX = mScrollX; 11603 final int scrollY = mScrollY; 11604 invalidateInternal(dirty.left - scrollX, dirty.top - scrollY, 11605 dirty.right - scrollX, dirty.bottom - scrollY, true, false); 11606 } 11607 11608 /** 11609 * Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The 11610 * coordinates of the dirty rect are relative to the view. If the view is 11611 * visible, {@link #onDraw(android.graphics.Canvas)} will be called at some 11612 * point in the future. 11613 * <p> 11614 * This must be called from a UI thread. To call from a non-UI thread, call 11615 * {@link #postInvalidate()}. 11616 * 11617 * @param l the left position of the dirty region 11618 * @param t the top position of the dirty region 11619 * @param r the right position of the dirty region 11620 * @param b the bottom position of the dirty region 11621 */ 11622 public void invalidate(int l, int t, int r, int b) { 11623 final int scrollX = mScrollX; 11624 final int scrollY = mScrollY; 11625 invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, true, false); 11626 } 11627 11628 /** 11629 * Invalidate the whole view. If the view is visible, 11630 * {@link #onDraw(android.graphics.Canvas)} will be called at some point in 11631 * the future. 11632 * <p> 11633 * This must be called from a UI thread. To call from a non-UI thread, call 11634 * {@link #postInvalidate()}. 11635 */ 11636 public void invalidate() { 11637 invalidate(true); 11638 } 11639 11640 /** 11641 * This is where the invalidate() work actually happens. A full invalidate() 11642 * causes the drawing cache to be invalidated, but this function can be 11643 * called with invalidateCache set to false to skip that invalidation step 11644 * for cases that do not need it (for example, a component that remains at 11645 * the same dimensions with the same content). 11646 * 11647 * @param invalidateCache Whether the drawing cache for this view should be 11648 * invalidated as well. This is usually true for a full 11649 * invalidate, but may be set to false if the View's contents or 11650 * dimensions have not changed. 11651 */ 11652 void invalidate(boolean invalidateCache) { 11653 invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true); 11654 } 11655 11656 void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache, 11657 boolean fullInvalidate) { 11658 if (mGhostView != null) { 11659 mGhostView.invalidate(invalidateCache); 11660 return; 11661 } 11662 11663 if (skipInvalidate()) { 11664 return; 11665 } 11666 11667 if ((mPrivateFlags & (PFLAG_DRAWN | PFLAG_HAS_BOUNDS)) == (PFLAG_DRAWN | PFLAG_HAS_BOUNDS) 11668 || (invalidateCache && (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) 11669 || (mPrivateFlags & PFLAG_INVALIDATED) != PFLAG_INVALIDATED 11670 || (fullInvalidate && isOpaque() != mLastIsOpaque)) { 11671 if (fullInvalidate) { 11672 mLastIsOpaque = isOpaque(); 11673 mPrivateFlags &= ~PFLAG_DRAWN; 11674 } 11675 11676 mPrivateFlags |= PFLAG_DIRTY; 11677 11678 if (invalidateCache) { 11679 mPrivateFlags |= PFLAG_INVALIDATED; 11680 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 11681 } 11682 11683 // Propagate the damage rectangle to the parent view. 11684 final AttachInfo ai = mAttachInfo; 11685 final ViewParent p = mParent; 11686 if (p != null && ai != null && l < r && t < b) { 11687 final Rect damage = ai.mTmpInvalRect; 11688 damage.set(l, t, r, b); 11689 p.invalidateChild(this, damage); 11690 } 11691 11692 // Damage the entire projection receiver, if necessary. 11693 if (mBackground != null && mBackground.isProjected()) { 11694 final View receiver = getProjectionReceiver(); 11695 if (receiver != null) { 11696 receiver.damageInParent(); 11697 } 11698 } 11699 11700 // Damage the entire IsolatedZVolume receiving this view's shadow. 11701 if (isHardwareAccelerated() && getZ() != 0) { 11702 damageShadowReceiver(); 11703 } 11704 } 11705 } 11706 11707 /** 11708 * @return this view's projection receiver, or {@code null} if none exists 11709 */ 11710 private View getProjectionReceiver() { 11711 ViewParent p = getParent(); 11712 while (p != null && p instanceof View) { 11713 final View v = (View) p; 11714 if (v.isProjectionReceiver()) { 11715 return v; 11716 } 11717 p = p.getParent(); 11718 } 11719 11720 return null; 11721 } 11722 11723 /** 11724 * @return whether the view is a projection receiver 11725 */ 11726 private boolean isProjectionReceiver() { 11727 return mBackground != null; 11728 } 11729 11730 /** 11731 * Damage area of the screen that can be covered by this View's shadow. 11732 * 11733 * This method will guarantee that any changes to shadows cast by a View 11734 * are damaged on the screen for future redraw. 11735 */ 11736 private void damageShadowReceiver() { 11737 final AttachInfo ai = mAttachInfo; 11738 if (ai != null) { 11739 ViewParent p = getParent(); 11740 if (p != null && p instanceof ViewGroup) { 11741 final ViewGroup vg = (ViewGroup) p; 11742 vg.damageInParent(); 11743 } 11744 } 11745 } 11746 11747 /** 11748 * Quick invalidation for View property changes (alpha, translationXY, etc.). We don't want to 11749 * set any flags or handle all of the cases handled by the default invalidation methods. 11750 * Instead, we just want to schedule a traversal in ViewRootImpl with the appropriate 11751 * dirty rect. This method calls into fast invalidation methods in ViewGroup that 11752 * walk up the hierarchy, transforming the dirty rect as necessary. 11753 * 11754 * The method also handles normal invalidation logic if display list properties are not 11755 * being used in this view. The invalidateParent and forceRedraw flags are used by that 11756 * backup approach, to handle these cases used in the various property-setting methods. 11757 * 11758 * @param invalidateParent Force a call to invalidateParentCaches() if display list properties 11759 * are not being used in this view 11760 * @param forceRedraw Mark the view as DRAWN to force the invalidation to propagate, if display 11761 * list properties are not being used in this view 11762 */ 11763 void invalidateViewProperty(boolean invalidateParent, boolean forceRedraw) { 11764 if (!isHardwareAccelerated() 11765 || !mRenderNode.isValid() 11766 || (mPrivateFlags & PFLAG_DRAW_ANIMATION) != 0) { 11767 if (invalidateParent) { 11768 invalidateParentCaches(); 11769 } 11770 if (forceRedraw) { 11771 mPrivateFlags |= PFLAG_DRAWN; // force another invalidation with the new orientation 11772 } 11773 invalidate(false); 11774 } else { 11775 damageInParent(); 11776 } 11777 if (isHardwareAccelerated() && invalidateParent && getZ() != 0) { 11778 damageShadowReceiver(); 11779 } 11780 } 11781 11782 /** 11783 * Tells the parent view to damage this view's bounds. 11784 * 11785 * @hide 11786 */ 11787 protected void damageInParent() { 11788 final AttachInfo ai = mAttachInfo; 11789 final ViewParent p = mParent; 11790 if (p != null && ai != null) { 11791 final Rect r = ai.mTmpInvalRect; 11792 r.set(0, 0, mRight - mLeft, mBottom - mTop); 11793 if (mParent instanceof ViewGroup) { 11794 ((ViewGroup) mParent).damageChild(this, r); 11795 } else { 11796 mParent.invalidateChild(this, r); 11797 } 11798 } 11799 } 11800 11801 /** 11802 * Utility method to transform a given Rect by the current matrix of this view. 11803 */ 11804 void transformRect(final Rect rect) { 11805 if (!getMatrix().isIdentity()) { 11806 RectF boundingRect = mAttachInfo.mTmpTransformRect; 11807 boundingRect.set(rect); 11808 getMatrix().mapRect(boundingRect); 11809 rect.set((int) Math.floor(boundingRect.left), 11810 (int) Math.floor(boundingRect.top), 11811 (int) Math.ceil(boundingRect.right), 11812 (int) Math.ceil(boundingRect.bottom)); 11813 } 11814 } 11815 11816 /** 11817 * Used to indicate that the parent of this view should clear its caches. This functionality 11818 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11819 * which is necessary when various parent-managed properties of the view change, such as 11820 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method only 11821 * clears the parent caches and does not causes an invalidate event. 11822 * 11823 * @hide 11824 */ 11825 protected void invalidateParentCaches() { 11826 if (mParent instanceof View) { 11827 ((View) mParent).mPrivateFlags |= PFLAG_INVALIDATED; 11828 } 11829 } 11830 11831 /** 11832 * Used to indicate that the parent of this view should be invalidated. This functionality 11833 * is used to force the parent to rebuild its display list (when hardware-accelerated), 11834 * which is necessary when various parent-managed properties of the view change, such as 11835 * alpha, translationX/Y, scrollX/Y, scaleX/Y, and rotation/X/Y. This method will propagate 11836 * an invalidation event to the parent. 11837 * 11838 * @hide 11839 */ 11840 protected void invalidateParentIfNeeded() { 11841 if (isHardwareAccelerated() && mParent instanceof View) { 11842 ((View) mParent).invalidate(true); 11843 } 11844 } 11845 11846 /** 11847 * @hide 11848 */ 11849 protected void invalidateParentIfNeededAndWasQuickRejected() { 11850 if ((mPrivateFlags2 & PFLAG2_VIEW_QUICK_REJECTED) != 0) { 11851 // View was rejected last time it was drawn by its parent; this may have changed 11852 invalidateParentIfNeeded(); 11853 } 11854 } 11855 11856 /** 11857 * Indicates whether this View is opaque. An opaque View guarantees that it will 11858 * draw all the pixels overlapping its bounds using a fully opaque color. 11859 * 11860 * Subclasses of View should override this method whenever possible to indicate 11861 * whether an instance is opaque. Opaque Views are treated in a special way by 11862 * the View hierarchy, possibly allowing it to perform optimizations during 11863 * invalidate/draw passes. 11864 * 11865 * @return True if this View is guaranteed to be fully opaque, false otherwise. 11866 */ 11867 @ViewDebug.ExportedProperty(category = "drawing") 11868 public boolean isOpaque() { 11869 return (mPrivateFlags & PFLAG_OPAQUE_MASK) == PFLAG_OPAQUE_MASK && 11870 getFinalAlpha() >= 1.0f; 11871 } 11872 11873 /** 11874 * @hide 11875 */ 11876 protected void computeOpaqueFlags() { 11877 // Opaque if: 11878 // - Has a background 11879 // - Background is opaque 11880 // - Doesn't have scrollbars or scrollbars overlay 11881 11882 if (mBackground != null && mBackground.getOpacity() == PixelFormat.OPAQUE) { 11883 mPrivateFlags |= PFLAG_OPAQUE_BACKGROUND; 11884 } else { 11885 mPrivateFlags &= ~PFLAG_OPAQUE_BACKGROUND; 11886 } 11887 11888 final int flags = mViewFlags; 11889 if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) || 11890 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY || 11891 (flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_OUTSIDE_OVERLAY) { 11892 mPrivateFlags |= PFLAG_OPAQUE_SCROLLBARS; 11893 } else { 11894 mPrivateFlags &= ~PFLAG_OPAQUE_SCROLLBARS; 11895 } 11896 } 11897 11898 /** 11899 * @hide 11900 */ 11901 protected boolean hasOpaqueScrollbars() { 11902 return (mPrivateFlags & PFLAG_OPAQUE_SCROLLBARS) == PFLAG_OPAQUE_SCROLLBARS; 11903 } 11904 11905 /** 11906 * @return A handler associated with the thread running the View. This 11907 * handler can be used to pump events in the UI events queue. 11908 */ 11909 public Handler getHandler() { 11910 final AttachInfo attachInfo = mAttachInfo; 11911 if (attachInfo != null) { 11912 return attachInfo.mHandler; 11913 } 11914 return null; 11915 } 11916 11917 /** 11918 * Gets the view root associated with the View. 11919 * @return The view root, or null if none. 11920 * @hide 11921 */ 11922 public ViewRootImpl getViewRootImpl() { 11923 if (mAttachInfo != null) { 11924 return mAttachInfo.mViewRootImpl; 11925 } 11926 return null; 11927 } 11928 11929 /** 11930 * @hide 11931 */ 11932 public HardwareRenderer getHardwareRenderer() { 11933 return mAttachInfo != null ? mAttachInfo.mHardwareRenderer : null; 11934 } 11935 11936 /** 11937 * <p>Causes the Runnable to be added to the message queue. 11938 * The runnable will be run on the user interface thread.</p> 11939 * 11940 * @param action The Runnable that will be executed. 11941 * 11942 * @return Returns true if the Runnable was successfully placed in to the 11943 * message queue. Returns false on failure, usually because the 11944 * looper processing the message queue is exiting. 11945 * 11946 * @see #postDelayed 11947 * @see #removeCallbacks 11948 */ 11949 public boolean post(Runnable action) { 11950 final AttachInfo attachInfo = mAttachInfo; 11951 if (attachInfo != null) { 11952 return attachInfo.mHandler.post(action); 11953 } 11954 // Assume that post will succeed later 11955 ViewRootImpl.getRunQueue().post(action); 11956 return true; 11957 } 11958 11959 /** 11960 * <p>Causes the Runnable to be added to the message queue, to be run 11961 * after the specified amount of time elapses. 11962 * The runnable will be run on the user interface thread.</p> 11963 * 11964 * @param action The Runnable that will be executed. 11965 * @param delayMillis The delay (in milliseconds) until the Runnable 11966 * will be executed. 11967 * 11968 * @return true if the Runnable was successfully placed in to the 11969 * message queue. Returns false on failure, usually because the 11970 * looper processing the message queue is exiting. Note that a 11971 * result of true does not mean the Runnable will be processed -- 11972 * if the looper is quit before the delivery time of the message 11973 * occurs then the message will be dropped. 11974 * 11975 * @see #post 11976 * @see #removeCallbacks 11977 */ 11978 public boolean postDelayed(Runnable action, long delayMillis) { 11979 final AttachInfo attachInfo = mAttachInfo; 11980 if (attachInfo != null) { 11981 return attachInfo.mHandler.postDelayed(action, delayMillis); 11982 } 11983 // Assume that post will succeed later 11984 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 11985 return true; 11986 } 11987 11988 /** 11989 * <p>Causes the Runnable to execute on the next animation time step. 11990 * The runnable will be run on the user interface thread.</p> 11991 * 11992 * @param action The Runnable that will be executed. 11993 * 11994 * @see #postOnAnimationDelayed 11995 * @see #removeCallbacks 11996 */ 11997 public void postOnAnimation(Runnable action) { 11998 final AttachInfo attachInfo = mAttachInfo; 11999 if (attachInfo != null) { 12000 attachInfo.mViewRootImpl.mChoreographer.postCallback( 12001 Choreographer.CALLBACK_ANIMATION, action, null); 12002 } else { 12003 // Assume that post will succeed later 12004 ViewRootImpl.getRunQueue().post(action); 12005 } 12006 } 12007 12008 /** 12009 * <p>Causes the Runnable to execute on the next animation time step, 12010 * after the specified amount of time elapses. 12011 * The runnable will be run on the user interface thread.</p> 12012 * 12013 * @param action The Runnable that will be executed. 12014 * @param delayMillis The delay (in milliseconds) until the Runnable 12015 * will be executed. 12016 * 12017 * @see #postOnAnimation 12018 * @see #removeCallbacks 12019 */ 12020 public void postOnAnimationDelayed(Runnable action, long delayMillis) { 12021 final AttachInfo attachInfo = mAttachInfo; 12022 if (attachInfo != null) { 12023 attachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 12024 Choreographer.CALLBACK_ANIMATION, action, null, delayMillis); 12025 } else { 12026 // Assume that post will succeed later 12027 ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); 12028 } 12029 } 12030 12031 /** 12032 * <p>Removes the specified Runnable from the message queue.</p> 12033 * 12034 * @param action The Runnable to remove from the message handling queue 12035 * 12036 * @return true if this view could ask the Handler to remove the Runnable, 12037 * false otherwise. When the returned value is true, the Runnable 12038 * may or may not have been actually removed from the message queue 12039 * (for instance, if the Runnable was not in the queue already.) 12040 * 12041 * @see #post 12042 * @see #postDelayed 12043 * @see #postOnAnimation 12044 * @see #postOnAnimationDelayed 12045 */ 12046 public boolean removeCallbacks(Runnable action) { 12047 if (action != null) { 12048 final AttachInfo attachInfo = mAttachInfo; 12049 if (attachInfo != null) { 12050 attachInfo.mHandler.removeCallbacks(action); 12051 attachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 12052 Choreographer.CALLBACK_ANIMATION, action, null); 12053 } 12054 // Assume that post will succeed later 12055 ViewRootImpl.getRunQueue().removeCallbacks(action); 12056 } 12057 return true; 12058 } 12059 12060 /** 12061 * <p>Cause an invalidate to happen on a subsequent cycle through the event loop. 12062 * Use this to invalidate the View from a non-UI thread.</p> 12063 * 12064 * <p>This method can be invoked from outside of the UI thread 12065 * only when this View is attached to a window.</p> 12066 * 12067 * @see #invalidate() 12068 * @see #postInvalidateDelayed(long) 12069 */ 12070 public void postInvalidate() { 12071 postInvalidateDelayed(0); 12072 } 12073 12074 /** 12075 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12076 * through the event loop. Use this to invalidate the View from a non-UI thread.</p> 12077 * 12078 * <p>This method can be invoked from outside of the UI thread 12079 * only when this View is attached to a window.</p> 12080 * 12081 * @param left The left coordinate of the rectangle to invalidate. 12082 * @param top The top coordinate of the rectangle to invalidate. 12083 * @param right The right coordinate of the rectangle to invalidate. 12084 * @param bottom The bottom coordinate of the rectangle to invalidate. 12085 * 12086 * @see #invalidate(int, int, int, int) 12087 * @see #invalidate(Rect) 12088 * @see #postInvalidateDelayed(long, int, int, int, int) 12089 */ 12090 public void postInvalidate(int left, int top, int right, int bottom) { 12091 postInvalidateDelayed(0, left, top, right, bottom); 12092 } 12093 12094 /** 12095 * <p>Cause an invalidate to happen on a subsequent cycle through the event 12096 * loop. Waits for the specified amount of time.</p> 12097 * 12098 * <p>This method can be invoked from outside of the UI thread 12099 * only when this View is attached to a window.</p> 12100 * 12101 * @param delayMilliseconds the duration in milliseconds to delay the 12102 * invalidation by 12103 * 12104 * @see #invalidate() 12105 * @see #postInvalidate() 12106 */ 12107 public void postInvalidateDelayed(long delayMilliseconds) { 12108 // We try only with the AttachInfo because there's no point in invalidating 12109 // if we are not attached to our window 12110 final AttachInfo attachInfo = mAttachInfo; 12111 if (attachInfo != null) { 12112 attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); 12113 } 12114 } 12115 12116 /** 12117 * <p>Cause an invalidate of the specified area to happen on a subsequent cycle 12118 * through the event loop. Waits for the specified amount of time.</p> 12119 * 12120 * <p>This method can be invoked from outside of the UI thread 12121 * only when this View is attached to a window.</p> 12122 * 12123 * @param delayMilliseconds the duration in milliseconds to delay the 12124 * invalidation by 12125 * @param left The left coordinate of the rectangle to invalidate. 12126 * @param top The top coordinate of the rectangle to invalidate. 12127 * @param right The right coordinate of the rectangle to invalidate. 12128 * @param bottom The bottom coordinate of the rectangle to invalidate. 12129 * 12130 * @see #invalidate(int, int, int, int) 12131 * @see #invalidate(Rect) 12132 * @see #postInvalidate(int, int, int, int) 12133 */ 12134 public void postInvalidateDelayed(long delayMilliseconds, int left, int top, 12135 int right, int bottom) { 12136 12137 // We try only with the AttachInfo because there's no point in invalidating 12138 // if we are not attached to our window 12139 final AttachInfo attachInfo = mAttachInfo; 12140 if (attachInfo != null) { 12141 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12142 info.target = this; 12143 info.left = left; 12144 info.top = top; 12145 info.right = right; 12146 info.bottom = bottom; 12147 12148 attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); 12149 } 12150 } 12151 12152 /** 12153 * <p>Cause an invalidate to happen on the next animation time step, typically the 12154 * next display frame.</p> 12155 * 12156 * <p>This method can be invoked from outside of the UI thread 12157 * only when this View is attached to a window.</p> 12158 * 12159 * @see #invalidate() 12160 */ 12161 public void postInvalidateOnAnimation() { 12162 // We try only with the AttachInfo because there's no point in invalidating 12163 // if we are not attached to our window 12164 final AttachInfo attachInfo = mAttachInfo; 12165 if (attachInfo != null) { 12166 attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); 12167 } 12168 } 12169 12170 /** 12171 * <p>Cause an invalidate of the specified area to happen on the next animation 12172 * time step, typically the next display frame.</p> 12173 * 12174 * <p>This method can be invoked from outside of the UI thread 12175 * only when this View is attached to a window.</p> 12176 * 12177 * @param left The left coordinate of the rectangle to invalidate. 12178 * @param top The top coordinate of the rectangle to invalidate. 12179 * @param right The right coordinate of the rectangle to invalidate. 12180 * @param bottom The bottom coordinate of the rectangle to invalidate. 12181 * 12182 * @see #invalidate(int, int, int, int) 12183 * @see #invalidate(Rect) 12184 */ 12185 public void postInvalidateOnAnimation(int left, int top, int right, int bottom) { 12186 // We try only with the AttachInfo because there's no point in invalidating 12187 // if we are not attached to our window 12188 final AttachInfo attachInfo = mAttachInfo; 12189 if (attachInfo != null) { 12190 final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.obtain(); 12191 info.target = this; 12192 info.left = left; 12193 info.top = top; 12194 info.right = right; 12195 info.bottom = bottom; 12196 12197 attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); 12198 } 12199 } 12200 12201 /** 12202 * Post a callback to send a {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} event. 12203 * This event is sent at most once every 12204 * {@link ViewConfiguration#getSendRecurringAccessibilityEventsInterval()}. 12205 */ 12206 private void postSendViewScrolledAccessibilityEventCallback() { 12207 if (mSendViewScrolledAccessibilityEvent == null) { 12208 mSendViewScrolledAccessibilityEvent = new SendViewScrolledAccessibilityEvent(); 12209 } 12210 if (!mSendViewScrolledAccessibilityEvent.mIsPending) { 12211 mSendViewScrolledAccessibilityEvent.mIsPending = true; 12212 postDelayed(mSendViewScrolledAccessibilityEvent, 12213 ViewConfiguration.getSendRecurringAccessibilityEventsInterval()); 12214 } 12215 } 12216 12217 /** 12218 * Called by a parent to request that a child update its values for mScrollX 12219 * and mScrollY if necessary. This will typically be done if the child is 12220 * animating a scroll using a {@link android.widget.Scroller Scroller} 12221 * object. 12222 */ 12223 public void computeScroll() { 12224 } 12225 12226 /** 12227 * <p>Indicate whether the horizontal edges are faded when the view is 12228 * scrolled horizontally.</p> 12229 * 12230 * @return true if the horizontal edges should are faded on scroll, false 12231 * otherwise 12232 * 12233 * @see #setHorizontalFadingEdgeEnabled(boolean) 12234 * 12235 * @attr ref android.R.styleable#View_requiresFadingEdge 12236 */ 12237 public boolean isHorizontalFadingEdgeEnabled() { 12238 return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL; 12239 } 12240 12241 /** 12242 * <p>Define whether the horizontal edges should be faded when this view 12243 * is scrolled horizontally.</p> 12244 * 12245 * @param horizontalFadingEdgeEnabled true if the horizontal edges should 12246 * be faded when the view is scrolled 12247 * horizontally 12248 * 12249 * @see #isHorizontalFadingEdgeEnabled() 12250 * 12251 * @attr ref android.R.styleable#View_requiresFadingEdge 12252 */ 12253 public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) { 12254 if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) { 12255 if (horizontalFadingEdgeEnabled) { 12256 initScrollCache(); 12257 } 12258 12259 mViewFlags ^= FADING_EDGE_HORIZONTAL; 12260 } 12261 } 12262 12263 /** 12264 * <p>Indicate whether the vertical edges are faded when the view is 12265 * scrolled horizontally.</p> 12266 * 12267 * @return true if the vertical edges should are faded on scroll, false 12268 * otherwise 12269 * 12270 * @see #setVerticalFadingEdgeEnabled(boolean) 12271 * 12272 * @attr ref android.R.styleable#View_requiresFadingEdge 12273 */ 12274 public boolean isVerticalFadingEdgeEnabled() { 12275 return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL; 12276 } 12277 12278 /** 12279 * <p>Define whether the vertical edges should be faded when this view 12280 * is scrolled vertically.</p> 12281 * 12282 * @param verticalFadingEdgeEnabled true if the vertical edges should 12283 * be faded when the view is scrolled 12284 * vertically 12285 * 12286 * @see #isVerticalFadingEdgeEnabled() 12287 * 12288 * @attr ref android.R.styleable#View_requiresFadingEdge 12289 */ 12290 public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) { 12291 if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) { 12292 if (verticalFadingEdgeEnabled) { 12293 initScrollCache(); 12294 } 12295 12296 mViewFlags ^= FADING_EDGE_VERTICAL; 12297 } 12298 } 12299 12300 /** 12301 * Returns the strength, or intensity, of the top faded edge. The strength is 12302 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12303 * returns 0.0 or 1.0 but no value in between. 12304 * 12305 * Subclasses should override this method to provide a smoother fade transition 12306 * when scrolling occurs. 12307 * 12308 * @return the intensity of the top fade as a float between 0.0f and 1.0f 12309 */ 12310 protected float getTopFadingEdgeStrength() { 12311 return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f; 12312 } 12313 12314 /** 12315 * Returns the strength, or intensity, of the bottom faded edge. The strength is 12316 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12317 * returns 0.0 or 1.0 but no value in between. 12318 * 12319 * Subclasses should override this method to provide a smoother fade transition 12320 * when scrolling occurs. 12321 * 12322 * @return the intensity of the bottom fade as a float between 0.0f and 1.0f 12323 */ 12324 protected float getBottomFadingEdgeStrength() { 12325 return computeVerticalScrollOffset() + computeVerticalScrollExtent() < 12326 computeVerticalScrollRange() ? 1.0f : 0.0f; 12327 } 12328 12329 /** 12330 * Returns the strength, or intensity, of the left faded edge. The strength is 12331 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12332 * returns 0.0 or 1.0 but no value in between. 12333 * 12334 * Subclasses should override this method to provide a smoother fade transition 12335 * when scrolling occurs. 12336 * 12337 * @return the intensity of the left fade as a float between 0.0f and 1.0f 12338 */ 12339 protected float getLeftFadingEdgeStrength() { 12340 return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f; 12341 } 12342 12343 /** 12344 * Returns the strength, or intensity, of the right faded edge. The strength is 12345 * a value between 0.0 (no fade) and 1.0 (full fade). The default implementation 12346 * returns 0.0 or 1.0 but no value in between. 12347 * 12348 * Subclasses should override this method to provide a smoother fade transition 12349 * when scrolling occurs. 12350 * 12351 * @return the intensity of the right fade as a float between 0.0f and 1.0f 12352 */ 12353 protected float getRightFadingEdgeStrength() { 12354 return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() < 12355 computeHorizontalScrollRange() ? 1.0f : 0.0f; 12356 } 12357 12358 /** 12359 * <p>Indicate whether the horizontal scrollbar should be drawn or not. The 12360 * scrollbar is not drawn by default.</p> 12361 * 12362 * @return true if the horizontal scrollbar should be painted, false 12363 * otherwise 12364 * 12365 * @see #setHorizontalScrollBarEnabled(boolean) 12366 */ 12367 public boolean isHorizontalScrollBarEnabled() { 12368 return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12369 } 12370 12371 /** 12372 * <p>Define whether the horizontal scrollbar should be drawn or not. The 12373 * scrollbar is not drawn by default.</p> 12374 * 12375 * @param horizontalScrollBarEnabled true if the horizontal scrollbar should 12376 * be painted 12377 * 12378 * @see #isHorizontalScrollBarEnabled() 12379 */ 12380 public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) { 12381 if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { 12382 mViewFlags ^= SCROLLBARS_HORIZONTAL; 12383 computeOpaqueFlags(); 12384 resolvePadding(); 12385 } 12386 } 12387 12388 /** 12389 * <p>Indicate whether the vertical scrollbar should be drawn or not. The 12390 * scrollbar is not drawn by default.</p> 12391 * 12392 * @return true if the vertical scrollbar should be painted, false 12393 * otherwise 12394 * 12395 * @see #setVerticalScrollBarEnabled(boolean) 12396 */ 12397 public boolean isVerticalScrollBarEnabled() { 12398 return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; 12399 } 12400 12401 /** 12402 * <p>Define whether the vertical scrollbar should be drawn or not. The 12403 * scrollbar is not drawn by default.</p> 12404 * 12405 * @param verticalScrollBarEnabled true if the vertical scrollbar should 12406 * be painted 12407 * 12408 * @see #isVerticalScrollBarEnabled() 12409 */ 12410 public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) { 12411 if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { 12412 mViewFlags ^= SCROLLBARS_VERTICAL; 12413 computeOpaqueFlags(); 12414 resolvePadding(); 12415 } 12416 } 12417 12418 /** 12419 * @hide 12420 */ 12421 protected void recomputePadding() { 12422 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 12423 } 12424 12425 /** 12426 * Define whether scrollbars will fade when the view is not scrolling. 12427 * 12428 * @param fadeScrollbars wheter to enable fading 12429 * 12430 * @attr ref android.R.styleable#View_fadeScrollbars 12431 */ 12432 public void setScrollbarFadingEnabled(boolean fadeScrollbars) { 12433 initScrollCache(); 12434 final ScrollabilityCache scrollabilityCache = mScrollCache; 12435 scrollabilityCache.fadeScrollBars = fadeScrollbars; 12436 if (fadeScrollbars) { 12437 scrollabilityCache.state = ScrollabilityCache.OFF; 12438 } else { 12439 scrollabilityCache.state = ScrollabilityCache.ON; 12440 } 12441 } 12442 12443 /** 12444 * 12445 * Returns true if scrollbars will fade when this view is not scrolling 12446 * 12447 * @return true if scrollbar fading is enabled 12448 * 12449 * @attr ref android.R.styleable#View_fadeScrollbars 12450 */ 12451 public boolean isScrollbarFadingEnabled() { 12452 return mScrollCache != null && mScrollCache.fadeScrollBars; 12453 } 12454 12455 /** 12456 * 12457 * Returns the delay before scrollbars fade. 12458 * 12459 * @return the delay before scrollbars fade 12460 * 12461 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12462 */ 12463 public int getScrollBarDefaultDelayBeforeFade() { 12464 return mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : 12465 mScrollCache.scrollBarDefaultDelayBeforeFade; 12466 } 12467 12468 /** 12469 * Define the delay before scrollbars fade. 12470 * 12471 * @param scrollBarDefaultDelayBeforeFade - the delay before scrollbars fade 12472 * 12473 * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade 12474 */ 12475 public void setScrollBarDefaultDelayBeforeFade(int scrollBarDefaultDelayBeforeFade) { 12476 getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; 12477 } 12478 12479 /** 12480 * 12481 * Returns the scrollbar fade duration. 12482 * 12483 * @return the scrollbar fade duration 12484 * 12485 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12486 */ 12487 public int getScrollBarFadeDuration() { 12488 return mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : 12489 mScrollCache.scrollBarFadeDuration; 12490 } 12491 12492 /** 12493 * Define the scrollbar fade duration. 12494 * 12495 * @param scrollBarFadeDuration - the scrollbar fade duration 12496 * 12497 * @attr ref android.R.styleable#View_scrollbarFadeDuration 12498 */ 12499 public void setScrollBarFadeDuration(int scrollBarFadeDuration) { 12500 getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; 12501 } 12502 12503 /** 12504 * 12505 * Returns the scrollbar size. 12506 * 12507 * @return the scrollbar size 12508 * 12509 * @attr ref android.R.styleable#View_scrollbarSize 12510 */ 12511 public int getScrollBarSize() { 12512 return mScrollCache == null ? ViewConfiguration.get(mContext).getScaledScrollBarSize() : 12513 mScrollCache.scrollBarSize; 12514 } 12515 12516 /** 12517 * Define the scrollbar size. 12518 * 12519 * @param scrollBarSize - the scrollbar size 12520 * 12521 * @attr ref android.R.styleable#View_scrollbarSize 12522 */ 12523 public void setScrollBarSize(int scrollBarSize) { 12524 getScrollCache().scrollBarSize = scrollBarSize; 12525 } 12526 12527 /** 12528 * <p>Specify the style of the scrollbars. The scrollbars can be overlaid or 12529 * inset. When inset, they add to the padding of the view. And the scrollbars 12530 * can be drawn inside the padding area or on the edge of the view. For example, 12531 * if a view has a background drawable and you want to draw the scrollbars 12532 * inside the padding specified by the drawable, you can use 12533 * SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to 12534 * appear at the edge of the view, ignoring the padding, then you can use 12535 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p> 12536 * @param style the style of the scrollbars. Should be one of 12537 * SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET, 12538 * SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET. 12539 * @see #SCROLLBARS_INSIDE_OVERLAY 12540 * @see #SCROLLBARS_INSIDE_INSET 12541 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12542 * @see #SCROLLBARS_OUTSIDE_INSET 12543 * 12544 * @attr ref android.R.styleable#View_scrollbarStyle 12545 */ 12546 public void setScrollBarStyle(@ScrollBarStyle int style) { 12547 if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) { 12548 mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK); 12549 computeOpaqueFlags(); 12550 resolvePadding(); 12551 } 12552 } 12553 12554 /** 12555 * <p>Returns the current scrollbar style.</p> 12556 * @return the current scrollbar style 12557 * @see #SCROLLBARS_INSIDE_OVERLAY 12558 * @see #SCROLLBARS_INSIDE_INSET 12559 * @see #SCROLLBARS_OUTSIDE_OVERLAY 12560 * @see #SCROLLBARS_OUTSIDE_INSET 12561 * 12562 * @attr ref android.R.styleable#View_scrollbarStyle 12563 */ 12564 @ViewDebug.ExportedProperty(mapping = { 12565 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_OVERLAY, to = "INSIDE_OVERLAY"), 12566 @ViewDebug.IntToString(from = SCROLLBARS_INSIDE_INSET, to = "INSIDE_INSET"), 12567 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_OVERLAY, to = "OUTSIDE_OVERLAY"), 12568 @ViewDebug.IntToString(from = SCROLLBARS_OUTSIDE_INSET, to = "OUTSIDE_INSET") 12569 }) 12570 @ScrollBarStyle 12571 public int getScrollBarStyle() { 12572 return mViewFlags & SCROLLBARS_STYLE_MASK; 12573 } 12574 12575 /** 12576 * <p>Compute the horizontal range that the horizontal scrollbar 12577 * represents.</p> 12578 * 12579 * <p>The range is expressed in arbitrary units that must be the same as the 12580 * units used by {@link #computeHorizontalScrollExtent()} and 12581 * {@link #computeHorizontalScrollOffset()}.</p> 12582 * 12583 * <p>The default range is the drawing width of this view.</p> 12584 * 12585 * @return the total horizontal range represented by the horizontal 12586 * scrollbar 12587 * 12588 * @see #computeHorizontalScrollExtent() 12589 * @see #computeHorizontalScrollOffset() 12590 * @see android.widget.ScrollBarDrawable 12591 */ 12592 protected int computeHorizontalScrollRange() { 12593 return getWidth(); 12594 } 12595 12596 /** 12597 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb 12598 * within the horizontal range. This value is used to compute the position 12599 * of the thumb within the scrollbar's track.</p> 12600 * 12601 * <p>The range is expressed in arbitrary units that must be the same as the 12602 * units used by {@link #computeHorizontalScrollRange()} and 12603 * {@link #computeHorizontalScrollExtent()}.</p> 12604 * 12605 * <p>The default offset is the scroll offset of this view.</p> 12606 * 12607 * @return the horizontal offset of the scrollbar's thumb 12608 * 12609 * @see #computeHorizontalScrollRange() 12610 * @see #computeHorizontalScrollExtent() 12611 * @see android.widget.ScrollBarDrawable 12612 */ 12613 protected int computeHorizontalScrollOffset() { 12614 return mScrollX; 12615 } 12616 12617 /** 12618 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb 12619 * within the horizontal range. This value is used to compute the length 12620 * of the thumb within the scrollbar's track.</p> 12621 * 12622 * <p>The range is expressed in arbitrary units that must be the same as the 12623 * units used by {@link #computeHorizontalScrollRange()} and 12624 * {@link #computeHorizontalScrollOffset()}.</p> 12625 * 12626 * <p>The default extent is the drawing width of this view.</p> 12627 * 12628 * @return the horizontal extent of the scrollbar's thumb 12629 * 12630 * @see #computeHorizontalScrollRange() 12631 * @see #computeHorizontalScrollOffset() 12632 * @see android.widget.ScrollBarDrawable 12633 */ 12634 protected int computeHorizontalScrollExtent() { 12635 return getWidth(); 12636 } 12637 12638 /** 12639 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 12640 * 12641 * <p>The range is expressed in arbitrary units that must be the same as the 12642 * units used by {@link #computeVerticalScrollExtent()} and 12643 * {@link #computeVerticalScrollOffset()}.</p> 12644 * 12645 * @return the total vertical range represented by the vertical scrollbar 12646 * 12647 * <p>The default range is the drawing height of this view.</p> 12648 * 12649 * @see #computeVerticalScrollExtent() 12650 * @see #computeVerticalScrollOffset() 12651 * @see android.widget.ScrollBarDrawable 12652 */ 12653 protected int computeVerticalScrollRange() { 12654 return getHeight(); 12655 } 12656 12657 /** 12658 * <p>Compute the vertical offset of the vertical scrollbar's thumb 12659 * within the horizontal range. This value is used to compute the position 12660 * of the thumb within the scrollbar's track.</p> 12661 * 12662 * <p>The range is expressed in arbitrary units that must be the same as the 12663 * units used by {@link #computeVerticalScrollRange()} and 12664 * {@link #computeVerticalScrollExtent()}.</p> 12665 * 12666 * <p>The default offset is the scroll offset of this view.</p> 12667 * 12668 * @return the vertical offset of the scrollbar's thumb 12669 * 12670 * @see #computeVerticalScrollRange() 12671 * @see #computeVerticalScrollExtent() 12672 * @see android.widget.ScrollBarDrawable 12673 */ 12674 protected int computeVerticalScrollOffset() { 12675 return mScrollY; 12676 } 12677 12678 /** 12679 * <p>Compute the vertical extent of the vertical scrollbar's thumb 12680 * within the vertical range. This value is used to compute the length 12681 * of the thumb within the scrollbar's track.</p> 12682 * 12683 * <p>The range is expressed in arbitrary units that must be the same as the 12684 * units used by {@link #computeVerticalScrollRange()} and 12685 * {@link #computeVerticalScrollOffset()}.</p> 12686 * 12687 * <p>The default extent is the drawing height of this view.</p> 12688 * 12689 * @return the vertical extent of the scrollbar's thumb 12690 * 12691 * @see #computeVerticalScrollRange() 12692 * @see #computeVerticalScrollOffset() 12693 * @see android.widget.ScrollBarDrawable 12694 */ 12695 protected int computeVerticalScrollExtent() { 12696 return getHeight(); 12697 } 12698 12699 /** 12700 * Check if this view can be scrolled horizontally in a certain direction. 12701 * 12702 * @param direction Negative to check scrolling left, positive to check scrolling right. 12703 * @return true if this view can be scrolled in the specified direction, false otherwise. 12704 */ 12705 public boolean canScrollHorizontally(int direction) { 12706 final int offset = computeHorizontalScrollOffset(); 12707 final int range = computeHorizontalScrollRange() - computeHorizontalScrollExtent(); 12708 if (range == 0) return false; 12709 if (direction < 0) { 12710 return offset > 0; 12711 } else { 12712 return offset < range - 1; 12713 } 12714 } 12715 12716 /** 12717 * Check if this view can be scrolled vertically in a certain direction. 12718 * 12719 * @param direction Negative to check scrolling up, positive to check scrolling down. 12720 * @return true if this view can be scrolled in the specified direction, false otherwise. 12721 */ 12722 public boolean canScrollVertically(int direction) { 12723 final int offset = computeVerticalScrollOffset(); 12724 final int range = computeVerticalScrollRange() - computeVerticalScrollExtent(); 12725 if (range == 0) return false; 12726 if (direction < 0) { 12727 return offset > 0; 12728 } else { 12729 return offset < range - 1; 12730 } 12731 } 12732 12733 /** 12734 * <p>Request the drawing of the horizontal and the vertical scrollbar. The 12735 * scrollbars are painted only if they have been awakened first.</p> 12736 * 12737 * @param canvas the canvas on which to draw the scrollbars 12738 * 12739 * @see #awakenScrollBars(int) 12740 */ 12741 protected final void onDrawScrollBars(Canvas canvas) { 12742 // scrollbars are drawn only when the animation is running 12743 final ScrollabilityCache cache = mScrollCache; 12744 if (cache != null) { 12745 12746 int state = cache.state; 12747 12748 if (state == ScrollabilityCache.OFF) { 12749 return; 12750 } 12751 12752 boolean invalidate = false; 12753 12754 if (state == ScrollabilityCache.FADING) { 12755 // We're fading -- get our fade interpolation 12756 if (cache.interpolatorValues == null) { 12757 cache.interpolatorValues = new float[1]; 12758 } 12759 12760 float[] values = cache.interpolatorValues; 12761 12762 // Stops the animation if we're done 12763 if (cache.scrollBarInterpolator.timeToValues(values) == 12764 Interpolator.Result.FREEZE_END) { 12765 cache.state = ScrollabilityCache.OFF; 12766 } else { 12767 cache.scrollBar.setAlpha(Math.round(values[0])); 12768 } 12769 12770 // This will make the scroll bars inval themselves after 12771 // drawing. We only want this when we're fading so that 12772 // we prevent excessive redraws 12773 invalidate = true; 12774 } else { 12775 // We're just on -- but we may have been fading before so 12776 // reset alpha 12777 cache.scrollBar.setAlpha(255); 12778 } 12779 12780 12781 final int viewFlags = mViewFlags; 12782 12783 final boolean drawHorizontalScrollBar = 12784 (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; 12785 final boolean drawVerticalScrollBar = 12786 (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL 12787 && !isVerticalScrollBarHidden(); 12788 12789 if (drawVerticalScrollBar || drawHorizontalScrollBar) { 12790 final int width = mRight - mLeft; 12791 final int height = mBottom - mTop; 12792 12793 final ScrollBarDrawable scrollBar = cache.scrollBar; 12794 12795 final int scrollX = mScrollX; 12796 final int scrollY = mScrollY; 12797 final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; 12798 12799 int left; 12800 int top; 12801 int right; 12802 int bottom; 12803 12804 if (drawHorizontalScrollBar) { 12805 int size = scrollBar.getSize(false); 12806 if (size <= 0) { 12807 size = cache.scrollBarSize; 12808 } 12809 12810 scrollBar.setParameters(computeHorizontalScrollRange(), 12811 computeHorizontalScrollOffset(), 12812 computeHorizontalScrollExtent(), false); 12813 final int verticalScrollBarGap = drawVerticalScrollBar ? 12814 getVerticalScrollbarWidth() : 0; 12815 top = scrollY + height - size - (mUserPaddingBottom & inside); 12816 left = scrollX + (mPaddingLeft & inside); 12817 right = scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap; 12818 bottom = top + size; 12819 onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); 12820 if (invalidate) { 12821 invalidate(left, top, right, bottom); 12822 } 12823 } 12824 12825 if (drawVerticalScrollBar) { 12826 int size = scrollBar.getSize(true); 12827 if (size <= 0) { 12828 size = cache.scrollBarSize; 12829 } 12830 12831 scrollBar.setParameters(computeVerticalScrollRange(), 12832 computeVerticalScrollOffset(), 12833 computeVerticalScrollExtent(), true); 12834 int verticalScrollbarPosition = mVerticalScrollbarPosition; 12835 if (verticalScrollbarPosition == SCROLLBAR_POSITION_DEFAULT) { 12836 verticalScrollbarPosition = isLayoutRtl() ? 12837 SCROLLBAR_POSITION_LEFT : SCROLLBAR_POSITION_RIGHT; 12838 } 12839 switch (verticalScrollbarPosition) { 12840 default: 12841 case SCROLLBAR_POSITION_RIGHT: 12842 left = scrollX + width - size - (mUserPaddingRight & inside); 12843 break; 12844 case SCROLLBAR_POSITION_LEFT: 12845 left = scrollX + (mUserPaddingLeft & inside); 12846 break; 12847 } 12848 top = scrollY + (mPaddingTop & inside); 12849 right = left + size; 12850 bottom = scrollY + height - (mUserPaddingBottom & inside); 12851 onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); 12852 if (invalidate) { 12853 invalidate(left, top, right, bottom); 12854 } 12855 } 12856 } 12857 } 12858 } 12859 12860 /** 12861 * Override this if the vertical scrollbar needs to be hidden in a subclass, like when 12862 * FastScroller is visible. 12863 * @return whether to temporarily hide the vertical scrollbar 12864 * @hide 12865 */ 12866 protected boolean isVerticalScrollBarHidden() { 12867 return false; 12868 } 12869 12870 /** 12871 * <p>Draw the horizontal scrollbar if 12872 * {@link #isHorizontalScrollBarEnabled()} returns true.</p> 12873 * 12874 * @param canvas the canvas on which to draw the scrollbar 12875 * @param scrollBar the scrollbar's drawable 12876 * 12877 * @see #isHorizontalScrollBarEnabled() 12878 * @see #computeHorizontalScrollRange() 12879 * @see #computeHorizontalScrollExtent() 12880 * @see #computeHorizontalScrollOffset() 12881 * @see android.widget.ScrollBarDrawable 12882 * @hide 12883 */ 12884 protected void onDrawHorizontalScrollBar(Canvas canvas, Drawable scrollBar, 12885 int l, int t, int r, int b) { 12886 scrollBar.setBounds(l, t, r, b); 12887 scrollBar.draw(canvas); 12888 } 12889 12890 /** 12891 * <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()} 12892 * returns true.</p> 12893 * 12894 * @param canvas the canvas on which to draw the scrollbar 12895 * @param scrollBar the scrollbar's drawable 12896 * 12897 * @see #isVerticalScrollBarEnabled() 12898 * @see #computeVerticalScrollRange() 12899 * @see #computeVerticalScrollExtent() 12900 * @see #computeVerticalScrollOffset() 12901 * @see android.widget.ScrollBarDrawable 12902 * @hide 12903 */ 12904 protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, 12905 int l, int t, int r, int b) { 12906 scrollBar.setBounds(l, t, r, b); 12907 scrollBar.draw(canvas); 12908 } 12909 12910 /** 12911 * Implement this to do your drawing. 12912 * 12913 * @param canvas the canvas on which the background will be drawn 12914 */ 12915 protected void onDraw(Canvas canvas) { 12916 } 12917 12918 /* 12919 * Caller is responsible for calling requestLayout if necessary. 12920 * (This allows addViewInLayout to not request a new layout.) 12921 */ 12922 void assignParent(ViewParent parent) { 12923 if (mParent == null) { 12924 mParent = parent; 12925 } else if (parent == null) { 12926 mParent = null; 12927 } else { 12928 throw new RuntimeException("view " + this + " being added, but" 12929 + " it already has a parent"); 12930 } 12931 } 12932 12933 /** 12934 * This is called when the view is attached to a window. At this point it 12935 * has a Surface and will start drawing. Note that this function is 12936 * guaranteed to be called before {@link #onDraw(android.graphics.Canvas)}, 12937 * however it may be called any time before the first onDraw -- including 12938 * before or after {@link #onMeasure(int, int)}. 12939 * 12940 * @see #onDetachedFromWindow() 12941 */ 12942 protected void onAttachedToWindow() { 12943 if ((mPrivateFlags & PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { 12944 mParent.requestTransparentRegion(this); 12945 } 12946 12947 if ((mPrivateFlags & PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { 12948 initialAwakenScrollBars(); 12949 mPrivateFlags &= ~PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; 12950 } 12951 12952 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 12953 12954 jumpDrawablesToCurrentState(); 12955 12956 resetSubtreeAccessibilityStateChanged(); 12957 12958 // rebuild, since Outline not maintained while View is detached 12959 rebuildOutline(); 12960 12961 if (isFocused()) { 12962 InputMethodManager imm = InputMethodManager.peekInstance(); 12963 imm.focusIn(this); 12964 } 12965 } 12966 12967 /** 12968 * Resolve all RTL related properties. 12969 * 12970 * @return true if resolution of RTL properties has been done 12971 * 12972 * @hide 12973 */ 12974 public boolean resolveRtlPropertiesIfNeeded() { 12975 if (!needRtlPropertiesResolution()) return false; 12976 12977 // Order is important here: LayoutDirection MUST be resolved first 12978 if (!isLayoutDirectionResolved()) { 12979 resolveLayoutDirection(); 12980 resolveLayoutParams(); 12981 } 12982 // ... then we can resolve the others properties depending on the resolved LayoutDirection. 12983 if (!isTextDirectionResolved()) { 12984 resolveTextDirection(); 12985 } 12986 if (!isTextAlignmentResolved()) { 12987 resolveTextAlignment(); 12988 } 12989 // Should resolve Drawables before Padding because we need the layout direction of the 12990 // Drawable to correctly resolve Padding. 12991 if (!isDrawablesResolved()) { 12992 resolveDrawables(); 12993 } 12994 if (!isPaddingResolved()) { 12995 resolvePadding(); 12996 } 12997 onRtlPropertiesChanged(getLayoutDirection()); 12998 return true; 12999 } 13000 13001 /** 13002 * Reset resolution of all RTL related properties. 13003 * 13004 * @hide 13005 */ 13006 public void resetRtlProperties() { 13007 resetResolvedLayoutDirection(); 13008 resetResolvedTextDirection(); 13009 resetResolvedTextAlignment(); 13010 resetResolvedPadding(); 13011 resetResolvedDrawables(); 13012 } 13013 13014 /** 13015 * @see #onScreenStateChanged(int) 13016 */ 13017 void dispatchScreenStateChanged(int screenState) { 13018 onScreenStateChanged(screenState); 13019 } 13020 13021 /** 13022 * This method is called whenever the state of the screen this view is 13023 * attached to changes. A state change will usually occurs when the screen 13024 * turns on or off (whether it happens automatically or the user does it 13025 * manually.) 13026 * 13027 * @param screenState The new state of the screen. Can be either 13028 * {@link #SCREEN_STATE_ON} or {@link #SCREEN_STATE_OFF} 13029 */ 13030 public void onScreenStateChanged(int screenState) { 13031 } 13032 13033 /** 13034 * Return true if the application tag in the AndroidManifest has set "supportRtl" to true 13035 */ 13036 private boolean hasRtlSupport() { 13037 return mContext.getApplicationInfo().hasRtlSupport(); 13038 } 13039 13040 /** 13041 * Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or 13042 * RTL not supported) 13043 */ 13044 private boolean isRtlCompatibilityMode() { 13045 final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion; 13046 return targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport(); 13047 } 13048 13049 /** 13050 * @return true if RTL properties need resolution. 13051 * 13052 */ 13053 private boolean needRtlPropertiesResolution() { 13054 return (mPrivateFlags2 & ALL_RTL_PROPERTIES_RESOLVED) != ALL_RTL_PROPERTIES_RESOLVED; 13055 } 13056 13057 /** 13058 * Called when any RTL property (layout direction or text direction or text alignment) has 13059 * been changed. 13060 * 13061 * Subclasses need to override this method to take care of cached information that depends on the 13062 * resolved layout direction, or to inform child views that inherit their layout direction. 13063 * 13064 * The default implementation does nothing. 13065 * 13066 * @param layoutDirection the direction of the layout 13067 * 13068 * @see #LAYOUT_DIRECTION_LTR 13069 * @see #LAYOUT_DIRECTION_RTL 13070 */ 13071 public void onRtlPropertiesChanged(@ResolvedLayoutDir int layoutDirection) { 13072 } 13073 13074 /** 13075 * Resolve and cache the layout direction. LTR is set initially. This is implicitly supposing 13076 * that the parent directionality can and will be resolved before its children. 13077 * 13078 * @return true if resolution has been done, false otherwise. 13079 * 13080 * @hide 13081 */ 13082 public boolean resolveLayoutDirection() { 13083 // Clear any previous layout direction resolution 13084 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13085 13086 if (hasRtlSupport()) { 13087 // Set resolved depending on layout direction 13088 switch ((mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_MASK) >> 13089 PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT) { 13090 case LAYOUT_DIRECTION_INHERIT: 13091 // We cannot resolve yet. LTR is by default and let the resolution happen again 13092 // later to get the correct resolved value 13093 if (!canResolveLayoutDirection()) return false; 13094 13095 // Parent has not yet resolved, LTR is still the default 13096 try { 13097 if (!mParent.isLayoutDirectionResolved()) return false; 13098 13099 if (mParent.getLayoutDirection() == LAYOUT_DIRECTION_RTL) { 13100 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13101 } 13102 } catch (AbstractMethodError e) { 13103 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13104 " does not fully implement ViewParent", e); 13105 } 13106 break; 13107 case LAYOUT_DIRECTION_RTL: 13108 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13109 break; 13110 case LAYOUT_DIRECTION_LOCALE: 13111 if((LAYOUT_DIRECTION_RTL == 13112 TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()))) { 13113 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED_RTL; 13114 } 13115 break; 13116 default: 13117 // Nothing to do, LTR by default 13118 } 13119 } 13120 13121 // Set to resolved 13122 mPrivateFlags2 |= PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13123 return true; 13124 } 13125 13126 /** 13127 * Check if layout direction resolution can be done. 13128 * 13129 * @return true if layout direction resolution can be done otherwise return false. 13130 */ 13131 public boolean canResolveLayoutDirection() { 13132 switch (getRawLayoutDirection()) { 13133 case LAYOUT_DIRECTION_INHERIT: 13134 if (mParent != null) { 13135 try { 13136 return mParent.canResolveLayoutDirection(); 13137 } catch (AbstractMethodError e) { 13138 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 13139 " does not fully implement ViewParent", e); 13140 } 13141 } 13142 return false; 13143 13144 default: 13145 return true; 13146 } 13147 } 13148 13149 /** 13150 * Reset the resolved layout direction. Layout direction will be resolved during a call to 13151 * {@link #onMeasure(int, int)}. 13152 * 13153 * @hide 13154 */ 13155 public void resetResolvedLayoutDirection() { 13156 // Reset the current resolved bits 13157 mPrivateFlags2 &= ~PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK; 13158 } 13159 13160 /** 13161 * @return true if the layout direction is inherited. 13162 * 13163 * @hide 13164 */ 13165 public boolean isLayoutDirectionInherited() { 13166 return (getRawLayoutDirection() == LAYOUT_DIRECTION_INHERIT); 13167 } 13168 13169 /** 13170 * @return true if layout direction has been resolved. 13171 */ 13172 public boolean isLayoutDirectionResolved() { 13173 return (mPrivateFlags2 & PFLAG2_LAYOUT_DIRECTION_RESOLVED) == PFLAG2_LAYOUT_DIRECTION_RESOLVED; 13174 } 13175 13176 /** 13177 * Return if padding has been resolved 13178 * 13179 * @hide 13180 */ 13181 boolean isPaddingResolved() { 13182 return (mPrivateFlags2 & PFLAG2_PADDING_RESOLVED) == PFLAG2_PADDING_RESOLVED; 13183 } 13184 13185 /** 13186 * Resolves padding depending on layout direction, if applicable, and 13187 * recomputes internal padding values to adjust for scroll bars. 13188 * 13189 * @hide 13190 */ 13191 public void resolvePadding() { 13192 final int resolvedLayoutDirection = getLayoutDirection(); 13193 13194 if (!isRtlCompatibilityMode()) { 13195 // Post Jelly Bean MR1 case: we need to take the resolved layout direction into account. 13196 // If start / end padding are defined, they will be resolved (hence overriding) to 13197 // left / right or right / left depending on the resolved layout direction. 13198 // If start / end padding are not defined, use the left / right ones. 13199 if (mBackground != null && (!mLeftPaddingDefined || !mRightPaddingDefined)) { 13200 Rect padding = sThreadLocal.get(); 13201 if (padding == null) { 13202 padding = new Rect(); 13203 sThreadLocal.set(padding); 13204 } 13205 mBackground.getPadding(padding); 13206 if (!mLeftPaddingDefined) { 13207 mUserPaddingLeftInitial = padding.left; 13208 } 13209 if (!mRightPaddingDefined) { 13210 mUserPaddingRightInitial = padding.right; 13211 } 13212 } 13213 switch (resolvedLayoutDirection) { 13214 case LAYOUT_DIRECTION_RTL: 13215 if (mUserPaddingStart != UNDEFINED_PADDING) { 13216 mUserPaddingRight = mUserPaddingStart; 13217 } else { 13218 mUserPaddingRight = mUserPaddingRightInitial; 13219 } 13220 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13221 mUserPaddingLeft = mUserPaddingEnd; 13222 } else { 13223 mUserPaddingLeft = mUserPaddingLeftInitial; 13224 } 13225 break; 13226 case LAYOUT_DIRECTION_LTR: 13227 default: 13228 if (mUserPaddingStart != UNDEFINED_PADDING) { 13229 mUserPaddingLeft = mUserPaddingStart; 13230 } else { 13231 mUserPaddingLeft = mUserPaddingLeftInitial; 13232 } 13233 if (mUserPaddingEnd != UNDEFINED_PADDING) { 13234 mUserPaddingRight = mUserPaddingEnd; 13235 } else { 13236 mUserPaddingRight = mUserPaddingRightInitial; 13237 } 13238 } 13239 13240 mUserPaddingBottom = (mUserPaddingBottom >= 0) ? mUserPaddingBottom : mPaddingBottom; 13241 } 13242 13243 internalSetPadding(mUserPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom); 13244 onRtlPropertiesChanged(resolvedLayoutDirection); 13245 13246 mPrivateFlags2 |= PFLAG2_PADDING_RESOLVED; 13247 } 13248 13249 /** 13250 * Reset the resolved layout direction. 13251 * 13252 * @hide 13253 */ 13254 public void resetResolvedPadding() { 13255 mPrivateFlags2 &= ~PFLAG2_PADDING_RESOLVED; 13256 } 13257 13258 /** 13259 * This is called when the view is detached from a window. At this point it 13260 * no longer has a surface for drawing. 13261 * 13262 * @see #onAttachedToWindow() 13263 */ 13264 protected void onDetachedFromWindow() { 13265 } 13266 13267 /** 13268 * This is a framework-internal mirror of onDetachedFromWindow() that's called 13269 * after onDetachedFromWindow(). 13270 * 13271 * If you override this you *MUST* call super.onDetachedFromWindowInternal()! 13272 * The super method should be called at the end of the overriden method to ensure 13273 * subclasses are destroyed first 13274 * 13275 * @hide 13276 */ 13277 protected void onDetachedFromWindowInternal() { 13278 mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT; 13279 mPrivateFlags3 &= ~PFLAG3_IS_LAID_OUT; 13280 13281 removeUnsetPressCallback(); 13282 removeLongPressCallback(); 13283 removePerformClickCallback(); 13284 removeSendViewScrolledAccessibilityEventCallback(); 13285 stopNestedScroll(); 13286 13287 // Anything that started animating right before detach should already 13288 // be in its final state when re-attached. 13289 jumpDrawablesToCurrentState(); 13290 13291 destroyDrawingCache(); 13292 13293 cleanupDraw(); 13294 mCurrentAnimation = null; 13295 } 13296 13297 private void cleanupDraw() { 13298 resetDisplayList(); 13299 if (mAttachInfo != null) { 13300 mAttachInfo.mViewRootImpl.cancelInvalidate(this); 13301 } 13302 } 13303 13304 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 13305 } 13306 13307 /** 13308 * @return The number of times this view has been attached to a window 13309 */ 13310 protected int getWindowAttachCount() { 13311 return mWindowAttachCount; 13312 } 13313 13314 /** 13315 * Retrieve a unique token identifying the window this view is attached to. 13316 * @return Return the window's token for use in 13317 * {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}. 13318 */ 13319 public IBinder getWindowToken() { 13320 return mAttachInfo != null ? mAttachInfo.mWindowToken : null; 13321 } 13322 13323 /** 13324 * Retrieve the {@link WindowId} for the window this view is 13325 * currently attached to. 13326 */ 13327 public WindowId getWindowId() { 13328 if (mAttachInfo == null) { 13329 return null; 13330 } 13331 if (mAttachInfo.mWindowId == null) { 13332 try { 13333 mAttachInfo.mIWindowId = mAttachInfo.mSession.getWindowId( 13334 mAttachInfo.mWindowToken); 13335 mAttachInfo.mWindowId = new WindowId( 13336 mAttachInfo.mIWindowId); 13337 } catch (RemoteException e) { 13338 } 13339 } 13340 return mAttachInfo.mWindowId; 13341 } 13342 13343 /** 13344 * Retrieve a unique token identifying the top-level "real" window of 13345 * the window that this view is attached to. That is, this is like 13346 * {@link #getWindowToken}, except if the window this view in is a panel 13347 * window (attached to another containing window), then the token of 13348 * the containing window is returned instead. 13349 * 13350 * @return Returns the associated window token, either 13351 * {@link #getWindowToken()} or the containing window's token. 13352 */ 13353 public IBinder getApplicationWindowToken() { 13354 AttachInfo ai = mAttachInfo; 13355 if (ai != null) { 13356 IBinder appWindowToken = ai.mPanelParentWindowToken; 13357 if (appWindowToken == null) { 13358 appWindowToken = ai.mWindowToken; 13359 } 13360 return appWindowToken; 13361 } 13362 return null; 13363 } 13364 13365 /** 13366 * Gets the logical display to which the view's window has been attached. 13367 * 13368 * @return The logical display, or null if the view is not currently attached to a window. 13369 */ 13370 public Display getDisplay() { 13371 return mAttachInfo != null ? mAttachInfo.mDisplay : null; 13372 } 13373 13374 /** 13375 * Retrieve private session object this view hierarchy is using to 13376 * communicate with the window manager. 13377 * @return the session object to communicate with the window manager 13378 */ 13379 /*package*/ IWindowSession getWindowSession() { 13380 return mAttachInfo != null ? mAttachInfo.mSession : null; 13381 } 13382 13383 /** 13384 * @param info the {@link android.view.View.AttachInfo} to associated with 13385 * this view 13386 */ 13387 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 13388 //System.out.println("Attached! " + this); 13389 mAttachInfo = info; 13390 if (mOverlay != null) { 13391 mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); 13392 } 13393 mWindowAttachCount++; 13394 // We will need to evaluate the drawable state at least once. 13395 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 13396 if (mFloatingTreeObserver != null) { 13397 info.mTreeObserver.merge(mFloatingTreeObserver); 13398 mFloatingTreeObserver = null; 13399 } 13400 if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) { 13401 mAttachInfo.mScrollContainers.add(this); 13402 mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED; 13403 } 13404 performCollectViewAttributes(mAttachInfo, visibility); 13405 onAttachedToWindow(); 13406 13407 ListenerInfo li = mListenerInfo; 13408 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13409 li != null ? li.mOnAttachStateChangeListeners : null; 13410 if (listeners != null && listeners.size() > 0) { 13411 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13412 // perform the dispatching. The iterator is a safe guard against listeners that 13413 // could mutate the list by calling the various add/remove methods. This prevents 13414 // the array from being modified while we iterate it. 13415 for (OnAttachStateChangeListener listener : listeners) { 13416 listener.onViewAttachedToWindow(this); 13417 } 13418 } 13419 13420 int vis = info.mWindowVisibility; 13421 if (vis != GONE) { 13422 onWindowVisibilityChanged(vis); 13423 } 13424 if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) { 13425 // If nobody has evaluated the drawable state yet, then do it now. 13426 refreshDrawableState(); 13427 } 13428 needGlobalAttributesUpdate(false); 13429 } 13430 13431 void dispatchDetachedFromWindow() { 13432 AttachInfo info = mAttachInfo; 13433 if (info != null) { 13434 int vis = info.mWindowVisibility; 13435 if (vis != GONE) { 13436 onWindowVisibilityChanged(GONE); 13437 } 13438 } 13439 13440 onDetachedFromWindow(); 13441 onDetachedFromWindowInternal(); 13442 13443 ListenerInfo li = mListenerInfo; 13444 final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners = 13445 li != null ? li.mOnAttachStateChangeListeners : null; 13446 if (listeners != null && listeners.size() > 0) { 13447 // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to 13448 // perform the dispatching. The iterator is a safe guard against listeners that 13449 // could mutate the list by calling the various add/remove methods. This prevents 13450 // the array from being modified while we iterate it. 13451 for (OnAttachStateChangeListener listener : listeners) { 13452 listener.onViewDetachedFromWindow(this); 13453 } 13454 } 13455 13456 if ((mPrivateFlags & PFLAG_SCROLL_CONTAINER_ADDED) != 0) { 13457 mAttachInfo.mScrollContainers.remove(this); 13458 mPrivateFlags &= ~PFLAG_SCROLL_CONTAINER_ADDED; 13459 } 13460 13461 mAttachInfo = null; 13462 if (mOverlay != null) { 13463 mOverlay.getOverlayView().dispatchDetachedFromWindow(); 13464 } 13465 } 13466 13467 /** 13468 * Cancel any deferred high-level input events that were previously posted to the event queue. 13469 * 13470 * <p>Many views post high-level events such as click handlers to the event queue 13471 * to run deferred in order to preserve a desired user experience - clearing visible 13472 * pressed states before executing, etc. This method will abort any events of this nature 13473 * that are currently in flight.</p> 13474 * 13475 * <p>Custom views that generate their own high-level deferred input events should override 13476 * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> 13477 * 13478 * <p>This will also cancel pending input events for any child views.</p> 13479 * 13480 * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. 13481 * This will not impact newer events posted after this call that may occur as a result of 13482 * lower-level input events still waiting in the queue. If you are trying to prevent 13483 * double-submitted events for the duration of some sort of asynchronous transaction 13484 * you should also take other steps to protect against unexpected double inputs e.g. calling 13485 * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when 13486 * the transaction completes, tracking already submitted transaction IDs, etc.</p> 13487 */ 13488 public final void cancelPendingInputEvents() { 13489 dispatchCancelPendingInputEvents(); 13490 } 13491 13492 /** 13493 * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. 13494 * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. 13495 */ 13496 void dispatchCancelPendingInputEvents() { 13497 mPrivateFlags3 &= ~PFLAG3_CALLED_SUPER; 13498 onCancelPendingInputEvents(); 13499 if ((mPrivateFlags3 & PFLAG3_CALLED_SUPER) != PFLAG3_CALLED_SUPER) { 13500 throw new SuperNotCalledException("View " + getClass().getSimpleName() + 13501 " did not call through to super.onCancelPendingInputEvents()"); 13502 } 13503 } 13504 13505 /** 13506 * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or 13507 * a parent view. 13508 * 13509 * <p>This method is responsible for removing any pending high-level input events that were 13510 * posted to the event queue to run later. Custom view classes that post their own deferred 13511 * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or 13512 * {@link android.os.Handler} should override this method, call 13513 * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. 13514 * </p> 13515 */ 13516 public void onCancelPendingInputEvents() { 13517 removePerformClickCallback(); 13518 cancelLongPress(); 13519 mPrivateFlags3 |= PFLAG3_CALLED_SUPER; 13520 } 13521 13522 /** 13523 * Store this view hierarchy's frozen state into the given container. 13524 * 13525 * @param container The SparseArray in which to save the view's state. 13526 * 13527 * @see #restoreHierarchyState(android.util.SparseArray) 13528 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13529 * @see #onSaveInstanceState() 13530 */ 13531 public void saveHierarchyState(SparseArray<Parcelable> container) { 13532 dispatchSaveInstanceState(container); 13533 } 13534 13535 /** 13536 * Called by {@link #saveHierarchyState(android.util.SparseArray)} to store the state for 13537 * this view and its children. May be overridden to modify how freezing happens to a 13538 * view's children; for example, some views may want to not store state for their children. 13539 * 13540 * @param container The SparseArray in which to save the view's state. 13541 * 13542 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13543 * @see #saveHierarchyState(android.util.SparseArray) 13544 * @see #onSaveInstanceState() 13545 */ 13546 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 13547 if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { 13548 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13549 Parcelable state = onSaveInstanceState(); 13550 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13551 throw new IllegalStateException( 13552 "Derived class did not call super.onSaveInstanceState()"); 13553 } 13554 if (state != null) { 13555 // Log.i("View", "Freezing #" + Integer.toHexString(mID) 13556 // + ": " + state); 13557 container.put(mID, state); 13558 } 13559 } 13560 } 13561 13562 /** 13563 * Hook allowing a view to generate a representation of its internal state 13564 * that can later be used to create a new instance with that same state. 13565 * This state should only contain information that is not persistent or can 13566 * not be reconstructed later. For example, you will never store your 13567 * current position on screen because that will be computed again when a 13568 * new instance of the view is placed in its view hierarchy. 13569 * <p> 13570 * Some examples of things you may store here: the current cursor position 13571 * in a text view (but usually not the text itself since that is stored in a 13572 * content provider or other persistent storage), the currently selected 13573 * item in a list view. 13574 * 13575 * @return Returns a Parcelable object containing the view's current dynamic 13576 * state, or null if there is nothing interesting to save. The 13577 * default implementation returns null. 13578 * @see #onRestoreInstanceState(android.os.Parcelable) 13579 * @see #saveHierarchyState(android.util.SparseArray) 13580 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13581 * @see #setSaveEnabled(boolean) 13582 */ 13583 protected Parcelable onSaveInstanceState() { 13584 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13585 return BaseSavedState.EMPTY_STATE; 13586 } 13587 13588 /** 13589 * Restore this view hierarchy's frozen state from the given container. 13590 * 13591 * @param container The SparseArray which holds previously frozen states. 13592 * 13593 * @see #saveHierarchyState(android.util.SparseArray) 13594 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13595 * @see #onRestoreInstanceState(android.os.Parcelable) 13596 */ 13597 public void restoreHierarchyState(SparseArray<Parcelable> container) { 13598 dispatchRestoreInstanceState(container); 13599 } 13600 13601 /** 13602 * Called by {@link #restoreHierarchyState(android.util.SparseArray)} to retrieve the 13603 * state for this view and its children. May be overridden to modify how restoring 13604 * happens to a view's children; for example, some views may want to not store state 13605 * for their children. 13606 * 13607 * @param container The SparseArray which holds previously saved state. 13608 * 13609 * @see #dispatchSaveInstanceState(android.util.SparseArray) 13610 * @see #restoreHierarchyState(android.util.SparseArray) 13611 * @see #onRestoreInstanceState(android.os.Parcelable) 13612 */ 13613 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 13614 if (mID != NO_ID) { 13615 Parcelable state = container.get(mID); 13616 if (state != null) { 13617 // Log.i("View", "Restoreing #" + Integer.toHexString(mID) 13618 // + ": " + state); 13619 mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED; 13620 onRestoreInstanceState(state); 13621 if ((mPrivateFlags & PFLAG_SAVE_STATE_CALLED) == 0) { 13622 throw new IllegalStateException( 13623 "Derived class did not call super.onRestoreInstanceState()"); 13624 } 13625 } 13626 } 13627 } 13628 13629 /** 13630 * Hook allowing a view to re-apply a representation of its internal state that had previously 13631 * been generated by {@link #onSaveInstanceState}. This function will never be called with a 13632 * null state. 13633 * 13634 * @param state The frozen state that had previously been returned by 13635 * {@link #onSaveInstanceState}. 13636 * 13637 * @see #onSaveInstanceState() 13638 * @see #restoreHierarchyState(android.util.SparseArray) 13639 * @see #dispatchRestoreInstanceState(android.util.SparseArray) 13640 */ 13641 protected void onRestoreInstanceState(Parcelable state) { 13642 mPrivateFlags |= PFLAG_SAVE_STATE_CALLED; 13643 if (state != BaseSavedState.EMPTY_STATE && state != null) { 13644 throw new IllegalArgumentException("Wrong state class, expecting View State but " 13645 + "received " + state.getClass().toString() + " instead. This usually happens " 13646 + "when two views of different type have the same id in the same hierarchy. " 13647 + "This view's id is " + ViewDebug.resolveId(mContext, getId()) + ". Make sure " 13648 + "other views do not use the same id."); 13649 } 13650 } 13651 13652 /** 13653 * <p>Return the time at which the drawing of the view hierarchy started.</p> 13654 * 13655 * @return the drawing start time in milliseconds 13656 */ 13657 public long getDrawingTime() { 13658 return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0; 13659 } 13660 13661 /** 13662 * <p>Enables or disables the duplication of the parent's state into this view. When 13663 * duplication is enabled, this view gets its drawable state from its parent rather 13664 * than from its own internal properties.</p> 13665 * 13666 * <p>Note: in the current implementation, setting this property to true after the 13667 * view was added to a ViewGroup might have no effect at all. This property should 13668 * always be used from XML or set to true before adding this view to a ViewGroup.</p> 13669 * 13670 * <p>Note: if this view's parent addStateFromChildren property is enabled and this 13671 * property is enabled, an exception will be thrown.</p> 13672 * 13673 * <p>Note: if the child view uses and updates additionnal states which are unknown to the 13674 * parent, these states should not be affected by this method.</p> 13675 * 13676 * @param enabled True to enable duplication of the parent's drawable state, false 13677 * to disable it. 13678 * 13679 * @see #getDrawableState() 13680 * @see #isDuplicateParentStateEnabled() 13681 */ 13682 public void setDuplicateParentStateEnabled(boolean enabled) { 13683 setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE); 13684 } 13685 13686 /** 13687 * <p>Indicates whether this duplicates its drawable state from its parent.</p> 13688 * 13689 * @return True if this view's drawable state is duplicated from the parent, 13690 * false otherwise 13691 * 13692 * @see #getDrawableState() 13693 * @see #setDuplicateParentStateEnabled(boolean) 13694 */ 13695 public boolean isDuplicateParentStateEnabled() { 13696 return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE; 13697 } 13698 13699 /** 13700 * <p>Specifies the type of layer backing this view. The layer can be 13701 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13702 * {@link #LAYER_TYPE_HARDWARE}.</p> 13703 * 13704 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13705 * instance that controls how the layer is composed on screen. The following 13706 * properties of the paint are taken into account when composing the layer:</p> 13707 * <ul> 13708 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13709 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13710 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13711 * </ul> 13712 * 13713 * <p>If this view has an alpha value set to < 1.0 by calling 13714 * {@link #setAlpha(float)}, the alpha value of the layer's paint is superceded 13715 * by this view's alpha value.</p> 13716 * 13717 * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE}, 13718 * {@link #LAYER_TYPE_SOFTWARE} and {@link #LAYER_TYPE_HARDWARE} 13719 * for more information on when and how to use layers.</p> 13720 * 13721 * @param layerType The type of layer to use with this view, must be one of 13722 * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13723 * {@link #LAYER_TYPE_HARDWARE} 13724 * @param paint The paint used to compose the layer. This argument is optional 13725 * and can be null. It is ignored when the layer type is 13726 * {@link #LAYER_TYPE_NONE} 13727 * 13728 * @see #getLayerType() 13729 * @see #LAYER_TYPE_NONE 13730 * @see #LAYER_TYPE_SOFTWARE 13731 * @see #LAYER_TYPE_HARDWARE 13732 * @see #setAlpha(float) 13733 * 13734 * @attr ref android.R.styleable#View_layerType 13735 */ 13736 public void setLayerType(int layerType, Paint paint) { 13737 if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) { 13738 throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " 13739 + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE"); 13740 } 13741 13742 boolean typeChanged = mRenderNode.setLayerType(layerType); 13743 13744 if (!typeChanged) { 13745 setLayerPaint(paint); 13746 return; 13747 } 13748 13749 // Destroy any previous software drawing cache if needed 13750 if (mLayerType == LAYER_TYPE_SOFTWARE) { 13751 destroyDrawingCache(); 13752 } 13753 13754 mLayerType = layerType; 13755 final boolean layerDisabled = (mLayerType == LAYER_TYPE_NONE); 13756 mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); 13757 mRenderNode.setLayerPaint(mLayerPaint); 13758 13759 // draw() behaves differently if we are on a layer, so we need to 13760 // invalidate() here 13761 invalidateParentCaches(); 13762 invalidate(true); 13763 } 13764 13765 /** 13766 * Updates the {@link Paint} object used with the current layer (used only if the current 13767 * layer type is not set to {@link #LAYER_TYPE_NONE}). Changed properties of the Paint 13768 * provided to {@link #setLayerType(int, android.graphics.Paint)} will be used the next time 13769 * the View is redrawn, but {@link #setLayerPaint(android.graphics.Paint)} must be called to 13770 * ensure that the view gets redrawn immediately. 13771 * 13772 * <p>A layer is associated with an optional {@link android.graphics.Paint} 13773 * instance that controls how the layer is composed on screen. The following 13774 * properties of the paint are taken into account when composing the layer:</p> 13775 * <ul> 13776 * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li> 13777 * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li> 13778 * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li> 13779 * </ul> 13780 * 13781 * <p>If this view has an alpha value set to < 1.0 by calling {@link #setAlpha(float)}, the 13782 * alpha value of the layer's paint is superceded by this view's alpha value.</p> 13783 * 13784 * @param paint The paint used to compose the layer. This argument is optional 13785 * and can be null. It is ignored when the layer type is 13786 * {@link #LAYER_TYPE_NONE} 13787 * 13788 * @see #setLayerType(int, android.graphics.Paint) 13789 */ 13790 public void setLayerPaint(Paint paint) { 13791 int layerType = getLayerType(); 13792 if (layerType != LAYER_TYPE_NONE) { 13793 mLayerPaint = paint == null ? new Paint() : paint; 13794 if (layerType == LAYER_TYPE_HARDWARE) { 13795 if (mRenderNode.setLayerPaint(mLayerPaint)) { 13796 invalidateViewProperty(false, false); 13797 } 13798 } else { 13799 invalidate(); 13800 } 13801 } 13802 } 13803 13804 /** 13805 * Indicates whether this view has a static layer. A view with layer type 13806 * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are 13807 * dynamic. 13808 */ 13809 boolean hasStaticLayer() { 13810 return true; 13811 } 13812 13813 /** 13814 * Indicates what type of layer is currently associated with this view. By default 13815 * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}. 13816 * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)} 13817 * for more information on the different types of layers. 13818 * 13819 * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or 13820 * {@link #LAYER_TYPE_HARDWARE} 13821 * 13822 * @see #setLayerType(int, android.graphics.Paint) 13823 * @see #buildLayer() 13824 * @see #LAYER_TYPE_NONE 13825 * @see #LAYER_TYPE_SOFTWARE 13826 * @see #LAYER_TYPE_HARDWARE 13827 */ 13828 public int getLayerType() { 13829 return mLayerType; 13830 } 13831 13832 /** 13833 * Forces this view's layer to be created and this view to be rendered 13834 * into its layer. If this view's layer type is set to {@link #LAYER_TYPE_NONE}, 13835 * invoking this method will have no effect. 13836 * 13837 * This method can for instance be used to render a view into its layer before 13838 * starting an animation. If this view is complex, rendering into the layer 13839 * before starting the animation will avoid skipping frames. 13840 * 13841 * @throws IllegalStateException If this view is not attached to a window 13842 * 13843 * @see #setLayerType(int, android.graphics.Paint) 13844 */ 13845 public void buildLayer() { 13846 if (mLayerType == LAYER_TYPE_NONE) return; 13847 13848 final AttachInfo attachInfo = mAttachInfo; 13849 if (attachInfo == null) { 13850 throw new IllegalStateException("This view must be attached to a window first"); 13851 } 13852 13853 if (getWidth() == 0 || getHeight() == 0) { 13854 return; 13855 } 13856 13857 switch (mLayerType) { 13858 case LAYER_TYPE_HARDWARE: 13859 updateDisplayListIfDirty(); 13860 if (attachInfo.mHardwareRenderer != null && mRenderNode.isValid()) { 13861 attachInfo.mHardwareRenderer.buildLayer(mRenderNode); 13862 } 13863 break; 13864 case LAYER_TYPE_SOFTWARE: 13865 buildDrawingCache(true); 13866 break; 13867 } 13868 } 13869 13870 /** 13871 * If this View draws with a HardwareLayer, returns it. 13872 * Otherwise returns null 13873 * 13874 * TODO: Only TextureView uses this, can we eliminate it? 13875 */ 13876 HardwareLayer getHardwareLayer() { 13877 return null; 13878 } 13879 13880 /** 13881 * Destroys all hardware rendering resources. This method is invoked 13882 * when the system needs to reclaim resources. Upon execution of this 13883 * method, you should free any OpenGL resources created by the view. 13884 * 13885 * Note: you <strong>must</strong> call 13886 * <code>super.destroyHardwareResources()</code> when overriding 13887 * this method. 13888 * 13889 * @hide 13890 */ 13891 protected void destroyHardwareResources() { 13892 // Although the Layer will be destroyed by RenderNode, we want to release 13893 // the staging display list, which is also a signal to RenderNode that it's 13894 // safe to free its copy of the display list as it knows that we will 13895 // push an updated DisplayList if we try to draw again 13896 resetDisplayList(); 13897 } 13898 13899 /** 13900 * <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call 13901 * to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a 13902 * bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when 13903 * the cache is enabled. To benefit from the cache, you must request the drawing cache by 13904 * calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not 13905 * null.</p> 13906 * 13907 * <p>Enabling the drawing cache is similar to 13908 * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware 13909 * acceleration is turned off. When hardware acceleration is turned on, enabling the 13910 * drawing cache has no effect on rendering because the system uses a different mechanism 13911 * for acceleration which ignores the flag. If you want to use a Bitmap for the view, even 13912 * when hardware acceleration is enabled, see {@link #setLayerType(int, android.graphics.Paint)} 13913 * for information on how to enable software and hardware layers.</p> 13914 * 13915 * <p>This API can be used to manually generate 13916 * a bitmap copy of this view, by setting the flag to <code>true</code> and calling 13917 * {@link #getDrawingCache()}.</p> 13918 * 13919 * @param enabled true to enable the drawing cache, false otherwise 13920 * 13921 * @see #isDrawingCacheEnabled() 13922 * @see #getDrawingCache() 13923 * @see #buildDrawingCache() 13924 * @see #setLayerType(int, android.graphics.Paint) 13925 */ 13926 public void setDrawingCacheEnabled(boolean enabled) { 13927 mCachingFailed = false; 13928 setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); 13929 } 13930 13931 /** 13932 * <p>Indicates whether the drawing cache is enabled for this view.</p> 13933 * 13934 * @return true if the drawing cache is enabled 13935 * 13936 * @see #setDrawingCacheEnabled(boolean) 13937 * @see #getDrawingCache() 13938 */ 13939 @ViewDebug.ExportedProperty(category = "drawing") 13940 public boolean isDrawingCacheEnabled() { 13941 return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; 13942 } 13943 13944 /** 13945 * Debugging utility which recursively outputs the dirty state of a view and its 13946 * descendants. 13947 * 13948 * @hide 13949 */ 13950 @SuppressWarnings({"UnusedDeclaration"}) 13951 public void outputDirtyFlags(String indent, boolean clear, int clearMask) { 13952 Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + 13953 ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + 13954 (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + 13955 ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); 13956 if (clear) { 13957 mPrivateFlags &= clearMask; 13958 } 13959 if (this instanceof ViewGroup) { 13960 ViewGroup parent = (ViewGroup) this; 13961 final int count = parent.getChildCount(); 13962 for (int i = 0; i < count; i++) { 13963 final View child = parent.getChildAt(i); 13964 child.outputDirtyFlags(indent + " ", clear, clearMask); 13965 } 13966 } 13967 } 13968 13969 /** 13970 * This method is used by ViewGroup to cause its children to restore or recreate their 13971 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 13972 * to recreate its own display list, which would happen if it went through the normal 13973 * draw/dispatchDraw mechanisms. 13974 * 13975 * @hide 13976 */ 13977 protected void dispatchGetDisplayList() {} 13978 13979 /** 13980 * A view that is not attached or hardware accelerated cannot create a display list. 13981 * This method checks these conditions and returns the appropriate result. 13982 * 13983 * @return true if view has the ability to create a display list, false otherwise. 13984 * 13985 * @hide 13986 */ 13987 public boolean canHaveDisplayList() { 13988 return !(mAttachInfo == null || mAttachInfo.mHardwareRenderer == null); 13989 } 13990 13991 private void updateDisplayListIfDirty() { 13992 final RenderNode renderNode = mRenderNode; 13993 if (!canHaveDisplayList()) { 13994 // can't populate RenderNode, don't try 13995 return; 13996 } 13997 13998 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 13999 || !renderNode.isValid() 14000 || (mRecreateDisplayList)) { 14001 // Don't need to recreate the display list, just need to tell our 14002 // children to restore/recreate theirs 14003 if (renderNode.isValid() 14004 && !mRecreateDisplayList) { 14005 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14006 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14007 dispatchGetDisplayList(); 14008 14009 return; // no work needed 14010 } 14011 14012 // If we got here, we're recreating it. Mark it as such to ensure that 14013 // we copy in child display lists into ours in drawChild() 14014 mRecreateDisplayList = true; 14015 14016 int width = mRight - mLeft; 14017 int height = mBottom - mTop; 14018 int layerType = getLayerType(); 14019 14020 final HardwareCanvas canvas = renderNode.start(width, height); 14021 canvas.setHighContrastText(mAttachInfo.mHighContrastText); 14022 14023 try { 14024 final HardwareLayer layer = getHardwareLayer(); 14025 if (layer != null && layer.isValid()) { 14026 canvas.drawHardwareLayer(layer, 0, 0, mLayerPaint); 14027 } else if (layerType == LAYER_TYPE_SOFTWARE) { 14028 buildDrawingCache(true); 14029 Bitmap cache = getDrawingCache(true); 14030 if (cache != null) { 14031 canvas.drawBitmap(cache, 0, 0, mLayerPaint); 14032 } 14033 } else { 14034 computeScroll(); 14035 14036 canvas.translate(-mScrollX, -mScrollY); 14037 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14038 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14039 14040 // Fast path for layouts with no backgrounds 14041 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14042 dispatchDraw(canvas); 14043 if (mOverlay != null && !mOverlay.isEmpty()) { 14044 mOverlay.getOverlayView().draw(canvas); 14045 } 14046 } else { 14047 draw(canvas); 14048 } 14049 drawAccessibilityFocus(canvas); 14050 } 14051 } finally { 14052 renderNode.end(canvas); 14053 setDisplayListProperties(renderNode); 14054 } 14055 } else { 14056 mPrivateFlags |= PFLAG_DRAWN | PFLAG_DRAWING_CACHE_VALID; 14057 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14058 } 14059 } 14060 14061 /** 14062 * Returns a RenderNode with View draw content recorded, which can be 14063 * used to draw this view again without executing its draw method. 14064 * 14065 * @return A RenderNode ready to replay, or null if caching is not enabled. 14066 * 14067 * @hide 14068 */ 14069 public RenderNode getDisplayList() { 14070 updateDisplayListIfDirty(); 14071 return mRenderNode; 14072 } 14073 14074 private void resetDisplayList() { 14075 if (mRenderNode.isValid()) { 14076 mRenderNode.destroyDisplayListData(); 14077 } 14078 14079 if (mBackgroundRenderNode != null && mBackgroundRenderNode.isValid()) { 14080 mBackgroundRenderNode.destroyDisplayListData(); 14081 } 14082 } 14083 14084 /** 14085 * <p>Calling this method is equivalent to calling <code>getDrawingCache(false)</code>.</p> 14086 * 14087 * @return A non-scaled bitmap representing this view or null if cache is disabled. 14088 * 14089 * @see #getDrawingCache(boolean) 14090 */ 14091 public Bitmap getDrawingCache() { 14092 return getDrawingCache(false); 14093 } 14094 14095 /** 14096 * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap 14097 * is null when caching is disabled. If caching is enabled and the cache is not ready, 14098 * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not 14099 * draw from the cache when the cache is enabled. To benefit from the cache, you must 14100 * request the drawing cache by calling this method and draw it on screen if the 14101 * returned bitmap is not null.</p> 14102 * 14103 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14104 * this method will create a bitmap of the same size as this view. Because this bitmap 14105 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14106 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14107 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14108 * size than the view. This implies that your application must be able to handle this 14109 * size.</p> 14110 * 14111 * @param autoScale Indicates whether the generated bitmap should be scaled based on 14112 * the current density of the screen when the application is in compatibility 14113 * mode. 14114 * 14115 * @return A bitmap representing this view or null if cache is disabled. 14116 * 14117 * @see #setDrawingCacheEnabled(boolean) 14118 * @see #isDrawingCacheEnabled() 14119 * @see #buildDrawingCache(boolean) 14120 * @see #destroyDrawingCache() 14121 */ 14122 public Bitmap getDrawingCache(boolean autoScale) { 14123 if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { 14124 return null; 14125 } 14126 if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) { 14127 buildDrawingCache(autoScale); 14128 } 14129 return autoScale ? mDrawingCache : mUnscaledDrawingCache; 14130 } 14131 14132 /** 14133 * <p>Frees the resources used by the drawing cache. If you call 14134 * {@link #buildDrawingCache()} manually without calling 14135 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14136 * should cleanup the cache with this method afterwards.</p> 14137 * 14138 * @see #setDrawingCacheEnabled(boolean) 14139 * @see #buildDrawingCache() 14140 * @see #getDrawingCache() 14141 */ 14142 public void destroyDrawingCache() { 14143 if (mDrawingCache != null) { 14144 mDrawingCache.recycle(); 14145 mDrawingCache = null; 14146 } 14147 if (mUnscaledDrawingCache != null) { 14148 mUnscaledDrawingCache.recycle(); 14149 mUnscaledDrawingCache = null; 14150 } 14151 } 14152 14153 /** 14154 * Setting a solid background color for the drawing cache's bitmaps will improve 14155 * performance and memory usage. Note, though that this should only be used if this 14156 * view will always be drawn on top of a solid color. 14157 * 14158 * @param color The background color to use for the drawing cache's bitmap 14159 * 14160 * @see #setDrawingCacheEnabled(boolean) 14161 * @see #buildDrawingCache() 14162 * @see #getDrawingCache() 14163 */ 14164 public void setDrawingCacheBackgroundColor(int color) { 14165 if (color != mDrawingCacheBackgroundColor) { 14166 mDrawingCacheBackgroundColor = color; 14167 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 14168 } 14169 } 14170 14171 /** 14172 * @see #setDrawingCacheBackgroundColor(int) 14173 * 14174 * @return The background color to used for the drawing cache's bitmap 14175 */ 14176 public int getDrawingCacheBackgroundColor() { 14177 return mDrawingCacheBackgroundColor; 14178 } 14179 14180 /** 14181 * <p>Calling this method is equivalent to calling <code>buildDrawingCache(false)</code>.</p> 14182 * 14183 * @see #buildDrawingCache(boolean) 14184 */ 14185 public void buildDrawingCache() { 14186 buildDrawingCache(false); 14187 } 14188 14189 /** 14190 * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> 14191 * 14192 * <p>If you call {@link #buildDrawingCache()} manually without calling 14193 * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you 14194 * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> 14195 * 14196 * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, 14197 * this method will create a bitmap of the same size as this view. Because this bitmap 14198 * will be drawn scaled by the parent ViewGroup, the result on screen might show 14199 * scaling artifacts. To avoid such artifacts, you should call this method by setting 14200 * the auto scaling to true. Doing so, however, will generate a bitmap of a different 14201 * size than the view. This implies that your application must be able to handle this 14202 * size.</p> 14203 * 14204 * <p>You should avoid calling this method when hardware acceleration is enabled. If 14205 * you do not need the drawing cache bitmap, calling this method will increase memory 14206 * usage and cause the view to be rendered in software once, thus negatively impacting 14207 * performance.</p> 14208 * 14209 * @see #getDrawingCache() 14210 * @see #destroyDrawingCache() 14211 */ 14212 public void buildDrawingCache(boolean autoScale) { 14213 if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? 14214 mDrawingCache == null : mUnscaledDrawingCache == null)) { 14215 mCachingFailed = false; 14216 14217 int width = mRight - mLeft; 14218 int height = mBottom - mTop; 14219 14220 final AttachInfo attachInfo = mAttachInfo; 14221 final boolean scalingRequired = attachInfo != null && attachInfo.mScalingRequired; 14222 14223 if (autoScale && scalingRequired) { 14224 width = (int) ((width * attachInfo.mApplicationScale) + 0.5f); 14225 height = (int) ((height * attachInfo.mApplicationScale) + 0.5f); 14226 } 14227 14228 final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor; 14229 final boolean opaque = drawingCacheBackgroundColor != 0 || isOpaque(); 14230 final boolean use32BitCache = attachInfo != null && attachInfo.mUse32BitDrawingCache; 14231 14232 final long projectedBitmapSize = width * height * (opaque && !use32BitCache ? 2 : 4); 14233 final long drawingCacheSize = 14234 ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize(); 14235 if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { 14236 if (width > 0 && height > 0) { 14237 Log.w(VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " 14238 + projectedBitmapSize + " bytes, only " 14239 + drawingCacheSize + " available"); 14240 } 14241 destroyDrawingCache(); 14242 mCachingFailed = true; 14243 return; 14244 } 14245 14246 boolean clear = true; 14247 Bitmap bitmap = autoScale ? mDrawingCache : mUnscaledDrawingCache; 14248 14249 if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) { 14250 Bitmap.Config quality; 14251 if (!opaque) { 14252 // Never pick ARGB_4444 because it looks awful 14253 // Keep the DRAWING_CACHE_QUALITY_LOW flag just in case 14254 switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) { 14255 case DRAWING_CACHE_QUALITY_AUTO: 14256 case DRAWING_CACHE_QUALITY_LOW: 14257 case DRAWING_CACHE_QUALITY_HIGH: 14258 default: 14259 quality = Bitmap.Config.ARGB_8888; 14260 break; 14261 } 14262 } else { 14263 // Optimization for translucent windows 14264 // If the window is translucent, use a 32 bits bitmap to benefit from memcpy() 14265 quality = use32BitCache ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; 14266 } 14267 14268 // Try to cleanup memory 14269 if (bitmap != null) bitmap.recycle(); 14270 14271 try { 14272 bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14273 width, height, quality); 14274 bitmap.setDensity(getResources().getDisplayMetrics().densityDpi); 14275 if (autoScale) { 14276 mDrawingCache = bitmap; 14277 } else { 14278 mUnscaledDrawingCache = bitmap; 14279 } 14280 if (opaque && use32BitCache) bitmap.setHasAlpha(false); 14281 } catch (OutOfMemoryError e) { 14282 // If there is not enough memory to create the bitmap cache, just 14283 // ignore the issue as bitmap caches are not required to draw the 14284 // view hierarchy 14285 if (autoScale) { 14286 mDrawingCache = null; 14287 } else { 14288 mUnscaledDrawingCache = null; 14289 } 14290 mCachingFailed = true; 14291 return; 14292 } 14293 14294 clear = drawingCacheBackgroundColor != 0; 14295 } 14296 14297 Canvas canvas; 14298 if (attachInfo != null) { 14299 canvas = attachInfo.mCanvas; 14300 if (canvas == null) { 14301 canvas = new Canvas(); 14302 } 14303 canvas.setBitmap(bitmap); 14304 // Temporarily clobber the cached Canvas in case one of our children 14305 // is also using a drawing cache. Without this, the children would 14306 // steal the canvas by attaching their own bitmap to it and bad, bad 14307 // thing would happen (invisible views, corrupted drawings, etc.) 14308 attachInfo.mCanvas = null; 14309 } else { 14310 // This case should hopefully never or seldom happen 14311 canvas = new Canvas(bitmap); 14312 } 14313 14314 if (clear) { 14315 bitmap.eraseColor(drawingCacheBackgroundColor); 14316 } 14317 14318 computeScroll(); 14319 final int restoreCount = canvas.save(); 14320 14321 if (autoScale && scalingRequired) { 14322 final float scale = attachInfo.mApplicationScale; 14323 canvas.scale(scale, scale); 14324 } 14325 14326 canvas.translate(-mScrollX, -mScrollY); 14327 14328 mPrivateFlags |= PFLAG_DRAWN; 14329 if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated || 14330 mLayerType != LAYER_TYPE_NONE) { 14331 mPrivateFlags |= PFLAG_DRAWING_CACHE_VALID; 14332 } 14333 14334 // Fast path for layouts with no backgrounds 14335 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14336 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14337 dispatchDraw(canvas); 14338 if (mOverlay != null && !mOverlay.isEmpty()) { 14339 mOverlay.getOverlayView().draw(canvas); 14340 } 14341 } else { 14342 draw(canvas); 14343 } 14344 drawAccessibilityFocus(canvas); 14345 14346 canvas.restoreToCount(restoreCount); 14347 canvas.setBitmap(null); 14348 14349 if (attachInfo != null) { 14350 // Restore the cached Canvas for our siblings 14351 attachInfo.mCanvas = canvas; 14352 } 14353 } 14354 } 14355 14356 /** 14357 * Create a snapshot of the view into a bitmap. We should probably make 14358 * some form of this public, but should think about the API. 14359 */ 14360 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 14361 int width = mRight - mLeft; 14362 int height = mBottom - mTop; 14363 14364 final AttachInfo attachInfo = mAttachInfo; 14365 final float scale = attachInfo != null ? attachInfo.mApplicationScale : 1.0f; 14366 width = (int) ((width * scale) + 0.5f); 14367 height = (int) ((height * scale) + 0.5f); 14368 14369 Bitmap bitmap = Bitmap.createBitmap(mResources.getDisplayMetrics(), 14370 width > 0 ? width : 1, height > 0 ? height : 1, quality); 14371 if (bitmap == null) { 14372 throw new OutOfMemoryError(); 14373 } 14374 14375 Resources resources = getResources(); 14376 if (resources != null) { 14377 bitmap.setDensity(resources.getDisplayMetrics().densityDpi); 14378 } 14379 14380 Canvas canvas; 14381 if (attachInfo != null) { 14382 canvas = attachInfo.mCanvas; 14383 if (canvas == null) { 14384 canvas = new Canvas(); 14385 } 14386 canvas.setBitmap(bitmap); 14387 // Temporarily clobber the cached Canvas in case one of our children 14388 // is also using a drawing cache. Without this, the children would 14389 // steal the canvas by attaching their own bitmap to it and bad, bad 14390 // things would happen (invisible views, corrupted drawings, etc.) 14391 attachInfo.mCanvas = null; 14392 } else { 14393 // This case should hopefully never or seldom happen 14394 canvas = new Canvas(bitmap); 14395 } 14396 14397 if ((backgroundColor & 0xff000000) != 0) { 14398 bitmap.eraseColor(backgroundColor); 14399 } 14400 14401 computeScroll(); 14402 final int restoreCount = canvas.save(); 14403 canvas.scale(scale, scale); 14404 canvas.translate(-mScrollX, -mScrollY); 14405 14406 // Temporarily remove the dirty mask 14407 int flags = mPrivateFlags; 14408 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 14409 14410 // Fast path for layouts with no backgrounds 14411 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 14412 dispatchDraw(canvas); 14413 if (mOverlay != null && !mOverlay.isEmpty()) { 14414 mOverlay.getOverlayView().draw(canvas); 14415 } 14416 } else { 14417 draw(canvas); 14418 } 14419 drawAccessibilityFocus(canvas); 14420 14421 mPrivateFlags = flags; 14422 14423 canvas.restoreToCount(restoreCount); 14424 canvas.setBitmap(null); 14425 14426 if (attachInfo != null) { 14427 // Restore the cached Canvas for our siblings 14428 attachInfo.mCanvas = canvas; 14429 } 14430 14431 return bitmap; 14432 } 14433 14434 /** 14435 * Indicates whether this View is currently in edit mode. A View is usually 14436 * in edit mode when displayed within a developer tool. For instance, if 14437 * this View is being drawn by a visual user interface builder, this method 14438 * should return true. 14439 * 14440 * Subclasses should check the return value of this method to provide 14441 * different behaviors if their normal behavior might interfere with the 14442 * host environment. For instance: the class spawns a thread in its 14443 * constructor, the drawing code relies on device-specific features, etc. 14444 * 14445 * This method is usually checked in the drawing code of custom widgets. 14446 * 14447 * @return True if this View is in edit mode, false otherwise. 14448 */ 14449 public boolean isInEditMode() { 14450 return false; 14451 } 14452 14453 /** 14454 * If the View draws content inside its padding and enables fading edges, 14455 * it needs to support padding offsets. Padding offsets are added to the 14456 * fading edges to extend the length of the fade so that it covers pixels 14457 * drawn inside the padding. 14458 * 14459 * Subclasses of this class should override this method if they need 14460 * to draw content inside the padding. 14461 * 14462 * @return True if padding offset must be applied, false otherwise. 14463 * 14464 * @see #getLeftPaddingOffset() 14465 * @see #getRightPaddingOffset() 14466 * @see #getTopPaddingOffset() 14467 * @see #getBottomPaddingOffset() 14468 * 14469 * @since CURRENT 14470 */ 14471 protected boolean isPaddingOffsetRequired() { 14472 return false; 14473 } 14474 14475 /** 14476 * Amount by which to extend the left fading region. Called only when 14477 * {@link #isPaddingOffsetRequired()} returns true. 14478 * 14479 * @return The left padding offset in pixels. 14480 * 14481 * @see #isPaddingOffsetRequired() 14482 * 14483 * @since CURRENT 14484 */ 14485 protected int getLeftPaddingOffset() { 14486 return 0; 14487 } 14488 14489 /** 14490 * Amount by which to extend the right fading region. Called only when 14491 * {@link #isPaddingOffsetRequired()} returns true. 14492 * 14493 * @return The right padding offset in pixels. 14494 * 14495 * @see #isPaddingOffsetRequired() 14496 * 14497 * @since CURRENT 14498 */ 14499 protected int getRightPaddingOffset() { 14500 return 0; 14501 } 14502 14503 /** 14504 * Amount by which to extend the top fading region. Called only when 14505 * {@link #isPaddingOffsetRequired()} returns true. 14506 * 14507 * @return The top padding offset in pixels. 14508 * 14509 * @see #isPaddingOffsetRequired() 14510 * 14511 * @since CURRENT 14512 */ 14513 protected int getTopPaddingOffset() { 14514 return 0; 14515 } 14516 14517 /** 14518 * Amount by which to extend the bottom fading region. Called only when 14519 * {@link #isPaddingOffsetRequired()} returns true. 14520 * 14521 * @return The bottom padding offset in pixels. 14522 * 14523 * @see #isPaddingOffsetRequired() 14524 * 14525 * @since CURRENT 14526 */ 14527 protected int getBottomPaddingOffset() { 14528 return 0; 14529 } 14530 14531 /** 14532 * @hide 14533 * @param offsetRequired 14534 */ 14535 protected int getFadeTop(boolean offsetRequired) { 14536 int top = mPaddingTop; 14537 if (offsetRequired) top += getTopPaddingOffset(); 14538 return top; 14539 } 14540 14541 /** 14542 * @hide 14543 * @param offsetRequired 14544 */ 14545 protected int getFadeHeight(boolean offsetRequired) { 14546 int padding = mPaddingTop; 14547 if (offsetRequired) padding += getTopPaddingOffset(); 14548 return mBottom - mTop - mPaddingBottom - padding; 14549 } 14550 14551 /** 14552 * <p>Indicates whether this view is attached to a hardware accelerated 14553 * window or not.</p> 14554 * 14555 * <p>Even if this method returns true, it does not mean that every call 14556 * to {@link #draw(android.graphics.Canvas)} will be made with an hardware 14557 * accelerated {@link android.graphics.Canvas}. For instance, if this view 14558 * is drawn onto an offscreen {@link android.graphics.Bitmap} and its 14559 * window is hardware accelerated, 14560 * {@link android.graphics.Canvas#isHardwareAccelerated()} will likely 14561 * return false, and this method will return true.</p> 14562 * 14563 * @return True if the view is attached to a window and the window is 14564 * hardware accelerated; false in any other case. 14565 */ 14566 @ViewDebug.ExportedProperty(category = "drawing") 14567 public boolean isHardwareAccelerated() { 14568 return mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14569 } 14570 14571 /** 14572 * Sets a rectangular area on this view to which the view will be clipped 14573 * when it is drawn. Setting the value to null will remove the clip bounds 14574 * and the view will draw normally, using its full bounds. 14575 * 14576 * @param clipBounds The rectangular area, in the local coordinates of 14577 * this view, to which future drawing operations will be clipped. 14578 */ 14579 public void setClipBounds(Rect clipBounds) { 14580 if (clipBounds != null) { 14581 if (clipBounds.equals(mClipBounds)) { 14582 return; 14583 } 14584 if (mClipBounds == null) { 14585 invalidate(); 14586 mClipBounds = new Rect(clipBounds); 14587 } else { 14588 invalidate(Math.min(mClipBounds.left, clipBounds.left), 14589 Math.min(mClipBounds.top, clipBounds.top), 14590 Math.max(mClipBounds.right, clipBounds.right), 14591 Math.max(mClipBounds.bottom, clipBounds.bottom)); 14592 mClipBounds.set(clipBounds); 14593 } 14594 } else { 14595 if (mClipBounds != null) { 14596 invalidate(); 14597 mClipBounds = null; 14598 } 14599 } 14600 mRenderNode.setClipBounds(mClipBounds); 14601 } 14602 14603 /** 14604 * Returns a copy of the current {@link #setClipBounds(Rect) clipBounds}. 14605 * 14606 * @return A copy of the current clip bounds if clip bounds are set, 14607 * otherwise null. 14608 */ 14609 public Rect getClipBounds() { 14610 return (mClipBounds != null) ? new Rect(mClipBounds) : null; 14611 } 14612 14613 /** 14614 * Utility function, called by draw(canvas, parent, drawingTime) to handle the less common 14615 * case of an active Animation being run on the view. 14616 */ 14617 private boolean drawAnimation(ViewGroup parent, long drawingTime, 14618 Animation a, boolean scalingRequired) { 14619 Transformation invalidationTransform; 14620 final int flags = parent.mGroupFlags; 14621 final boolean initialized = a.isInitialized(); 14622 if (!initialized) { 14623 a.initialize(mRight - mLeft, mBottom - mTop, parent.getWidth(), parent.getHeight()); 14624 a.initializeInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop); 14625 if (mAttachInfo != null) a.setListenerHandler(mAttachInfo.mHandler); 14626 onAnimationStart(); 14627 } 14628 14629 final Transformation t = parent.getChildTransformation(); 14630 boolean more = a.getTransformation(drawingTime, t, 1f); 14631 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 14632 if (parent.mInvalidationTransformation == null) { 14633 parent.mInvalidationTransformation = new Transformation(); 14634 } 14635 invalidationTransform = parent.mInvalidationTransformation; 14636 a.getTransformation(drawingTime, invalidationTransform, 1f); 14637 } else { 14638 invalidationTransform = t; 14639 } 14640 14641 if (more) { 14642 if (!a.willChangeBounds()) { 14643 if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == 14644 ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { 14645 parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; 14646 } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { 14647 // The child need to draw an animation, potentially offscreen, so 14648 // make sure we do not cancel invalidate requests 14649 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14650 parent.invalidate(mLeft, mTop, mRight, mBottom); 14651 } 14652 } else { 14653 if (parent.mInvalidateRegion == null) { 14654 parent.mInvalidateRegion = new RectF(); 14655 } 14656 final RectF region = parent.mInvalidateRegion; 14657 a.getInvalidateRegion(0, 0, mRight - mLeft, mBottom - mTop, region, 14658 invalidationTransform); 14659 14660 // The child need to draw an animation, potentially offscreen, so 14661 // make sure we do not cancel invalidate requests 14662 parent.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 14663 14664 final int left = mLeft + (int) region.left; 14665 final int top = mTop + (int) region.top; 14666 parent.invalidate(left, top, left + (int) (region.width() + .5f), 14667 top + (int) (region.height() + .5f)); 14668 } 14669 } 14670 return more; 14671 } 14672 14673 /** 14674 * This method is called by getDisplayList() when a display list is recorded for a View. 14675 * It pushes any properties to the RenderNode that aren't managed by the RenderNode. 14676 */ 14677 void setDisplayListProperties(RenderNode renderNode) { 14678 if (renderNode != null) { 14679 if ((mPrivateFlags3 & PFLAG3_OUTLINE_INVALID) != 0) { 14680 rebuildOutline(); 14681 mPrivateFlags3 &= ~PFLAG3_OUTLINE_INVALID; 14682 } 14683 renderNode.setHasOverlappingRendering(hasOverlappingRendering()); 14684 if (mParent instanceof ViewGroup) { 14685 renderNode.setClipToBounds( 14686 (((ViewGroup) mParent).mGroupFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0); 14687 } 14688 float alpha = 1; 14689 if (mParent instanceof ViewGroup && (((ViewGroup) mParent).mGroupFlags & 14690 ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14691 ViewGroup parentVG = (ViewGroup) mParent; 14692 final Transformation t = parentVG.getChildTransformation(); 14693 if (parentVG.getChildStaticTransformation(this, t)) { 14694 final int transformType = t.getTransformationType(); 14695 if (transformType != Transformation.TYPE_IDENTITY) { 14696 if ((transformType & Transformation.TYPE_ALPHA) != 0) { 14697 alpha = t.getAlpha(); 14698 } 14699 if ((transformType & Transformation.TYPE_MATRIX) != 0) { 14700 renderNode.setStaticMatrix(t.getMatrix()); 14701 } 14702 } 14703 } 14704 } 14705 if (mTransformationInfo != null) { 14706 alpha *= getFinalAlpha(); 14707 if (alpha < 1) { 14708 final int multipliedAlpha = (int) (255 * alpha); 14709 if (onSetAlpha(multipliedAlpha)) { 14710 alpha = 1; 14711 } 14712 } 14713 renderNode.setAlpha(alpha); 14714 } else if (alpha < 1) { 14715 renderNode.setAlpha(alpha); 14716 } 14717 } 14718 } 14719 14720 /** 14721 * This method is called by ViewGroup.drawChild() to have each child view draw itself. 14722 * This draw() method is an implementation detail and is not intended to be overridden or 14723 * to be called from anywhere else other than ViewGroup.drawChild(). 14724 */ 14725 boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { 14726 boolean usingRenderNodeProperties = mAttachInfo != null && mAttachInfo.mHardwareAccelerated; 14727 boolean more = false; 14728 final boolean childHasIdentityMatrix = hasIdentityMatrix(); 14729 final int flags = parent.mGroupFlags; 14730 14731 if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { 14732 parent.getChildTransformation().clear(); 14733 parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14734 } 14735 14736 Transformation transformToApply = null; 14737 boolean concatMatrix = false; 14738 14739 boolean scalingRequired = false; 14740 boolean caching; 14741 int layerType = getLayerType(); 14742 14743 final boolean hardwareAccelerated = canvas.isHardwareAccelerated(); 14744 if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || 14745 (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { 14746 caching = true; 14747 // Auto-scaled apps are not hw-accelerated, no need to set scaling flag on DisplayList 14748 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 14749 } else { 14750 caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated; 14751 } 14752 14753 final Animation a = getAnimation(); 14754 if (a != null) { 14755 more = drawAnimation(parent, drawingTime, a, scalingRequired); 14756 concatMatrix = a.willChangeTransformationMatrix(); 14757 if (concatMatrix) { 14758 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14759 } 14760 transformToApply = parent.getChildTransformation(); 14761 } else { 14762 if ((mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) != 0) { 14763 // No longer animating: clear out old animation matrix 14764 mRenderNode.setAnimationMatrix(null); 14765 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; 14766 } 14767 if (!usingRenderNodeProperties && 14768 (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 14769 final Transformation t = parent.getChildTransformation(); 14770 final boolean hasTransform = parent.getChildStaticTransformation(this, t); 14771 if (hasTransform) { 14772 final int transformType = t.getTransformationType(); 14773 transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; 14774 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 14775 } 14776 } 14777 } 14778 14779 concatMatrix |= !childHasIdentityMatrix; 14780 14781 // Sets the flag as early as possible to allow draw() implementations 14782 // to call invalidate() successfully when doing animations 14783 mPrivateFlags |= PFLAG_DRAWN; 14784 14785 if (!concatMatrix && 14786 (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | 14787 ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && 14788 canvas.quickReject(mLeft, mTop, mRight, mBottom, Canvas.EdgeType.BW) && 14789 (mPrivateFlags & PFLAG_DRAW_ANIMATION) == 0) { 14790 mPrivateFlags2 |= PFLAG2_VIEW_QUICK_REJECTED; 14791 return more; 14792 } 14793 mPrivateFlags2 &= ~PFLAG2_VIEW_QUICK_REJECTED; 14794 14795 if (hardwareAccelerated) { 14796 // Clear INVALIDATED flag to allow invalidation to occur during rendering, but 14797 // retain the flag's value temporarily in the mRecreateDisplayList flag 14798 mRecreateDisplayList = (mPrivateFlags & PFLAG_INVALIDATED) == PFLAG_INVALIDATED; 14799 mPrivateFlags &= ~PFLAG_INVALIDATED; 14800 } 14801 14802 RenderNode renderNode = null; 14803 Bitmap cache = null; 14804 boolean hasDisplayList = false; 14805 if (caching) { 14806 if (!hardwareAccelerated) { 14807 if (layerType != LAYER_TYPE_NONE) { 14808 layerType = LAYER_TYPE_SOFTWARE; 14809 buildDrawingCache(true); 14810 } 14811 cache = getDrawingCache(true); 14812 } else { 14813 switch (layerType) { 14814 case LAYER_TYPE_SOFTWARE: 14815 if (usingRenderNodeProperties) { 14816 hasDisplayList = canHaveDisplayList(); 14817 } else { 14818 buildDrawingCache(true); 14819 cache = getDrawingCache(true); 14820 } 14821 break; 14822 case LAYER_TYPE_HARDWARE: 14823 if (usingRenderNodeProperties) { 14824 hasDisplayList = canHaveDisplayList(); 14825 } 14826 break; 14827 case LAYER_TYPE_NONE: 14828 // Delay getting the display list until animation-driven alpha values are 14829 // set up and possibly passed on to the view 14830 hasDisplayList = canHaveDisplayList(); 14831 break; 14832 } 14833 } 14834 } 14835 usingRenderNodeProperties &= hasDisplayList; 14836 if (usingRenderNodeProperties) { 14837 renderNode = getDisplayList(); 14838 if (!renderNode.isValid()) { 14839 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14840 // to getDisplayList(), the display list will be marked invalid and we should not 14841 // try to use it again. 14842 renderNode = null; 14843 hasDisplayList = false; 14844 usingRenderNodeProperties = false; 14845 } 14846 } 14847 14848 int sx = 0; 14849 int sy = 0; 14850 if (!hasDisplayList) { 14851 computeScroll(); 14852 sx = mScrollX; 14853 sy = mScrollY; 14854 } 14855 14856 final boolean hasNoCache = cache == null || hasDisplayList; 14857 final boolean offsetForScroll = cache == null && !hasDisplayList && 14858 layerType != LAYER_TYPE_HARDWARE; 14859 14860 int restoreTo = -1; 14861 if (!usingRenderNodeProperties || transformToApply != null) { 14862 restoreTo = canvas.save(); 14863 } 14864 if (offsetForScroll) { 14865 canvas.translate(mLeft - sx, mTop - sy); 14866 } else { 14867 if (!usingRenderNodeProperties) { 14868 canvas.translate(mLeft, mTop); 14869 } 14870 if (scalingRequired) { 14871 if (usingRenderNodeProperties) { 14872 // TODO: Might not need this if we put everything inside the DL 14873 restoreTo = canvas.save(); 14874 } 14875 // mAttachInfo cannot be null, otherwise scalingRequired == false 14876 final float scale = 1.0f / mAttachInfo.mApplicationScale; 14877 canvas.scale(scale, scale); 14878 } 14879 } 14880 14881 float alpha = usingRenderNodeProperties ? 1 : (getAlpha() * getTransitionAlpha()); 14882 if (transformToApply != null || alpha < 1 || !hasIdentityMatrix() || 14883 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14884 if (transformToApply != null || !childHasIdentityMatrix) { 14885 int transX = 0; 14886 int transY = 0; 14887 14888 if (offsetForScroll) { 14889 transX = -sx; 14890 transY = -sy; 14891 } 14892 14893 if (transformToApply != null) { 14894 if (concatMatrix) { 14895 if (usingRenderNodeProperties) { 14896 renderNode.setAnimationMatrix(transformToApply.getMatrix()); 14897 } else { 14898 // Undo the scroll translation, apply the transformation matrix, 14899 // then redo the scroll translate to get the correct result. 14900 canvas.translate(-transX, -transY); 14901 canvas.concat(transformToApply.getMatrix()); 14902 canvas.translate(transX, transY); 14903 } 14904 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14905 } 14906 14907 float transformAlpha = transformToApply.getAlpha(); 14908 if (transformAlpha < 1) { 14909 alpha *= transformAlpha; 14910 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14911 } 14912 } 14913 14914 if (!childHasIdentityMatrix && !usingRenderNodeProperties) { 14915 canvas.translate(-transX, -transY); 14916 canvas.concat(getMatrix()); 14917 canvas.translate(transX, transY); 14918 } 14919 } 14920 14921 // Deal with alpha if it is or used to be <1 14922 if (alpha < 1 || 14923 (mPrivateFlags3 & PFLAG3_VIEW_IS_ANIMATING_ALPHA) == PFLAG3_VIEW_IS_ANIMATING_ALPHA) { 14924 if (alpha < 1) { 14925 mPrivateFlags3 |= PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14926 } else { 14927 mPrivateFlags3 &= ~PFLAG3_VIEW_IS_ANIMATING_ALPHA; 14928 } 14929 parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; 14930 if (hasNoCache) { 14931 final int multipliedAlpha = (int) (255 * alpha); 14932 if (!onSetAlpha(multipliedAlpha)) { 14933 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 14934 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || 14935 layerType != LAYER_TYPE_NONE) { 14936 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 14937 } 14938 if (usingRenderNodeProperties) { 14939 renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha()); 14940 } else if (layerType == LAYER_TYPE_NONE) { 14941 final int scrollX = hasDisplayList ? 0 : sx; 14942 final int scrollY = hasDisplayList ? 0 : sy; 14943 canvas.saveLayerAlpha(scrollX, scrollY, 14944 scrollX + (mRight - mLeft), scrollY + (mBottom - mTop), 14945 multipliedAlpha, layerFlags); 14946 } 14947 } else { 14948 // Alpha is handled by the child directly, clobber the layer's alpha 14949 mPrivateFlags |= PFLAG_ALPHA_SET; 14950 } 14951 } 14952 } 14953 } else if ((mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 14954 onSetAlpha(255); 14955 mPrivateFlags &= ~PFLAG_ALPHA_SET; 14956 } 14957 14958 if (!usingRenderNodeProperties) { 14959 // apply clips directly, since RenderNode won't do it for this draw 14960 if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN 14961 && cache == null) { 14962 if (offsetForScroll) { 14963 canvas.clipRect(sx, sy, sx + (mRight - mLeft), sy + (mBottom - mTop)); 14964 } else { 14965 if (!scalingRequired || cache == null) { 14966 canvas.clipRect(0, 0, mRight - mLeft, mBottom - mTop); 14967 } else { 14968 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 14969 } 14970 } 14971 } 14972 14973 if (mClipBounds != null) { 14974 // clip bounds ignore scroll 14975 canvas.clipRect(mClipBounds); 14976 } 14977 } 14978 14979 14980 14981 if (!usingRenderNodeProperties && hasDisplayList) { 14982 renderNode = getDisplayList(); 14983 if (!renderNode.isValid()) { 14984 // Uncommon, but possible. If a view is removed from the hierarchy during the call 14985 // to getDisplayList(), the display list will be marked invalid and we should not 14986 // try to use it again. 14987 renderNode = null; 14988 hasDisplayList = false; 14989 } 14990 } 14991 14992 if (hasNoCache) { 14993 boolean layerRendered = false; 14994 if (layerType == LAYER_TYPE_HARDWARE && !usingRenderNodeProperties) { 14995 final HardwareLayer layer = getHardwareLayer(); 14996 if (layer != null && layer.isValid()) { 14997 int restoreAlpha = mLayerPaint.getAlpha(); 14998 mLayerPaint.setAlpha((int) (alpha * 255)); 14999 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, mLayerPaint); 15000 mLayerPaint.setAlpha(restoreAlpha); 15001 layerRendered = true; 15002 } else { 15003 final int scrollX = hasDisplayList ? 0 : sx; 15004 final int scrollY = hasDisplayList ? 0 : sy; 15005 canvas.saveLayer(scrollX, scrollY, 15006 scrollX + mRight - mLeft, scrollY + mBottom - mTop, mLayerPaint, 15007 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 15008 } 15009 } 15010 15011 if (!layerRendered) { 15012 if (!hasDisplayList) { 15013 // Fast path for layouts with no backgrounds 15014 if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { 15015 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15016 dispatchDraw(canvas); 15017 if (mOverlay != null && !mOverlay.isEmpty()) { 15018 mOverlay.getOverlayView().draw(canvas); 15019 } 15020 } else { 15021 draw(canvas); 15022 } 15023 drawAccessibilityFocus(canvas); 15024 } else { 15025 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15026 ((HardwareCanvas) canvas).drawRenderNode(renderNode, null, flags); 15027 } 15028 } 15029 } else if (cache != null) { 15030 mPrivateFlags &= ~PFLAG_DIRTY_MASK; 15031 Paint cachePaint; 15032 int restoreAlpha = 0; 15033 15034 if (layerType == LAYER_TYPE_NONE) { 15035 cachePaint = parent.mCachePaint; 15036 if (cachePaint == null) { 15037 cachePaint = new Paint(); 15038 cachePaint.setDither(false); 15039 parent.mCachePaint = cachePaint; 15040 } 15041 } else { 15042 cachePaint = mLayerPaint; 15043 restoreAlpha = mLayerPaint.getAlpha(); 15044 } 15045 cachePaint.setAlpha((int) (alpha * 255)); 15046 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 15047 cachePaint.setAlpha(restoreAlpha); 15048 } 15049 15050 if (restoreTo >= 0) { 15051 canvas.restoreToCount(restoreTo); 15052 } 15053 15054 if (a != null && !more) { 15055 if (!hardwareAccelerated && !a.getFillAfter()) { 15056 onSetAlpha(255); 15057 } 15058 parent.finishAnimatingView(this, a); 15059 } 15060 15061 if (more && hardwareAccelerated) { 15062 if (a.hasAlpha() && (mPrivateFlags & PFLAG_ALPHA_SET) == PFLAG_ALPHA_SET) { 15063 // alpha animations should cause the child to recreate its display list 15064 invalidate(true); 15065 } 15066 } 15067 15068 mRecreateDisplayList = false; 15069 15070 return more; 15071 } 15072 15073 /** 15074 * Manually render this view (and all of its children) to the given Canvas. 15075 * The view must have already done a full layout before this function is 15076 * called. When implementing a view, implement 15077 * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. 15078 * If you do need to override this method, call the superclass version. 15079 * 15080 * @param canvas The Canvas to which the View is rendered. 15081 */ 15082 public void draw(Canvas canvas) { 15083 final int privateFlags = mPrivateFlags; 15084 final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE && 15085 (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState); 15086 mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 15087 15088 /* 15089 * Draw traversal performs several drawing steps which must be executed 15090 * in the appropriate order: 15091 * 15092 * 1. Draw the background 15093 * 2. If necessary, save the canvas' layers to prepare for fading 15094 * 3. Draw view's content 15095 * 4. Draw children 15096 * 5. If necessary, draw the fading edges and restore layers 15097 * 6. Draw decorations (scrollbars for instance) 15098 */ 15099 15100 // Step 1, draw the background, if needed 15101 int saveCount; 15102 15103 if (!dirtyOpaque) { 15104 drawBackground(canvas); 15105 } 15106 15107 // skip step 2 & 5 if possible (common case) 15108 final int viewFlags = mViewFlags; 15109 boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0; 15110 boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; 15111 if (!verticalEdges && !horizontalEdges) { 15112 // Step 3, draw the content 15113 if (!dirtyOpaque) onDraw(canvas); 15114 15115 // Step 4, draw the children 15116 dispatchDraw(canvas); 15117 15118 // Step 6, draw decorations (scrollbars) 15119 onDrawScrollBars(canvas); 15120 15121 if (mOverlay != null && !mOverlay.isEmpty()) { 15122 mOverlay.getOverlayView().dispatchDraw(canvas); 15123 } 15124 15125 // we're done... 15126 return; 15127 } 15128 15129 /* 15130 * Here we do the full fledged routine... 15131 * (this is an uncommon case where speed matters less, 15132 * this is why we repeat some of the tests that have been 15133 * done above) 15134 */ 15135 15136 boolean drawTop = false; 15137 boolean drawBottom = false; 15138 boolean drawLeft = false; 15139 boolean drawRight = false; 15140 15141 float topFadeStrength = 0.0f; 15142 float bottomFadeStrength = 0.0f; 15143 float leftFadeStrength = 0.0f; 15144 float rightFadeStrength = 0.0f; 15145 15146 // Step 2, save the canvas' layers 15147 int paddingLeft = mPaddingLeft; 15148 15149 final boolean offsetRequired = isPaddingOffsetRequired(); 15150 if (offsetRequired) { 15151 paddingLeft += getLeftPaddingOffset(); 15152 } 15153 15154 int left = mScrollX + paddingLeft; 15155 int right = left + mRight - mLeft - mPaddingRight - paddingLeft; 15156 int top = mScrollY + getFadeTop(offsetRequired); 15157 int bottom = top + getFadeHeight(offsetRequired); 15158 15159 if (offsetRequired) { 15160 right += getRightPaddingOffset(); 15161 bottom += getBottomPaddingOffset(); 15162 } 15163 15164 final ScrollabilityCache scrollabilityCache = mScrollCache; 15165 final float fadeHeight = scrollabilityCache.fadingEdgeLength; 15166 int length = (int) fadeHeight; 15167 15168 // clip the fade length if top and bottom fades overlap 15169 // overlapping fades produce odd-looking artifacts 15170 if (verticalEdges && (top + length > bottom - length)) { 15171 length = (bottom - top) / 2; 15172 } 15173 15174 // also clip horizontal fades if necessary 15175 if (horizontalEdges && (left + length > right - length)) { 15176 length = (right - left) / 2; 15177 } 15178 15179 if (verticalEdges) { 15180 topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength())); 15181 drawTop = topFadeStrength * fadeHeight > 1.0f; 15182 bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength())); 15183 drawBottom = bottomFadeStrength * fadeHeight > 1.0f; 15184 } 15185 15186 if (horizontalEdges) { 15187 leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength())); 15188 drawLeft = leftFadeStrength * fadeHeight > 1.0f; 15189 rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength())); 15190 drawRight = rightFadeStrength * fadeHeight > 1.0f; 15191 } 15192 15193 saveCount = canvas.getSaveCount(); 15194 15195 int solidColor = getSolidColor(); 15196 if (solidColor == 0) { 15197 final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 15198 15199 if (drawTop) { 15200 canvas.saveLayer(left, top, right, top + length, null, flags); 15201 } 15202 15203 if (drawBottom) { 15204 canvas.saveLayer(left, bottom - length, right, bottom, null, flags); 15205 } 15206 15207 if (drawLeft) { 15208 canvas.saveLayer(left, top, left + length, bottom, null, flags); 15209 } 15210 15211 if (drawRight) { 15212 canvas.saveLayer(right - length, top, right, bottom, null, flags); 15213 } 15214 } else { 15215 scrollabilityCache.setFadeColor(solidColor); 15216 } 15217 15218 // Step 3, draw the content 15219 if (!dirtyOpaque) onDraw(canvas); 15220 15221 // Step 4, draw the children 15222 dispatchDraw(canvas); 15223 15224 // Step 5, draw the fade effect and restore layers 15225 final Paint p = scrollabilityCache.paint; 15226 final Matrix matrix = scrollabilityCache.matrix; 15227 final Shader fade = scrollabilityCache.shader; 15228 15229 if (drawTop) { 15230 matrix.setScale(1, fadeHeight * topFadeStrength); 15231 matrix.postTranslate(left, top); 15232 fade.setLocalMatrix(matrix); 15233 p.setShader(fade); 15234 canvas.drawRect(left, top, right, top + length, p); 15235 } 15236 15237 if (drawBottom) { 15238 matrix.setScale(1, fadeHeight * bottomFadeStrength); 15239 matrix.postRotate(180); 15240 matrix.postTranslate(left, bottom); 15241 fade.setLocalMatrix(matrix); 15242 p.setShader(fade); 15243 canvas.drawRect(left, bottom - length, right, bottom, p); 15244 } 15245 15246 if (drawLeft) { 15247 matrix.setScale(1, fadeHeight * leftFadeStrength); 15248 matrix.postRotate(-90); 15249 matrix.postTranslate(left, top); 15250 fade.setLocalMatrix(matrix); 15251 p.setShader(fade); 15252 canvas.drawRect(left, top, left + length, bottom, p); 15253 } 15254 15255 if (drawRight) { 15256 matrix.setScale(1, fadeHeight * rightFadeStrength); 15257 matrix.postRotate(90); 15258 matrix.postTranslate(right, top); 15259 fade.setLocalMatrix(matrix); 15260 p.setShader(fade); 15261 canvas.drawRect(right - length, top, right, bottom, p); 15262 } 15263 15264 canvas.restoreToCount(saveCount); 15265 15266 // Step 6, draw decorations (scrollbars) 15267 onDrawScrollBars(canvas); 15268 15269 if (mOverlay != null && !mOverlay.isEmpty()) { 15270 mOverlay.getOverlayView().dispatchDraw(canvas); 15271 } 15272 } 15273 15274 /** 15275 * Draws the accessibility focus rect onto the specified canvas. 15276 * 15277 * @param canvas Canvas on which to draw the focus rect 15278 */ 15279 private void drawAccessibilityFocus(Canvas canvas) { 15280 if (mAttachInfo == null) { 15281 return; 15282 } 15283 15284 final Rect bounds = mAttachInfo.mTmpInvalRect; 15285 final ViewRootImpl viewRoot = getViewRootImpl(); 15286 if (viewRoot == null || viewRoot.getAccessibilityFocusedHost() != this) { 15287 return; 15288 } 15289 15290 final AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 15291 if (!manager.isEnabled() || !manager.isTouchExplorationEnabled()) { 15292 return; 15293 } 15294 15295 final Drawable drawable = viewRoot.getAccessibilityFocusedDrawable(); 15296 if (drawable == null) { 15297 return; 15298 } 15299 15300 final AccessibilityNodeInfo virtualView = viewRoot.getAccessibilityFocusedVirtualView(); 15301 if (virtualView != null) { 15302 virtualView.getBoundsInScreen(bounds); 15303 final int[] offset = mAttachInfo.mTmpLocation; 15304 getLocationOnScreen(offset); 15305 bounds.offset(-offset[0], -offset[1]); 15306 } else { 15307 bounds.set(0, 0, mRight - mLeft, mBottom - mTop); 15308 } 15309 15310 canvas.save(); 15311 canvas.translate(mScrollX, mScrollY); 15312 canvas.clipRect(bounds, Region.Op.REPLACE); 15313 drawable.setBounds(bounds); 15314 drawable.draw(canvas); 15315 canvas.restore(); 15316 } 15317 15318 /** 15319 * Draws the background onto the specified canvas. 15320 * 15321 * @param canvas Canvas on which to draw the background 15322 */ 15323 private void drawBackground(Canvas canvas) { 15324 final Drawable background = mBackground; 15325 if (background == null) { 15326 return; 15327 } 15328 15329 if (mBackgroundSizeChanged) { 15330 background.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 15331 mBackgroundSizeChanged = false; 15332 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15333 } 15334 15335 // Attempt to use a display list if requested. 15336 if (canvas.isHardwareAccelerated() && mAttachInfo != null 15337 && mAttachInfo.mHardwareRenderer != null) { 15338 mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode); 15339 15340 final RenderNode displayList = mBackgroundRenderNode; 15341 if (displayList != null && displayList.isValid()) { 15342 setBackgroundDisplayListProperties(displayList); 15343 ((HardwareCanvas) canvas).drawRenderNode(displayList); 15344 return; 15345 } 15346 } 15347 15348 final int scrollX = mScrollX; 15349 final int scrollY = mScrollY; 15350 if ((scrollX | scrollY) == 0) { 15351 background.draw(canvas); 15352 } else { 15353 canvas.translate(scrollX, scrollY); 15354 background.draw(canvas); 15355 canvas.translate(-scrollX, -scrollY); 15356 } 15357 } 15358 15359 /** 15360 * Set up background drawable display list properties. 15361 * 15362 * @param displayList Valid display list for the background drawable 15363 */ 15364 private void setBackgroundDisplayListProperties(RenderNode displayList) { 15365 displayList.setTranslationX(mScrollX); 15366 displayList.setTranslationY(mScrollY); 15367 } 15368 15369 /** 15370 * Creates a new display list or updates the existing display list for the 15371 * specified Drawable. 15372 * 15373 * @param drawable Drawable for which to create a display list 15374 * @param renderNode Existing RenderNode, or {@code null} 15375 * @return A valid display list for the specified drawable 15376 */ 15377 private RenderNode getDrawableRenderNode(Drawable drawable, RenderNode renderNode) { 15378 if (renderNode == null) { 15379 renderNode = RenderNode.create(drawable.getClass().getName(), this); 15380 } 15381 15382 final Rect bounds = drawable.getBounds(); 15383 final int width = bounds.width(); 15384 final int height = bounds.height(); 15385 final HardwareCanvas canvas = renderNode.start(width, height); 15386 try { 15387 drawable.draw(canvas); 15388 } finally { 15389 renderNode.end(canvas); 15390 } 15391 15392 // Set up drawable properties that are view-independent. 15393 renderNode.setLeftTopRightBottom(bounds.left, bounds.top, bounds.right, bounds.bottom); 15394 renderNode.setProjectBackwards(drawable.isProjected()); 15395 renderNode.setProjectionReceiver(true); 15396 renderNode.setClipToBounds(false); 15397 return renderNode; 15398 } 15399 15400 /** 15401 * Returns the overlay for this view, creating it if it does not yet exist. 15402 * Adding drawables to the overlay will cause them to be displayed whenever 15403 * the view itself is redrawn. Objects in the overlay should be actively 15404 * managed: remove them when they should not be displayed anymore. The 15405 * overlay will always have the same size as its host view. 15406 * 15407 * <p>Note: Overlays do not currently work correctly with {@link 15408 * SurfaceView} or {@link TextureView}; contents in overlays for these 15409 * types of views may not display correctly.</p> 15410 * 15411 * @return The ViewOverlay object for this view. 15412 * @see ViewOverlay 15413 */ 15414 public ViewOverlay getOverlay() { 15415 if (mOverlay == null) { 15416 mOverlay = new ViewOverlay(mContext, this); 15417 } 15418 return mOverlay; 15419 } 15420 15421 /** 15422 * Override this if your view is known to always be drawn on top of a solid color background, 15423 * and needs to draw fading edges. Returning a non-zero color enables the view system to 15424 * optimize the drawing of the fading edges. If you do return a non-zero color, the alpha 15425 * should be set to 0xFF. 15426 * 15427 * @see #setVerticalFadingEdgeEnabled(boolean) 15428 * @see #setHorizontalFadingEdgeEnabled(boolean) 15429 * 15430 * @return The known solid color background for this view, or 0 if the color may vary 15431 */ 15432 @ViewDebug.ExportedProperty(category = "drawing") 15433 public int getSolidColor() { 15434 return 0; 15435 } 15436 15437 /** 15438 * Build a human readable string representation of the specified view flags. 15439 * 15440 * @param flags the view flags to convert to a string 15441 * @return a String representing the supplied flags 15442 */ 15443 private static String printFlags(int flags) { 15444 String output = ""; 15445 int numFlags = 0; 15446 if ((flags & FOCUSABLE_MASK) == FOCUSABLE) { 15447 output += "TAKES_FOCUS"; 15448 numFlags++; 15449 } 15450 15451 switch (flags & VISIBILITY_MASK) { 15452 case INVISIBLE: 15453 if (numFlags > 0) { 15454 output += " "; 15455 } 15456 output += "INVISIBLE"; 15457 // USELESS HERE numFlags++; 15458 break; 15459 case GONE: 15460 if (numFlags > 0) { 15461 output += " "; 15462 } 15463 output += "GONE"; 15464 // USELESS HERE numFlags++; 15465 break; 15466 default: 15467 break; 15468 } 15469 return output; 15470 } 15471 15472 /** 15473 * Build a human readable string representation of the specified private 15474 * view flags. 15475 * 15476 * @param privateFlags the private view flags to convert to a string 15477 * @return a String representing the supplied flags 15478 */ 15479 private static String printPrivateFlags(int privateFlags) { 15480 String output = ""; 15481 int numFlags = 0; 15482 15483 if ((privateFlags & PFLAG_WANTS_FOCUS) == PFLAG_WANTS_FOCUS) { 15484 output += "WANTS_FOCUS"; 15485 numFlags++; 15486 } 15487 15488 if ((privateFlags & PFLAG_FOCUSED) == PFLAG_FOCUSED) { 15489 if (numFlags > 0) { 15490 output += " "; 15491 } 15492 output += "FOCUSED"; 15493 numFlags++; 15494 } 15495 15496 if ((privateFlags & PFLAG_SELECTED) == PFLAG_SELECTED) { 15497 if (numFlags > 0) { 15498 output += " "; 15499 } 15500 output += "SELECTED"; 15501 numFlags++; 15502 } 15503 15504 if ((privateFlags & PFLAG_IS_ROOT_NAMESPACE) == PFLAG_IS_ROOT_NAMESPACE) { 15505 if (numFlags > 0) { 15506 output += " "; 15507 } 15508 output += "IS_ROOT_NAMESPACE"; 15509 numFlags++; 15510 } 15511 15512 if ((privateFlags & PFLAG_HAS_BOUNDS) == PFLAG_HAS_BOUNDS) { 15513 if (numFlags > 0) { 15514 output += " "; 15515 } 15516 output += "HAS_BOUNDS"; 15517 numFlags++; 15518 } 15519 15520 if ((privateFlags & PFLAG_DRAWN) == PFLAG_DRAWN) { 15521 if (numFlags > 0) { 15522 output += " "; 15523 } 15524 output += "DRAWN"; 15525 // USELESS HERE numFlags++; 15526 } 15527 return output; 15528 } 15529 15530 /** 15531 * <p>Indicates whether or not this view's layout will be requested during 15532 * the next hierarchy layout pass.</p> 15533 * 15534 * @return true if the layout will be forced during next layout pass 15535 */ 15536 public boolean isLayoutRequested() { 15537 return (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT; 15538 } 15539 15540 /** 15541 * Return true if o is a ViewGroup that is laying out using optical bounds. 15542 * @hide 15543 */ 15544 public static boolean isLayoutModeOptical(Object o) { 15545 return o instanceof ViewGroup && ((ViewGroup) o).isLayoutModeOptical(); 15546 } 15547 15548 private boolean setOpticalFrame(int left, int top, int right, int bottom) { 15549 Insets parentInsets = mParent instanceof View ? 15550 ((View) mParent).getOpticalInsets() : Insets.NONE; 15551 Insets childInsets = getOpticalInsets(); 15552 return setFrame( 15553 left + parentInsets.left - childInsets.left, 15554 top + parentInsets.top - childInsets.top, 15555 right + parentInsets.left + childInsets.right, 15556 bottom + parentInsets.top + childInsets.bottom); 15557 } 15558 15559 /** 15560 * Assign a size and position to a view and all of its 15561 * descendants 15562 * 15563 * <p>This is the second phase of the layout mechanism. 15564 * (The first is measuring). In this phase, each parent calls 15565 * layout on all of its children to position them. 15566 * This is typically done using the child measurements 15567 * that were stored in the measure pass().</p> 15568 * 15569 * <p>Derived classes should not override this method. 15570 * Derived classes with children should override 15571 * onLayout. In that method, they should 15572 * call layout on each of their children.</p> 15573 * 15574 * @param l Left position, relative to parent 15575 * @param t Top position, relative to parent 15576 * @param r Right position, relative to parent 15577 * @param b Bottom position, relative to parent 15578 */ 15579 @SuppressWarnings({"unchecked"}) 15580 public void layout(int l, int t, int r, int b) { 15581 if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { 15582 onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); 15583 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 15584 } 15585 15586 int oldL = mLeft; 15587 int oldT = mTop; 15588 int oldB = mBottom; 15589 int oldR = mRight; 15590 15591 boolean changed = isLayoutModeOptical(mParent) ? 15592 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); 15593 15594 if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { 15595 onLayout(changed, l, t, r, b); 15596 mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED; 15597 15598 ListenerInfo li = mListenerInfo; 15599 if (li != null && li.mOnLayoutChangeListeners != null) { 15600 ArrayList<OnLayoutChangeListener> listenersCopy = 15601 (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone(); 15602 int numListeners = listenersCopy.size(); 15603 for (int i = 0; i < numListeners; ++i) { 15604 listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); 15605 } 15606 } 15607 } 15608 15609 mPrivateFlags &= ~PFLAG_FORCE_LAYOUT; 15610 mPrivateFlags3 |= PFLAG3_IS_LAID_OUT; 15611 } 15612 15613 /** 15614 * Called from layout when this view should 15615 * assign a size and position to each of its children. 15616 * 15617 * Derived classes with children should override 15618 * this method and call layout on each of 15619 * their children. 15620 * @param changed This is a new size or position for this view 15621 * @param left Left position, relative to parent 15622 * @param top Top position, relative to parent 15623 * @param right Right position, relative to parent 15624 * @param bottom Bottom position, relative to parent 15625 */ 15626 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 15627 } 15628 15629 /** 15630 * Assign a size and position to this view. 15631 * 15632 * This is called from layout. 15633 * 15634 * @param left Left position, relative to parent 15635 * @param top Top position, relative to parent 15636 * @param right Right position, relative to parent 15637 * @param bottom Bottom position, relative to parent 15638 * @return true if the new size and position are different than the 15639 * previous ones 15640 * {@hide} 15641 */ 15642 protected boolean setFrame(int left, int top, int right, int bottom) { 15643 boolean changed = false; 15644 15645 if (DBG) { 15646 Log.d("View", this + " View.setFrame(" + left + "," + top + "," 15647 + right + "," + bottom + ")"); 15648 } 15649 15650 if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) { 15651 changed = true; 15652 15653 // Remember our drawn bit 15654 int drawn = mPrivateFlags & PFLAG_DRAWN; 15655 15656 int oldWidth = mRight - mLeft; 15657 int oldHeight = mBottom - mTop; 15658 int newWidth = right - left; 15659 int newHeight = bottom - top; 15660 boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); 15661 15662 // Invalidate our old position 15663 invalidate(sizeChanged); 15664 15665 mLeft = left; 15666 mTop = top; 15667 mRight = right; 15668 mBottom = bottom; 15669 mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom); 15670 15671 mPrivateFlags |= PFLAG_HAS_BOUNDS; 15672 15673 15674 if (sizeChanged) { 15675 sizeChange(newWidth, newHeight, oldWidth, oldHeight); 15676 } 15677 15678 if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) { 15679 // If we are visible, force the DRAWN bit to on so that 15680 // this invalidate will go through (at least to our parent). 15681 // This is because someone may have invalidated this view 15682 // before this call to setFrame came in, thereby clearing 15683 // the DRAWN bit. 15684 mPrivateFlags |= PFLAG_DRAWN; 15685 invalidate(sizeChanged); 15686 // parent display list may need to be recreated based on a change in the bounds 15687 // of any child 15688 invalidateParentCaches(); 15689 } 15690 15691 // Reset drawn bit to original value (invalidate turns it off) 15692 mPrivateFlags |= drawn; 15693 15694 mBackgroundSizeChanged = true; 15695 15696 notifySubtreeAccessibilityStateChangedIfNeeded(); 15697 } 15698 return changed; 15699 } 15700 15701 private void sizeChange(int newWidth, int newHeight, int oldWidth, int oldHeight) { 15702 onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); 15703 if (mOverlay != null) { 15704 mOverlay.getOverlayView().setRight(newWidth); 15705 mOverlay.getOverlayView().setBottom(newHeight); 15706 } 15707 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15708 } 15709 15710 /** 15711 * Finalize inflating a view from XML. This is called as the last phase 15712 * of inflation, after all child views have been added. 15713 * 15714 * <p>Even if the subclass overrides onFinishInflate, they should always be 15715 * sure to call the super method, so that we get called. 15716 */ 15717 protected void onFinishInflate() { 15718 } 15719 15720 /** 15721 * Returns the resources associated with this view. 15722 * 15723 * @return Resources object. 15724 */ 15725 public Resources getResources() { 15726 return mResources; 15727 } 15728 15729 /** 15730 * Invalidates the specified Drawable. 15731 * 15732 * @param drawable the drawable to invalidate 15733 */ 15734 @Override 15735 public void invalidateDrawable(@NonNull Drawable drawable) { 15736 if (verifyDrawable(drawable)) { 15737 final Rect dirty = drawable.getDirtyBounds(); 15738 final int scrollX = mScrollX; 15739 final int scrollY = mScrollY; 15740 15741 invalidate(dirty.left + scrollX, dirty.top + scrollY, 15742 dirty.right + scrollX, dirty.bottom + scrollY); 15743 15744 mPrivateFlags3 |= PFLAG3_OUTLINE_INVALID; 15745 } 15746 } 15747 15748 /** 15749 * Schedules an action on a drawable to occur at a specified time. 15750 * 15751 * @param who the recipient of the action 15752 * @param what the action to run on the drawable 15753 * @param when the time at which the action must occur. Uses the 15754 * {@link SystemClock#uptimeMillis} timebase. 15755 */ 15756 @Override 15757 public void scheduleDrawable(Drawable who, Runnable what, long when) { 15758 if (verifyDrawable(who) && what != null) { 15759 final long delay = when - SystemClock.uptimeMillis(); 15760 if (mAttachInfo != null) { 15761 mAttachInfo.mViewRootImpl.mChoreographer.postCallbackDelayed( 15762 Choreographer.CALLBACK_ANIMATION, what, who, 15763 Choreographer.subtractFrameDelay(delay)); 15764 } else { 15765 ViewRootImpl.getRunQueue().postDelayed(what, delay); 15766 } 15767 } 15768 } 15769 15770 /** 15771 * Cancels a scheduled action on a drawable. 15772 * 15773 * @param who the recipient of the action 15774 * @param what the action to cancel 15775 */ 15776 @Override 15777 public void unscheduleDrawable(Drawable who, Runnable what) { 15778 if (verifyDrawable(who) && what != null) { 15779 if (mAttachInfo != null) { 15780 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15781 Choreographer.CALLBACK_ANIMATION, what, who); 15782 } 15783 ViewRootImpl.getRunQueue().removeCallbacks(what); 15784 } 15785 } 15786 15787 /** 15788 * Unschedule any events associated with the given Drawable. This can be 15789 * used when selecting a new Drawable into a view, so that the previous 15790 * one is completely unscheduled. 15791 * 15792 * @param who The Drawable to unschedule. 15793 * 15794 * @see #drawableStateChanged 15795 */ 15796 public void unscheduleDrawable(Drawable who) { 15797 if (mAttachInfo != null && who != null) { 15798 mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks( 15799 Choreographer.CALLBACK_ANIMATION, null, who); 15800 } 15801 } 15802 15803 /** 15804 * Resolve the Drawables depending on the layout direction. This is implicitly supposing 15805 * that the View directionality can and will be resolved before its Drawables. 15806 * 15807 * Will call {@link View#onResolveDrawables} when resolution is done. 15808 * 15809 * @hide 15810 */ 15811 protected void resolveDrawables() { 15812 // Drawables resolution may need to happen before resolving the layout direction (which is 15813 // done only during the measure() call). 15814 // If the layout direction is not resolved yet, we cannot resolve the Drawables except in 15815 // one case: when the raw layout direction has not been defined as LAYOUT_DIRECTION_INHERIT. 15816 // So, if the raw layout direction is LAYOUT_DIRECTION_LTR or LAYOUT_DIRECTION_RTL or 15817 // LAYOUT_DIRECTION_LOCALE, we can "cheat" and we don't need to wait for the layout 15818 // direction to be resolved as its resolved value will be the same as its raw value. 15819 if (!isLayoutDirectionResolved() && 15820 getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT) { 15821 return; 15822 } 15823 15824 final int layoutDirection = isLayoutDirectionResolved() ? 15825 getLayoutDirection() : getRawLayoutDirection(); 15826 15827 if (mBackground != null) { 15828 mBackground.setLayoutDirection(layoutDirection); 15829 } 15830 mPrivateFlags2 |= PFLAG2_DRAWABLE_RESOLVED; 15831 onResolveDrawables(layoutDirection); 15832 } 15833 15834 /** 15835 * Called when layout direction has been resolved. 15836 * 15837 * The default implementation does nothing. 15838 * 15839 * @param layoutDirection The resolved layout direction. 15840 * 15841 * @see #LAYOUT_DIRECTION_LTR 15842 * @see #LAYOUT_DIRECTION_RTL 15843 * 15844 * @hide 15845 */ 15846 public void onResolveDrawables(@ResolvedLayoutDir int layoutDirection) { 15847 } 15848 15849 /** 15850 * @hide 15851 */ 15852 protected void resetResolvedDrawables() { 15853 mPrivateFlags2 &= ~PFLAG2_DRAWABLE_RESOLVED; 15854 } 15855 15856 private boolean isDrawablesResolved() { 15857 return (mPrivateFlags2 & PFLAG2_DRAWABLE_RESOLVED) == PFLAG2_DRAWABLE_RESOLVED; 15858 } 15859 15860 /** 15861 * If your view subclass is displaying its own Drawable objects, it should 15862 * override this function and return true for any Drawable it is 15863 * displaying. This allows animations for those drawables to be 15864 * scheduled. 15865 * 15866 * <p>Be sure to call through to the super class when overriding this 15867 * function. 15868 * 15869 * @param who The Drawable to verify. Return true if it is one you are 15870 * displaying, else return the result of calling through to the 15871 * super class. 15872 * 15873 * @return boolean If true than the Drawable is being displayed in the 15874 * view; else false and it is not allowed to animate. 15875 * 15876 * @see #unscheduleDrawable(android.graphics.drawable.Drawable) 15877 * @see #drawableStateChanged() 15878 */ 15879 protected boolean verifyDrawable(Drawable who) { 15880 return who == mBackground; 15881 } 15882 15883 /** 15884 * This function is called whenever the state of the view changes in such 15885 * a way that it impacts the state of drawables being shown. 15886 * <p> 15887 * If the View has a StateListAnimator, it will also be called to run necessary state 15888 * change animations. 15889 * <p> 15890 * Be sure to call through to the superclass when overriding this function. 15891 * 15892 * @see Drawable#setState(int[]) 15893 */ 15894 protected void drawableStateChanged() { 15895 final Drawable d = mBackground; 15896 if (d != null && d.isStateful()) { 15897 d.setState(getDrawableState()); 15898 } 15899 15900 if (mStateListAnimator != null) { 15901 mStateListAnimator.setState(getDrawableState()); 15902 } 15903 } 15904 15905 /** 15906 * This function is called whenever the view hotspot changes and needs to 15907 * be propagated to drawables managed by the view. 15908 * <p> 15909 * Be sure to call through to the superclass when overriding this function. 15910 * 15911 * @param x hotspot x coordinate 15912 * @param y hotspot y coordinate 15913 */ 15914 public void drawableHotspotChanged(float x, float y) { 15915 if (mBackground != null) { 15916 mBackground.setHotspot(x, y); 15917 } 15918 } 15919 15920 /** 15921 * Call this to force a view to update its drawable state. This will cause 15922 * drawableStateChanged to be called on this view. Views that are interested 15923 * in the new state should call getDrawableState. 15924 * 15925 * @see #drawableStateChanged 15926 * @see #getDrawableState 15927 */ 15928 public void refreshDrawableState() { 15929 mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY; 15930 drawableStateChanged(); 15931 15932 ViewParent parent = mParent; 15933 if (parent != null) { 15934 parent.childDrawableStateChanged(this); 15935 } 15936 } 15937 15938 /** 15939 * Return an array of resource IDs of the drawable states representing the 15940 * current state of the view. 15941 * 15942 * @return The current drawable state 15943 * 15944 * @see Drawable#setState(int[]) 15945 * @see #drawableStateChanged() 15946 * @see #onCreateDrawableState(int) 15947 */ 15948 public final int[] getDrawableState() { 15949 if ((mDrawableState != null) && ((mPrivateFlags & PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { 15950 return mDrawableState; 15951 } else { 15952 mDrawableState = onCreateDrawableState(0); 15953 mPrivateFlags &= ~PFLAG_DRAWABLE_STATE_DIRTY; 15954 return mDrawableState; 15955 } 15956 } 15957 15958 /** 15959 * Generate the new {@link android.graphics.drawable.Drawable} state for 15960 * this view. This is called by the view 15961 * system when the cached Drawable state is determined to be invalid. To 15962 * retrieve the current state, you should use {@link #getDrawableState}. 15963 * 15964 * @param extraSpace if non-zero, this is the number of extra entries you 15965 * would like in the returned array in which you can place your own 15966 * states. 15967 * 15968 * @return Returns an array holding the current {@link Drawable} state of 15969 * the view. 15970 * 15971 * @see #mergeDrawableStates(int[], int[]) 15972 */ 15973 protected int[] onCreateDrawableState(int extraSpace) { 15974 if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE && 15975 mParent instanceof View) { 15976 return ((View) mParent).onCreateDrawableState(extraSpace); 15977 } 15978 15979 int[] drawableState; 15980 15981 int privateFlags = mPrivateFlags; 15982 15983 int viewStateIndex = 0; 15984 if ((privateFlags & PFLAG_PRESSED) != 0) viewStateIndex |= VIEW_STATE_PRESSED; 15985 if ((mViewFlags & ENABLED_MASK) == ENABLED) viewStateIndex |= VIEW_STATE_ENABLED; 15986 if (isFocused()) viewStateIndex |= VIEW_STATE_FOCUSED; 15987 if ((privateFlags & PFLAG_SELECTED) != 0) viewStateIndex |= VIEW_STATE_SELECTED; 15988 if (hasWindowFocus()) viewStateIndex |= VIEW_STATE_WINDOW_FOCUSED; 15989 if ((privateFlags & PFLAG_ACTIVATED) != 0) viewStateIndex |= VIEW_STATE_ACTIVATED; 15990 if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && 15991 HardwareRenderer.isAvailable()) { 15992 // This is set if HW acceleration is requested, even if the current 15993 // process doesn't allow it. This is just to allow app preview 15994 // windows to better match their app. 15995 viewStateIndex |= VIEW_STATE_ACCELERATED; 15996 } 15997 if ((privateFlags & PFLAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_HOVERED; 15998 15999 final int privateFlags2 = mPrivateFlags2; 16000 if ((privateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= VIEW_STATE_DRAG_CAN_ACCEPT; 16001 if ((privateFlags2 & PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= VIEW_STATE_DRAG_HOVERED; 16002 16003 drawableState = VIEW_STATE_SETS[viewStateIndex]; 16004 16005 //noinspection ConstantIfStatement 16006 if (false) { 16007 Log.i("View", "drawableStateIndex=" + viewStateIndex); 16008 Log.i("View", toString() 16009 + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) 16010 + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) 16011 + " fo=" + hasFocus() 16012 + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) 16013 + " wf=" + hasWindowFocus() 16014 + ": " + Arrays.toString(drawableState)); 16015 } 16016 16017 if (extraSpace == 0) { 16018 return drawableState; 16019 } 16020 16021 final int[] fullState; 16022 if (drawableState != null) { 16023 fullState = new int[drawableState.length + extraSpace]; 16024 System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); 16025 } else { 16026 fullState = new int[extraSpace]; 16027 } 16028 16029 return fullState; 16030 } 16031 16032 /** 16033 * Merge your own state values in <var>additionalState</var> into the base 16034 * state values <var>baseState</var> that were returned by 16035 * {@link #onCreateDrawableState(int)}. 16036 * 16037 * @param baseState The base state values returned by 16038 * {@link #onCreateDrawableState(int)}, which will be modified to also hold your 16039 * own additional state values. 16040 * 16041 * @param additionalState The additional state values you would like 16042 * added to <var>baseState</var>; this array is not modified. 16043 * 16044 * @return As a convenience, the <var>baseState</var> array you originally 16045 * passed into the function is returned. 16046 * 16047 * @see #onCreateDrawableState(int) 16048 */ 16049 protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) { 16050 final int N = baseState.length; 16051 int i = N - 1; 16052 while (i >= 0 && baseState[i] == 0) { 16053 i--; 16054 } 16055 System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); 16056 return baseState; 16057 } 16058 16059 /** 16060 * Call {@link Drawable#jumpToCurrentState() Drawable.jumpToCurrentState()} 16061 * on all Drawable objects associated with this view. 16062 * <p> 16063 * Also calls {@link StateListAnimator#jumpToCurrentState()} if there is a StateListAnimator 16064 * attached to this view. 16065 */ 16066 public void jumpDrawablesToCurrentState() { 16067 if (mBackground != null) { 16068 mBackground.jumpToCurrentState(); 16069 } 16070 if (mStateListAnimator != null) { 16071 mStateListAnimator.jumpToCurrentState(); 16072 } 16073 } 16074 16075 /** 16076 * Sets the background color for this view. 16077 * @param color the color of the background 16078 */ 16079 @RemotableViewMethod 16080 public void setBackgroundColor(int color) { 16081 if (mBackground instanceof ColorDrawable) { 16082 ((ColorDrawable) mBackground.mutate()).setColor(color); 16083 computeOpaqueFlags(); 16084 mBackgroundResource = 0; 16085 } else { 16086 setBackground(new ColorDrawable(color)); 16087 } 16088 } 16089 16090 /** 16091 * Set the background to a given resource. The resource should refer to 16092 * a Drawable object or 0 to remove the background. 16093 * @param resid The identifier of the resource. 16094 * 16095 * @attr ref android.R.styleable#View_background 16096 */ 16097 @RemotableViewMethod 16098 public void setBackgroundResource(int resid) { 16099 if (resid != 0 && resid == mBackgroundResource) { 16100 return; 16101 } 16102 16103 Drawable d = null; 16104 if (resid != 0) { 16105 d = mContext.getDrawable(resid); 16106 } 16107 setBackground(d); 16108 16109 mBackgroundResource = resid; 16110 } 16111 16112 /** 16113 * Set the background to a given Drawable, or remove the background. If the 16114 * background has padding, this View's padding is set to the background's 16115 * padding. However, when a background is removed, this View's padding isn't 16116 * touched. If setting the padding is desired, please use 16117 * {@link #setPadding(int, int, int, int)}. 16118 * 16119 * @param background The Drawable to use as the background, or null to remove the 16120 * background 16121 */ 16122 public void setBackground(Drawable background) { 16123 //noinspection deprecation 16124 setBackgroundDrawable(background); 16125 } 16126 16127 /** 16128 * @deprecated use {@link #setBackground(Drawable)} instead 16129 */ 16130 @Deprecated 16131 public void setBackgroundDrawable(Drawable background) { 16132 computeOpaqueFlags(); 16133 16134 if (background == mBackground) { 16135 return; 16136 } 16137 16138 boolean requestLayout = false; 16139 16140 mBackgroundResource = 0; 16141 16142 /* 16143 * Regardless of whether we're setting a new background or not, we want 16144 * to clear the previous drawable. 16145 */ 16146 if (mBackground != null) { 16147 mBackground.setCallback(null); 16148 unscheduleDrawable(mBackground); 16149 } 16150 16151 if (background != null) { 16152 Rect padding = sThreadLocal.get(); 16153 if (padding == null) { 16154 padding = new Rect(); 16155 sThreadLocal.set(padding); 16156 } 16157 resetResolvedDrawables(); 16158 background.setLayoutDirection(getLayoutDirection()); 16159 if (background.getPadding(padding)) { 16160 resetResolvedPadding(); 16161 switch (background.getLayoutDirection()) { 16162 case LAYOUT_DIRECTION_RTL: 16163 mUserPaddingLeftInitial = padding.right; 16164 mUserPaddingRightInitial = padding.left; 16165 internalSetPadding(padding.right, padding.top, padding.left, padding.bottom); 16166 break; 16167 case LAYOUT_DIRECTION_LTR: 16168 default: 16169 mUserPaddingLeftInitial = padding.left; 16170 mUserPaddingRightInitial = padding.right; 16171 internalSetPadding(padding.left, padding.top, padding.right, padding.bottom); 16172 } 16173 mLeftPaddingDefined = false; 16174 mRightPaddingDefined = false; 16175 } 16176 16177 // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or 16178 // if it has a different minimum size, we should layout again 16179 if (mBackground == null 16180 || mBackground.getMinimumHeight() != background.getMinimumHeight() 16181 || mBackground.getMinimumWidth() != background.getMinimumWidth()) { 16182 requestLayout = true; 16183 } 16184 16185 background.setCallback(this); 16186 if (background.isStateful()) { 16187 background.setState(getDrawableState()); 16188 } 16189 background.setVisible(getVisibility() == VISIBLE, false); 16190 mBackground = background; 16191 16192 applyBackgroundTint(); 16193 16194 if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { 16195 mPrivateFlags &= ~PFLAG_SKIP_DRAW; 16196 mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; 16197 requestLayout = true; 16198 } 16199 } else { 16200 /* Remove the background */ 16201 mBackground = null; 16202 16203 if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { 16204 /* 16205 * This view ONLY drew the background before and we're removing 16206 * the background, so now it won't draw anything 16207 * (hence we SKIP_DRAW) 16208 */ 16209 mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; 16210 mPrivateFlags |= PFLAG_SKIP_DRAW; 16211 } 16212 16213 /* 16214 * When the background is set, we try to apply its padding to this 16215 * View. When the background is removed, we don't touch this View's 16216 * padding. This is noted in the Javadocs. Hence, we don't need to 16217 * requestLayout(), the invalidate() below is sufficient. 16218 */ 16219 16220 // The old background's minimum size could have affected this 16221 // View's layout, so let's requestLayout 16222 requestLayout = true; 16223 } 16224 16225 computeOpaqueFlags(); 16226 16227 if (requestLayout) { 16228 requestLayout(); 16229 } 16230 16231 mBackgroundSizeChanged = true; 16232 invalidate(true); 16233 } 16234 16235 /** 16236 * Gets the background drawable 16237 * 16238 * @return The drawable used as the background for this view, if any. 16239 * 16240 * @see #setBackground(Drawable) 16241 * 16242 * @attr ref android.R.styleable#View_background 16243 */ 16244 public Drawable getBackground() { 16245 return mBackground; 16246 } 16247 16248 /** 16249 * Applies a tint to the background drawable. Does not modify the current tint 16250 * mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 16251 * <p> 16252 * Subsequent calls to {@link #setBackground(Drawable)} will automatically 16253 * mutate the drawable and apply the specified tint and tint mode using 16254 * {@link Drawable#setTintList(ColorStateList)}. 16255 * 16256 * @param tint the tint to apply, may be {@code null} to clear tint 16257 * 16258 * @attr ref android.R.styleable#View_backgroundTint 16259 * @see #getBackgroundTintList() 16260 * @see Drawable#setTintList(ColorStateList) 16261 */ 16262 public void setBackgroundTintList(@Nullable ColorStateList tint) { 16263 if (mBackgroundTint == null) { 16264 mBackgroundTint = new TintInfo(); 16265 } 16266 mBackgroundTint.mTintList = tint; 16267 mBackgroundTint.mHasTintList = true; 16268 16269 applyBackgroundTint(); 16270 } 16271 16272 /** 16273 * Return the tint applied to the background drawable, if specified. 16274 * 16275 * @return the tint applied to the background drawable 16276 * @attr ref android.R.styleable#View_backgroundTint 16277 * @see #setBackgroundTintList(ColorStateList) 16278 */ 16279 @Nullable 16280 public ColorStateList getBackgroundTintList() { 16281 return mBackgroundTint != null ? mBackgroundTint.mTintList : null; 16282 } 16283 16284 /** 16285 * Specifies the blending mode used to apply the tint specified by 16286 * {@link #setBackgroundTintList(ColorStateList)}} to the background 16287 * drawable. The default mode is {@link PorterDuff.Mode#SRC_IN}. 16288 * 16289 * @param tintMode the blending mode used to apply the tint, may be 16290 * {@code null} to clear tint 16291 * @attr ref android.R.styleable#View_backgroundTintMode 16292 * @see #getBackgroundTintMode() 16293 * @see Drawable#setTintMode(PorterDuff.Mode) 16294 */ 16295 public void setBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) { 16296 if (mBackgroundTint == null) { 16297 mBackgroundTint = new TintInfo(); 16298 } 16299 mBackgroundTint.mTintMode = tintMode; 16300 mBackgroundTint.mHasTintMode = true; 16301 16302 applyBackgroundTint(); 16303 } 16304 16305 /** 16306 * Return the blending mode used to apply the tint to the background 16307 * drawable, if specified. 16308 * 16309 * @return the blending mode used to apply the tint to the background 16310 * drawable 16311 * @attr ref android.R.styleable#View_backgroundTintMode 16312 * @see #setBackgroundTintMode(PorterDuff.Mode) 16313 */ 16314 @Nullable 16315 public PorterDuff.Mode getBackgroundTintMode() { 16316 return mBackgroundTint != null ? mBackgroundTint.mTintMode : null; 16317 } 16318 16319 private void applyBackgroundTint() { 16320 if (mBackground != null && mBackgroundTint != null) { 16321 final TintInfo tintInfo = mBackgroundTint; 16322 if (tintInfo.mHasTintList || tintInfo.mHasTintMode) { 16323 mBackground = mBackground.mutate(); 16324 16325 if (tintInfo.mHasTintList) { 16326 mBackground.setTintList(tintInfo.mTintList); 16327 } 16328 16329 if (tintInfo.mHasTintMode) { 16330 mBackground.setTintMode(tintInfo.mTintMode); 16331 } 16332 } 16333 } 16334 } 16335 16336 /** 16337 * Sets the padding. The view may add on the space required to display 16338 * the scrollbars, depending on the style and visibility of the scrollbars. 16339 * So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop}, 16340 * {@link #getPaddingRight} and {@link #getPaddingBottom} may be different 16341 * from the values set in this call. 16342 * 16343 * @attr ref android.R.styleable#View_padding 16344 * @attr ref android.R.styleable#View_paddingBottom 16345 * @attr ref android.R.styleable#View_paddingLeft 16346 * @attr ref android.R.styleable#View_paddingRight 16347 * @attr ref android.R.styleable#View_paddingTop 16348 * @param left the left padding in pixels 16349 * @param top the top padding in pixels 16350 * @param right the right padding in pixels 16351 * @param bottom the bottom padding in pixels 16352 */ 16353 public void setPadding(int left, int top, int right, int bottom) { 16354 resetResolvedPadding(); 16355 16356 mUserPaddingStart = UNDEFINED_PADDING; 16357 mUserPaddingEnd = UNDEFINED_PADDING; 16358 16359 mUserPaddingLeftInitial = left; 16360 mUserPaddingRightInitial = right; 16361 16362 mLeftPaddingDefined = true; 16363 mRightPaddingDefined = true; 16364 16365 internalSetPadding(left, top, right, bottom); 16366 } 16367 16368 /** 16369 * @hide 16370 */ 16371 protected void internalSetPadding(int left, int top, int right, int bottom) { 16372 mUserPaddingLeft = left; 16373 mUserPaddingRight = right; 16374 mUserPaddingBottom = bottom; 16375 16376 final int viewFlags = mViewFlags; 16377 boolean changed = false; 16378 16379 // Common case is there are no scroll bars. 16380 if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) { 16381 if ((viewFlags & SCROLLBARS_VERTICAL) != 0) { 16382 final int offset = (viewFlags & SCROLLBARS_INSET_MASK) == 0 16383 ? 0 : getVerticalScrollbarWidth(); 16384 switch (mVerticalScrollbarPosition) { 16385 case SCROLLBAR_POSITION_DEFAULT: 16386 if (isLayoutRtl()) { 16387 left += offset; 16388 } else { 16389 right += offset; 16390 } 16391 break; 16392 case SCROLLBAR_POSITION_RIGHT: 16393 right += offset; 16394 break; 16395 case SCROLLBAR_POSITION_LEFT: 16396 left += offset; 16397 break; 16398 } 16399 } 16400 if ((viewFlags & SCROLLBARS_HORIZONTAL) != 0) { 16401 bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0 16402 ? 0 : getHorizontalScrollbarHeight(); 16403 } 16404 } 16405 16406 if (mPaddingLeft != left) { 16407 changed = true; 16408 mPaddingLeft = left; 16409 } 16410 if (mPaddingTop != top) { 16411 changed = true; 16412 mPaddingTop = top; 16413 } 16414 if (mPaddingRight != right) { 16415 changed = true; 16416 mPaddingRight = right; 16417 } 16418 if (mPaddingBottom != bottom) { 16419 changed = true; 16420 mPaddingBottom = bottom; 16421 } 16422 16423 if (changed) { 16424 requestLayout(); 16425 } 16426 } 16427 16428 /** 16429 * Sets the relative padding. The view may add on the space required to display 16430 * the scrollbars, depending on the style and visibility of the scrollbars. 16431 * So the values returned from {@link #getPaddingStart}, {@link #getPaddingTop}, 16432 * {@link #getPaddingEnd} and {@link #getPaddingBottom} may be different 16433 * from the values set in this call. 16434 * 16435 * @attr ref android.R.styleable#View_padding 16436 * @attr ref android.R.styleable#View_paddingBottom 16437 * @attr ref android.R.styleable#View_paddingStart 16438 * @attr ref android.R.styleable#View_paddingEnd 16439 * @attr ref android.R.styleable#View_paddingTop 16440 * @param start the start padding in pixels 16441 * @param top the top padding in pixels 16442 * @param end the end padding in pixels 16443 * @param bottom the bottom padding in pixels 16444 */ 16445 public void setPaddingRelative(int start, int top, int end, int bottom) { 16446 resetResolvedPadding(); 16447 16448 mUserPaddingStart = start; 16449 mUserPaddingEnd = end; 16450 mLeftPaddingDefined = true; 16451 mRightPaddingDefined = true; 16452 16453 switch(getLayoutDirection()) { 16454 case LAYOUT_DIRECTION_RTL: 16455 mUserPaddingLeftInitial = end; 16456 mUserPaddingRightInitial = start; 16457 internalSetPadding(end, top, start, bottom); 16458 break; 16459 case LAYOUT_DIRECTION_LTR: 16460 default: 16461 mUserPaddingLeftInitial = start; 16462 mUserPaddingRightInitial = end; 16463 internalSetPadding(start, top, end, bottom); 16464 } 16465 } 16466 16467 /** 16468 * Returns the top padding of this view. 16469 * 16470 * @return the top padding in pixels 16471 */ 16472 public int getPaddingTop() { 16473 return mPaddingTop; 16474 } 16475 16476 /** 16477 * Returns the bottom padding of this view. If there are inset and enabled 16478 * scrollbars, this value may include the space required to display the 16479 * scrollbars as well. 16480 * 16481 * @return the bottom padding in pixels 16482 */ 16483 public int getPaddingBottom() { 16484 return mPaddingBottom; 16485 } 16486 16487 /** 16488 * Returns the left padding of this view. If there are inset and enabled 16489 * scrollbars, this value may include the space required to display the 16490 * scrollbars as well. 16491 * 16492 * @return the left padding in pixels 16493 */ 16494 public int getPaddingLeft() { 16495 if (!isPaddingResolved()) { 16496 resolvePadding(); 16497 } 16498 return mPaddingLeft; 16499 } 16500 16501 /** 16502 * Returns the start padding of this view depending on its resolved layout direction. 16503 * If there are inset and enabled scrollbars, this value may include the space 16504 * required to display the scrollbars as well. 16505 * 16506 * @return the start padding in pixels 16507 */ 16508 public int getPaddingStart() { 16509 if (!isPaddingResolved()) { 16510 resolvePadding(); 16511 } 16512 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16513 mPaddingRight : mPaddingLeft; 16514 } 16515 16516 /** 16517 * Returns the right padding of this view. If there are inset and enabled 16518 * scrollbars, this value may include the space required to display the 16519 * scrollbars as well. 16520 * 16521 * @return the right padding in pixels 16522 */ 16523 public int getPaddingRight() { 16524 if (!isPaddingResolved()) { 16525 resolvePadding(); 16526 } 16527 return mPaddingRight; 16528 } 16529 16530 /** 16531 * Returns the end padding of this view depending on its resolved layout direction. 16532 * If there are inset and enabled scrollbars, this value may include the space 16533 * required to display the scrollbars as well. 16534 * 16535 * @return the end padding in pixels 16536 */ 16537 public int getPaddingEnd() { 16538 if (!isPaddingResolved()) { 16539 resolvePadding(); 16540 } 16541 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 16542 mPaddingLeft : mPaddingRight; 16543 } 16544 16545 /** 16546 * Return if the padding as been set thru relative values 16547 * {@link #setPaddingRelative(int, int, int, int)} or thru 16548 * @attr ref android.R.styleable#View_paddingStart or 16549 * @attr ref android.R.styleable#View_paddingEnd 16550 * 16551 * @return true if the padding is relative or false if it is not. 16552 */ 16553 public boolean isPaddingRelative() { 16554 return (mUserPaddingStart != UNDEFINED_PADDING || mUserPaddingEnd != UNDEFINED_PADDING); 16555 } 16556 16557 Insets computeOpticalInsets() { 16558 return (mBackground == null) ? Insets.NONE : mBackground.getOpticalInsets(); 16559 } 16560 16561 /** 16562 * @hide 16563 */ 16564 public void resetPaddingToInitialValues() { 16565 if (isRtlCompatibilityMode()) { 16566 mPaddingLeft = mUserPaddingLeftInitial; 16567 mPaddingRight = mUserPaddingRightInitial; 16568 return; 16569 } 16570 if (isLayoutRtl()) { 16571 mPaddingLeft = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingLeftInitial; 16572 mPaddingRight = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingRightInitial; 16573 } else { 16574 mPaddingLeft = (mUserPaddingStart >= 0) ? mUserPaddingStart : mUserPaddingLeftInitial; 16575 mPaddingRight = (mUserPaddingEnd >= 0) ? mUserPaddingEnd : mUserPaddingRightInitial; 16576 } 16577 } 16578 16579 /** 16580 * @hide 16581 */ 16582 public Insets getOpticalInsets() { 16583 if (mLayoutInsets == null) { 16584 mLayoutInsets = computeOpticalInsets(); 16585 } 16586 return mLayoutInsets; 16587 } 16588 16589 /** 16590 * Set this view's optical insets. 16591 * 16592 * <p>This method should be treated similarly to setMeasuredDimension and not as a general 16593 * property. Views that compute their own optical insets should call it as part of measurement. 16594 * This method does not request layout. If you are setting optical insets outside of 16595 * measure/layout itself you will want to call requestLayout() yourself. 16596 * </p> 16597 * @hide 16598 */ 16599 public void setOpticalInsets(Insets insets) { 16600 mLayoutInsets = insets; 16601 } 16602 16603 /** 16604 * Changes the selection state of this view. A view can be selected or not. 16605 * Note that selection is not the same as focus. Views are typically 16606 * selected in the context of an AdapterView like ListView or GridView; 16607 * the selected view is the view that is highlighted. 16608 * 16609 * @param selected true if the view must be selected, false otherwise 16610 */ 16611 public void setSelected(boolean selected) { 16612 //noinspection DoubleNegation 16613 if (((mPrivateFlags & PFLAG_SELECTED) != 0) != selected) { 16614 mPrivateFlags = (mPrivateFlags & ~PFLAG_SELECTED) | (selected ? PFLAG_SELECTED : 0); 16615 if (!selected) resetPressedState(); 16616 invalidate(true); 16617 refreshDrawableState(); 16618 dispatchSetSelected(selected); 16619 notifyViewAccessibilityStateChangedIfNeeded( 16620 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 16621 } 16622 } 16623 16624 /** 16625 * Dispatch setSelected to all of this View's children. 16626 * 16627 * @see #setSelected(boolean) 16628 * 16629 * @param selected The new selected state 16630 */ 16631 protected void dispatchSetSelected(boolean selected) { 16632 } 16633 16634 /** 16635 * Indicates the selection state of this view. 16636 * 16637 * @return true if the view is selected, false otherwise 16638 */ 16639 @ViewDebug.ExportedProperty 16640 public boolean isSelected() { 16641 return (mPrivateFlags & PFLAG_SELECTED) != 0; 16642 } 16643 16644 /** 16645 * Changes the activated state of this view. A view can be activated or not. 16646 * Note that activation is not the same as selection. Selection is 16647 * a transient property, representing the view (hierarchy) the user is 16648 * currently interacting with. Activation is a longer-term state that the 16649 * user can move views in and out of. For example, in a list view with 16650 * single or multiple selection enabled, the views in the current selection 16651 * set are activated. (Um, yeah, we are deeply sorry about the terminology 16652 * here.) The activated state is propagated down to children of the view it 16653 * is set on. 16654 * 16655 * @param activated true if the view must be activated, false otherwise 16656 */ 16657 public void setActivated(boolean activated) { 16658 //noinspection DoubleNegation 16659 if (((mPrivateFlags & PFLAG_ACTIVATED) != 0) != activated) { 16660 mPrivateFlags = (mPrivateFlags & ~PFLAG_ACTIVATED) | (activated ? PFLAG_ACTIVATED : 0); 16661 invalidate(true); 16662 refreshDrawableState(); 16663 dispatchSetActivated(activated); 16664 } 16665 } 16666 16667 /** 16668 * Dispatch setActivated to all of this View's children. 16669 * 16670 * @see #setActivated(boolean) 16671 * 16672 * @param activated The new activated state 16673 */ 16674 protected void dispatchSetActivated(boolean activated) { 16675 } 16676 16677 /** 16678 * Indicates the activation state of this view. 16679 * 16680 * @return true if the view is activated, false otherwise 16681 */ 16682 @ViewDebug.ExportedProperty 16683 public boolean isActivated() { 16684 return (mPrivateFlags & PFLAG_ACTIVATED) != 0; 16685 } 16686 16687 /** 16688 * Returns the ViewTreeObserver for this view's hierarchy. The view tree 16689 * observer can be used to get notifications when global events, like 16690 * layout, happen. 16691 * 16692 * The returned ViewTreeObserver observer is not guaranteed to remain 16693 * valid for the lifetime of this View. If the caller of this method keeps 16694 * a long-lived reference to ViewTreeObserver, it should always check for 16695 * the return value of {@link ViewTreeObserver#isAlive()}. 16696 * 16697 * @return The ViewTreeObserver for this view's hierarchy. 16698 */ 16699 public ViewTreeObserver getViewTreeObserver() { 16700 if (mAttachInfo != null) { 16701 return mAttachInfo.mTreeObserver; 16702 } 16703 if (mFloatingTreeObserver == null) { 16704 mFloatingTreeObserver = new ViewTreeObserver(); 16705 } 16706 return mFloatingTreeObserver; 16707 } 16708 16709 /** 16710 * <p>Finds the topmost view in the current view hierarchy.</p> 16711 * 16712 * @return the topmost view containing this view 16713 */ 16714 public View getRootView() { 16715 if (mAttachInfo != null) { 16716 final View v = mAttachInfo.mRootView; 16717 if (v != null) { 16718 return v; 16719 } 16720 } 16721 16722 View parent = this; 16723 16724 while (parent.mParent != null && parent.mParent instanceof View) { 16725 parent = (View) parent.mParent; 16726 } 16727 16728 return parent; 16729 } 16730 16731 /** 16732 * Transforms a motion event from view-local coordinates to on-screen 16733 * coordinates. 16734 * 16735 * @param ev the view-local motion event 16736 * @return false if the transformation could not be applied 16737 * @hide 16738 */ 16739 public boolean toGlobalMotionEvent(MotionEvent ev) { 16740 final AttachInfo info = mAttachInfo; 16741 if (info == null) { 16742 return false; 16743 } 16744 16745 final Matrix m = info.mTmpMatrix; 16746 m.set(Matrix.IDENTITY_MATRIX); 16747 transformMatrixToGlobal(m); 16748 ev.transform(m); 16749 return true; 16750 } 16751 16752 /** 16753 * Transforms a motion event from on-screen coordinates to view-local 16754 * coordinates. 16755 * 16756 * @param ev the on-screen motion event 16757 * @return false if the transformation could not be applied 16758 * @hide 16759 */ 16760 public boolean toLocalMotionEvent(MotionEvent ev) { 16761 final AttachInfo info = mAttachInfo; 16762 if (info == null) { 16763 return false; 16764 } 16765 16766 final Matrix m = info.mTmpMatrix; 16767 m.set(Matrix.IDENTITY_MATRIX); 16768 transformMatrixToLocal(m); 16769 ev.transform(m); 16770 return true; 16771 } 16772 16773 /** 16774 * Modifies the input matrix such that it maps view-local coordinates to 16775 * on-screen coordinates. 16776 * 16777 * @param m input matrix to modify 16778 * @hide 16779 */ 16780 public void transformMatrixToGlobal(Matrix m) { 16781 final ViewParent parent = mParent; 16782 if (parent instanceof View) { 16783 final View vp = (View) parent; 16784 vp.transformMatrixToGlobal(m); 16785 m.preTranslate(-vp.mScrollX, -vp.mScrollY); 16786 } else if (parent instanceof ViewRootImpl) { 16787 final ViewRootImpl vr = (ViewRootImpl) parent; 16788 vr.transformMatrixToGlobal(m); 16789 m.preTranslate(0, -vr.mCurScrollY); 16790 } 16791 16792 m.preTranslate(mLeft, mTop); 16793 16794 if (!hasIdentityMatrix()) { 16795 m.preConcat(getMatrix()); 16796 } 16797 } 16798 16799 /** 16800 * Modifies the input matrix such that it maps on-screen coordinates to 16801 * view-local coordinates. 16802 * 16803 * @param m input matrix to modify 16804 * @hide 16805 */ 16806 public void transformMatrixToLocal(Matrix m) { 16807 final ViewParent parent = mParent; 16808 if (parent instanceof View) { 16809 final View vp = (View) parent; 16810 vp.transformMatrixToLocal(m); 16811 m.postTranslate(vp.mScrollX, vp.mScrollY); 16812 } else if (parent instanceof ViewRootImpl) { 16813 final ViewRootImpl vr = (ViewRootImpl) parent; 16814 vr.transformMatrixToLocal(m); 16815 m.postTranslate(0, vr.mCurScrollY); 16816 } 16817 16818 m.postTranslate(-mLeft, -mTop); 16819 16820 if (!hasIdentityMatrix()) { 16821 m.postConcat(getInverseMatrix()); 16822 } 16823 } 16824 16825 /** 16826 * @hide 16827 */ 16828 @ViewDebug.ExportedProperty(category = "layout", indexMapping = { 16829 @ViewDebug.IntToString(from = 0, to = "x"), 16830 @ViewDebug.IntToString(from = 1, to = "y") 16831 }) 16832 public int[] getLocationOnScreen() { 16833 int[] location = new int[2]; 16834 getLocationOnScreen(location); 16835 return location; 16836 } 16837 16838 /** 16839 * <p>Computes the coordinates of this view on the screen. The argument 16840 * must be an array of two integers. After the method returns, the array 16841 * contains the x and y location in that order.</p> 16842 * 16843 * @param location an array of two integers in which to hold the coordinates 16844 */ 16845 public void getLocationOnScreen(int[] location) { 16846 getLocationInWindow(location); 16847 16848 final AttachInfo info = mAttachInfo; 16849 if (info != null) { 16850 location[0] += info.mWindowLeft; 16851 location[1] += info.mWindowTop; 16852 } 16853 } 16854 16855 /** 16856 * <p>Computes the coordinates of this view in its window. The argument 16857 * must be an array of two integers. After the method returns, the array 16858 * contains the x and y location in that order.</p> 16859 * 16860 * @param location an array of two integers in which to hold the coordinates 16861 */ 16862 public void getLocationInWindow(int[] location) { 16863 if (location == null || location.length < 2) { 16864 throw new IllegalArgumentException("location must be an array of two integers"); 16865 } 16866 16867 if (mAttachInfo == null) { 16868 // When the view is not attached to a window, this method does not make sense 16869 location[0] = location[1] = 0; 16870 return; 16871 } 16872 16873 float[] position = mAttachInfo.mTmpTransformLocation; 16874 position[0] = position[1] = 0.0f; 16875 16876 if (!hasIdentityMatrix()) { 16877 getMatrix().mapPoints(position); 16878 } 16879 16880 position[0] += mLeft; 16881 position[1] += mTop; 16882 16883 ViewParent viewParent = mParent; 16884 while (viewParent instanceof View) { 16885 final View view = (View) viewParent; 16886 16887 position[0] -= view.mScrollX; 16888 position[1] -= view.mScrollY; 16889 16890 if (!view.hasIdentityMatrix()) { 16891 view.getMatrix().mapPoints(position); 16892 } 16893 16894 position[0] += view.mLeft; 16895 position[1] += view.mTop; 16896 16897 viewParent = view.mParent; 16898 } 16899 16900 if (viewParent instanceof ViewRootImpl) { 16901 // *cough* 16902 final ViewRootImpl vr = (ViewRootImpl) viewParent; 16903 position[1] -= vr.mCurScrollY; 16904 } 16905 16906 location[0] = (int) (position[0] + 0.5f); 16907 location[1] = (int) (position[1] + 0.5f); 16908 } 16909 16910 /** 16911 * {@hide} 16912 * @param id the id of the view to be found 16913 * @return the view of the specified id, null if cannot be found 16914 */ 16915 protected View findViewTraversal(int id) { 16916 if (id == mID) { 16917 return this; 16918 } 16919 return null; 16920 } 16921 16922 /** 16923 * {@hide} 16924 * @param tag the tag of the view to be found 16925 * @return the view of specified tag, null if cannot be found 16926 */ 16927 protected View findViewWithTagTraversal(Object tag) { 16928 if (tag != null && tag.equals(mTag)) { 16929 return this; 16930 } 16931 return null; 16932 } 16933 16934 /** 16935 * {@hide} 16936 * @param predicate The predicate to evaluate. 16937 * @param childToSkip If not null, ignores this child during the recursive traversal. 16938 * @return The first view that matches the predicate or null. 16939 */ 16940 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 16941 if (predicate.apply(this)) { 16942 return this; 16943 } 16944 return null; 16945 } 16946 16947 /** 16948 * Look for a child view with the given id. If this view has the given 16949 * id, return this view. 16950 * 16951 * @param id The id to search for. 16952 * @return The view that has the given id in the hierarchy or null 16953 */ 16954 public final View findViewById(int id) { 16955 if (id < 0) { 16956 return null; 16957 } 16958 return findViewTraversal(id); 16959 } 16960 16961 /** 16962 * Finds a view by its unuque and stable accessibility id. 16963 * 16964 * @param accessibilityId The searched accessibility id. 16965 * @return The found view. 16966 */ 16967 final View findViewByAccessibilityId(int accessibilityId) { 16968 if (accessibilityId < 0) { 16969 return null; 16970 } 16971 return findViewByAccessibilityIdTraversal(accessibilityId); 16972 } 16973 16974 /** 16975 * Performs the traversal to find a view by its unuque and stable accessibility id. 16976 * 16977 * <strong>Note:</strong>This method does not stop at the root namespace 16978 * boundary since the user can touch the screen at an arbitrary location 16979 * potentially crossing the root namespace bounday which will send an 16980 * accessibility event to accessibility services and they should be able 16981 * to obtain the event source. Also accessibility ids are guaranteed to be 16982 * unique in the window. 16983 * 16984 * @param accessibilityId The accessibility id. 16985 * @return The found view. 16986 * 16987 * @hide 16988 */ 16989 public View findViewByAccessibilityIdTraversal(int accessibilityId) { 16990 if (getAccessibilityViewId() == accessibilityId) { 16991 return this; 16992 } 16993 return null; 16994 } 16995 16996 /** 16997 * Look for a child view with the given tag. If this view has the given 16998 * tag, return this view. 16999 * 17000 * @param tag The tag to search for, using "tag.equals(getTag())". 17001 * @return The View that has the given tag in the hierarchy or null 17002 */ 17003 public final View findViewWithTag(Object tag) { 17004 if (tag == null) { 17005 return null; 17006 } 17007 return findViewWithTagTraversal(tag); 17008 } 17009 17010 /** 17011 * {@hide} 17012 * Look for a child view that matches the specified predicate. 17013 * If this view matches the predicate, return this view. 17014 * 17015 * @param predicate The predicate to evaluate. 17016 * @return The first view that matches the predicate or null. 17017 */ 17018 public final View findViewByPredicate(Predicate<View> predicate) { 17019 return findViewByPredicateTraversal(predicate, null); 17020 } 17021 17022 /** 17023 * {@hide} 17024 * Look for a child view that matches the specified predicate, 17025 * starting with the specified view and its descendents and then 17026 * recusively searching the ancestors and siblings of that view 17027 * until this view is reached. 17028 * 17029 * This method is useful in cases where the predicate does not match 17030 * a single unique view (perhaps multiple views use the same id) 17031 * and we are trying to find the view that is "closest" in scope to the 17032 * starting view. 17033 * 17034 * @param start The view to start from. 17035 * @param predicate The predicate to evaluate. 17036 * @return The first view that matches the predicate or null. 17037 */ 17038 public final View findViewByPredicateInsideOut(View start, Predicate<View> predicate) { 17039 View childToSkip = null; 17040 for (;;) { 17041 View view = start.findViewByPredicateTraversal(predicate, childToSkip); 17042 if (view != null || start == this) { 17043 return view; 17044 } 17045 17046 ViewParent parent = start.getParent(); 17047 if (parent == null || !(parent instanceof View)) { 17048 return null; 17049 } 17050 17051 childToSkip = start; 17052 start = (View) parent; 17053 } 17054 } 17055 17056 /** 17057 * Sets the identifier for this view. The identifier does not have to be 17058 * unique in this view's hierarchy. The identifier should be a positive 17059 * number. 17060 * 17061 * @see #NO_ID 17062 * @see #getId() 17063 * @see #findViewById(int) 17064 * 17065 * @param id a number used to identify the view 17066 * 17067 * @attr ref android.R.styleable#View_id 17068 */ 17069 public void setId(int id) { 17070 mID = id; 17071 if (mID == View.NO_ID && mLabelForId != View.NO_ID) { 17072 mID = generateViewId(); 17073 } 17074 } 17075 17076 /** 17077 * {@hide} 17078 * 17079 * @param isRoot true if the view belongs to the root namespace, false 17080 * otherwise 17081 */ 17082 public void setIsRootNamespace(boolean isRoot) { 17083 if (isRoot) { 17084 mPrivateFlags |= PFLAG_IS_ROOT_NAMESPACE; 17085 } else { 17086 mPrivateFlags &= ~PFLAG_IS_ROOT_NAMESPACE; 17087 } 17088 } 17089 17090 /** 17091 * {@hide} 17092 * 17093 * @return true if the view belongs to the root namespace, false otherwise 17094 */ 17095 public boolean isRootNamespace() { 17096 return (mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0; 17097 } 17098 17099 /** 17100 * Returns this view's identifier. 17101 * 17102 * @return a positive integer used to identify the view or {@link #NO_ID} 17103 * if the view has no ID 17104 * 17105 * @see #setId(int) 17106 * @see #findViewById(int) 17107 * @attr ref android.R.styleable#View_id 17108 */ 17109 @ViewDebug.CapturedViewProperty 17110 public int getId() { 17111 return mID; 17112 } 17113 17114 /** 17115 * Returns this view's tag. 17116 * 17117 * @return the Object stored in this view as a tag, or {@code null} if not 17118 * set 17119 * 17120 * @see #setTag(Object) 17121 * @see #getTag(int) 17122 */ 17123 @ViewDebug.ExportedProperty 17124 public Object getTag() { 17125 return mTag; 17126 } 17127 17128 /** 17129 * Sets the tag associated with this view. A tag can be used to mark 17130 * a view in its hierarchy and does not have to be unique within the 17131 * hierarchy. Tags can also be used to store data within a view without 17132 * resorting to another data structure. 17133 * 17134 * @param tag an Object to tag the view with 17135 * 17136 * @see #getTag() 17137 * @see #setTag(int, Object) 17138 */ 17139 public void setTag(final Object tag) { 17140 mTag = tag; 17141 } 17142 17143 /** 17144 * Returns the tag associated with this view and the specified key. 17145 * 17146 * @param key The key identifying the tag 17147 * 17148 * @return the Object stored in this view as a tag, or {@code null} if not 17149 * set 17150 * 17151 * @see #setTag(int, Object) 17152 * @see #getTag() 17153 */ 17154 public Object getTag(int key) { 17155 if (mKeyedTags != null) return mKeyedTags.get(key); 17156 return null; 17157 } 17158 17159 /** 17160 * Sets a tag associated with this view and a key. A tag can be used 17161 * to mark a view in its hierarchy and does not have to be unique within 17162 * the hierarchy. Tags can also be used to store data within a view 17163 * without resorting to another data structure. 17164 * 17165 * The specified key should be an id declared in the resources of the 17166 * application to ensure it is unique (see the <a 17167 * href={@docRoot}guide/topics/resources/more-resources.html#Id">ID resource type</a>). 17168 * Keys identified as belonging to 17169 * the Android framework or not associated with any package will cause 17170 * an {@link IllegalArgumentException} to be thrown. 17171 * 17172 * @param key The key identifying the tag 17173 * @param tag An Object to tag the view with 17174 * 17175 * @throws IllegalArgumentException If they specified key is not valid 17176 * 17177 * @see #setTag(Object) 17178 * @see #getTag(int) 17179 */ 17180 public void setTag(int key, final Object tag) { 17181 // If the package id is 0x00 or 0x01, it's either an undefined package 17182 // or a framework id 17183 if ((key >>> 24) < 2) { 17184 throw new IllegalArgumentException("The key must be an application-specific " 17185 + "resource id."); 17186 } 17187 17188 setKeyedTag(key, tag); 17189 } 17190 17191 /** 17192 * Variation of {@link #setTag(int, Object)} that enforces the key to be a 17193 * framework id. 17194 * 17195 * @hide 17196 */ 17197 public void setTagInternal(int key, Object tag) { 17198 if ((key >>> 24) != 0x1) { 17199 throw new IllegalArgumentException("The key must be a framework-specific " 17200 + "resource id."); 17201 } 17202 17203 setKeyedTag(key, tag); 17204 } 17205 17206 private void setKeyedTag(int key, Object tag) { 17207 if (mKeyedTags == null) { 17208 mKeyedTags = new SparseArray<Object>(2); 17209 } 17210 17211 mKeyedTags.put(key, tag); 17212 } 17213 17214 /** 17215 * Prints information about this view in the log output, with the tag 17216 * {@link #VIEW_LOG_TAG}. 17217 * 17218 * @hide 17219 */ 17220 public void debug() { 17221 debug(0); 17222 } 17223 17224 /** 17225 * Prints information about this view in the log output, with the tag 17226 * {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an 17227 * indentation defined by the <code>depth</code>. 17228 * 17229 * @param depth the indentation level 17230 * 17231 * @hide 17232 */ 17233 protected void debug(int depth) { 17234 String output = debugIndent(depth - 1); 17235 17236 output += "+ " + this; 17237 int id = getId(); 17238 if (id != -1) { 17239 output += " (id=" + id + ")"; 17240 } 17241 Object tag = getTag(); 17242 if (tag != null) { 17243 output += " (tag=" + tag + ")"; 17244 } 17245 Log.d(VIEW_LOG_TAG, output); 17246 17247 if ((mPrivateFlags & PFLAG_FOCUSED) != 0) { 17248 output = debugIndent(depth) + " FOCUSED"; 17249 Log.d(VIEW_LOG_TAG, output); 17250 } 17251 17252 output = debugIndent(depth); 17253 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 17254 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 17255 + "} "; 17256 Log.d(VIEW_LOG_TAG, output); 17257 17258 if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0 17259 || mPaddingBottom != 0) { 17260 output = debugIndent(depth); 17261 output += "padding={" + mPaddingLeft + ", " + mPaddingTop 17262 + ", " + mPaddingRight + ", " + mPaddingBottom + "}"; 17263 Log.d(VIEW_LOG_TAG, output); 17264 } 17265 17266 output = debugIndent(depth); 17267 output += "mMeasureWidth=" + mMeasuredWidth + 17268 " mMeasureHeight=" + mMeasuredHeight; 17269 Log.d(VIEW_LOG_TAG, output); 17270 17271 output = debugIndent(depth); 17272 if (mLayoutParams == null) { 17273 output += "BAD! no layout params"; 17274 } else { 17275 output = mLayoutParams.debug(output); 17276 } 17277 Log.d(VIEW_LOG_TAG, output); 17278 17279 output = debugIndent(depth); 17280 output += "flags={"; 17281 output += View.printFlags(mViewFlags); 17282 output += "}"; 17283 Log.d(VIEW_LOG_TAG, output); 17284 17285 output = debugIndent(depth); 17286 output += "privateFlags={"; 17287 output += View.printPrivateFlags(mPrivateFlags); 17288 output += "}"; 17289 Log.d(VIEW_LOG_TAG, output); 17290 } 17291 17292 /** 17293 * Creates a string of whitespaces used for indentation. 17294 * 17295 * @param depth the indentation level 17296 * @return a String containing (depth * 2 + 3) * 2 white spaces 17297 * 17298 * @hide 17299 */ 17300 protected static String debugIndent(int depth) { 17301 StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2); 17302 for (int i = 0; i < (depth * 2) + 3; i++) { 17303 spaces.append(' ').append(' '); 17304 } 17305 return spaces.toString(); 17306 } 17307 17308 /** 17309 * <p>Return the offset of the widget's text baseline from the widget's top 17310 * boundary. If this widget does not support baseline alignment, this 17311 * method returns -1. </p> 17312 * 17313 * @return the offset of the baseline within the widget's bounds or -1 17314 * if baseline alignment is not supported 17315 */ 17316 @ViewDebug.ExportedProperty(category = "layout") 17317 public int getBaseline() { 17318 return -1; 17319 } 17320 17321 /** 17322 * Returns whether the view hierarchy is currently undergoing a layout pass. This 17323 * information is useful to avoid situations such as calling {@link #requestLayout()} during 17324 * a layout pass. 17325 * 17326 * @return whether the view hierarchy is currently undergoing a layout pass 17327 */ 17328 public boolean isInLayout() { 17329 ViewRootImpl viewRoot = getViewRootImpl(); 17330 return (viewRoot != null && viewRoot.isInLayout()); 17331 } 17332 17333 /** 17334 * Call this when something has changed which has invalidated the 17335 * layout of this view. This will schedule a layout pass of the view 17336 * tree. This should not be called while the view hierarchy is currently in a layout 17337 * pass ({@link #isInLayout()}. If layout is happening, the request may be honored at the 17338 * end of the current layout pass (and then layout will run again) or after the current 17339 * frame is drawn and the next layout occurs. 17340 * 17341 * <p>Subclasses which override this method should call the superclass method to 17342 * handle possible request-during-layout errors correctly.</p> 17343 */ 17344 public void requestLayout() { 17345 if (mMeasureCache != null) mMeasureCache.clear(); 17346 17347 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) { 17348 // Only trigger request-during-layout logic if this is the view requesting it, 17349 // not the views in its parent hierarchy 17350 ViewRootImpl viewRoot = getViewRootImpl(); 17351 if (viewRoot != null && viewRoot.isInLayout()) { 17352 if (!viewRoot.requestLayoutDuringLayout(this)) { 17353 return; 17354 } 17355 } 17356 mAttachInfo.mViewRequestingLayout = this; 17357 } 17358 17359 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17360 mPrivateFlags |= PFLAG_INVALIDATED; 17361 17362 if (mParent != null && !mParent.isLayoutRequested()) { 17363 mParent.requestLayout(); 17364 } 17365 if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) { 17366 mAttachInfo.mViewRequestingLayout = null; 17367 } 17368 } 17369 17370 /** 17371 * Forces this view to be laid out during the next layout pass. 17372 * This method does not call requestLayout() or forceLayout() 17373 * on the parent. 17374 */ 17375 public void forceLayout() { 17376 if (mMeasureCache != null) mMeasureCache.clear(); 17377 17378 mPrivateFlags |= PFLAG_FORCE_LAYOUT; 17379 mPrivateFlags |= PFLAG_INVALIDATED; 17380 } 17381 17382 /** 17383 * <p> 17384 * This is called to find out how big a view should be. The parent 17385 * supplies constraint information in the width and height parameters. 17386 * </p> 17387 * 17388 * <p> 17389 * The actual measurement work of a view is performed in 17390 * {@link #onMeasure(int, int)}, called by this method. Therefore, only 17391 * {@link #onMeasure(int, int)} can and must be overridden by subclasses. 17392 * </p> 17393 * 17394 * 17395 * @param widthMeasureSpec Horizontal space requirements as imposed by the 17396 * parent 17397 * @param heightMeasureSpec Vertical space requirements as imposed by the 17398 * parent 17399 * 17400 * @see #onMeasure(int, int) 17401 */ 17402 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { 17403 boolean optical = isLayoutModeOptical(this); 17404 if (optical != isLayoutModeOptical(mParent)) { 17405 Insets insets = getOpticalInsets(); 17406 int oWidth = insets.left + insets.right; 17407 int oHeight = insets.top + insets.bottom; 17408 widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); 17409 heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); 17410 } 17411 17412 // Suppress sign extension for the low bytes 17413 long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; 17414 if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); 17415 17416 if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || 17417 widthMeasureSpec != mOldWidthMeasureSpec || 17418 heightMeasureSpec != mOldHeightMeasureSpec) { 17419 17420 // first clears the measured dimension flag 17421 mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; 17422 17423 resolveRtlPropertiesIfNeeded(); 17424 17425 int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : 17426 mMeasureCache.indexOfKey(key); 17427 if (cacheIndex < 0 || sIgnoreMeasureCache) { 17428 // measure ourselves, this should set the measured dimension flag back 17429 onMeasure(widthMeasureSpec, heightMeasureSpec); 17430 mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17431 } else { 17432 long value = mMeasureCache.valueAt(cacheIndex); 17433 // Casting a long to int drops the high 32 bits, no mask needed 17434 setMeasuredDimensionRaw((int) (value >> 32), (int) value); 17435 mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; 17436 } 17437 17438 // flag not set, setMeasuredDimension() was not invoked, we raise 17439 // an exception to warn the developer 17440 if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { 17441 throw new IllegalStateException("onMeasure() did not set the" 17442 + " measured dimension by calling" 17443 + " setMeasuredDimension()"); 17444 } 17445 17446 mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; 17447 } 17448 17449 mOldWidthMeasureSpec = widthMeasureSpec; 17450 mOldHeightMeasureSpec = heightMeasureSpec; 17451 17452 mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | 17453 (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension 17454 } 17455 17456 /** 17457 * <p> 17458 * Measure the view and its content to determine the measured width and the 17459 * measured height. This method is invoked by {@link #measure(int, int)} and 17460 * should be overriden by subclasses to provide accurate and efficient 17461 * measurement of their contents. 17462 * </p> 17463 * 17464 * <p> 17465 * <strong>CONTRACT:</strong> When overriding this method, you 17466 * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the 17467 * measured width and height of this view. Failure to do so will trigger an 17468 * <code>IllegalStateException</code>, thrown by 17469 * {@link #measure(int, int)}. Calling the superclass' 17470 * {@link #onMeasure(int, int)} is a valid use. 17471 * </p> 17472 * 17473 * <p> 17474 * The base class implementation of measure defaults to the background size, 17475 * unless a larger size is allowed by the MeasureSpec. Subclasses should 17476 * override {@link #onMeasure(int, int)} to provide better measurements of 17477 * their content. 17478 * </p> 17479 * 17480 * <p> 17481 * If this method is overridden, it is the subclass's responsibility to make 17482 * sure the measured height and width are at least the view's minimum height 17483 * and width ({@link #getSuggestedMinimumHeight()} and 17484 * {@link #getSuggestedMinimumWidth()}). 17485 * </p> 17486 * 17487 * @param widthMeasureSpec horizontal space requirements as imposed by the parent. 17488 * The requirements are encoded with 17489 * {@link android.view.View.MeasureSpec}. 17490 * @param heightMeasureSpec vertical space requirements as imposed by the parent. 17491 * The requirements are encoded with 17492 * {@link android.view.View.MeasureSpec}. 17493 * 17494 * @see #getMeasuredWidth() 17495 * @see #getMeasuredHeight() 17496 * @see #setMeasuredDimension(int, int) 17497 * @see #getSuggestedMinimumHeight() 17498 * @see #getSuggestedMinimumWidth() 17499 * @see android.view.View.MeasureSpec#getMode(int) 17500 * @see android.view.View.MeasureSpec#getSize(int) 17501 */ 17502 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 17503 setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), 17504 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); 17505 } 17506 17507 /** 17508 * <p>This method must be called by {@link #onMeasure(int, int)} to store the 17509 * measured width and measured height. Failing to do so will trigger an 17510 * exception at measurement time.</p> 17511 * 17512 * @param measuredWidth The measured width of this view. May be a complex 17513 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17514 * {@link #MEASURED_STATE_TOO_SMALL}. 17515 * @param measuredHeight The measured height of this view. May be a complex 17516 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17517 * {@link #MEASURED_STATE_TOO_SMALL}. 17518 */ 17519 protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { 17520 boolean optical = isLayoutModeOptical(this); 17521 if (optical != isLayoutModeOptical(mParent)) { 17522 Insets insets = getOpticalInsets(); 17523 int opticalWidth = insets.left + insets.right; 17524 int opticalHeight = insets.top + insets.bottom; 17525 17526 measuredWidth += optical ? opticalWidth : -opticalWidth; 17527 measuredHeight += optical ? opticalHeight : -opticalHeight; 17528 } 17529 setMeasuredDimensionRaw(measuredWidth, measuredHeight); 17530 } 17531 17532 /** 17533 * Sets the measured dimension without extra processing for things like optical bounds. 17534 * Useful for reapplying consistent values that have already been cooked with adjustments 17535 * for optical bounds, etc. such as those from the measurement cache. 17536 * 17537 * @param measuredWidth The measured width of this view. May be a complex 17538 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17539 * {@link #MEASURED_STATE_TOO_SMALL}. 17540 * @param measuredHeight The measured height of this view. May be a complex 17541 * bit mask as defined by {@link #MEASURED_SIZE_MASK} and 17542 * {@link #MEASURED_STATE_TOO_SMALL}. 17543 */ 17544 private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { 17545 mMeasuredWidth = measuredWidth; 17546 mMeasuredHeight = measuredHeight; 17547 17548 mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; 17549 } 17550 17551 /** 17552 * Merge two states as returned by {@link #getMeasuredState()}. 17553 * @param curState The current state as returned from a view or the result 17554 * of combining multiple views. 17555 * @param newState The new view state to combine. 17556 * @return Returns a new integer reflecting the combination of the two 17557 * states. 17558 */ 17559 public static int combineMeasuredStates(int curState, int newState) { 17560 return curState | newState; 17561 } 17562 17563 /** 17564 * Version of {@link #resolveSizeAndState(int, int, int)} 17565 * returning only the {@link #MEASURED_SIZE_MASK} bits of the result. 17566 */ 17567 public static int resolveSize(int size, int measureSpec) { 17568 return resolveSizeAndState(size, measureSpec, 0) & MEASURED_SIZE_MASK; 17569 } 17570 17571 /** 17572 * Utility to reconcile a desired size and state, with constraints imposed 17573 * by a MeasureSpec. Will take the desired size, unless a different size 17574 * is imposed by the constraints. The returned value is a compound integer, 17575 * with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and 17576 * optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting 17577 * size is smaller than the size the view wants to be. 17578 * 17579 * @param size How big the view wants to be 17580 * @param measureSpec Constraints imposed by the parent 17581 * @return Size information bit mask as defined by 17582 * {@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}. 17583 */ 17584 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { 17585 int result = size; 17586 int specMode = MeasureSpec.getMode(measureSpec); 17587 int specSize = MeasureSpec.getSize(measureSpec); 17588 switch (specMode) { 17589 case MeasureSpec.UNSPECIFIED: 17590 result = size; 17591 break; 17592 case MeasureSpec.AT_MOST: 17593 if (specSize < size) { 17594 result = specSize | MEASURED_STATE_TOO_SMALL; 17595 } else { 17596 result = size; 17597 } 17598 break; 17599 case MeasureSpec.EXACTLY: 17600 result = specSize; 17601 break; 17602 } 17603 return result | (childMeasuredState&MEASURED_STATE_MASK); 17604 } 17605 17606 /** 17607 * Utility to return a default size. Uses the supplied size if the 17608 * MeasureSpec imposed no constraints. Will get larger if allowed 17609 * by the MeasureSpec. 17610 * 17611 * @param size Default size for this view 17612 * @param measureSpec Constraints imposed by the parent 17613 * @return The size this view should be. 17614 */ 17615 public static int getDefaultSize(int size, int measureSpec) { 17616 int result = size; 17617 int specMode = MeasureSpec.getMode(measureSpec); 17618 int specSize = MeasureSpec.getSize(measureSpec); 17619 17620 switch (specMode) { 17621 case MeasureSpec.UNSPECIFIED: 17622 result = size; 17623 break; 17624 case MeasureSpec.AT_MOST: 17625 case MeasureSpec.EXACTLY: 17626 result = specSize; 17627 break; 17628 } 17629 return result; 17630 } 17631 17632 /** 17633 * Returns the suggested minimum height that the view should use. This 17634 * returns the maximum of the view's minimum height 17635 * and the background's minimum height 17636 * ({@link android.graphics.drawable.Drawable#getMinimumHeight()}). 17637 * <p> 17638 * When being used in {@link #onMeasure(int, int)}, the caller should still 17639 * ensure the returned height is within the requirements of the parent. 17640 * 17641 * @return The suggested minimum height of the view. 17642 */ 17643 protected int getSuggestedMinimumHeight() { 17644 return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight()); 17645 17646 } 17647 17648 /** 17649 * Returns the suggested minimum width that the view should use. This 17650 * returns the maximum of the view's minimum width) 17651 * and the background's minimum width 17652 * ({@link android.graphics.drawable.Drawable#getMinimumWidth()}). 17653 * <p> 17654 * When being used in {@link #onMeasure(int, int)}, the caller should still 17655 * ensure the returned width is within the requirements of the parent. 17656 * 17657 * @return The suggested minimum width of the view. 17658 */ 17659 protected int getSuggestedMinimumWidth() { 17660 return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); 17661 } 17662 17663 /** 17664 * Returns the minimum height of the view. 17665 * 17666 * @return the minimum height the view will try to be. 17667 * 17668 * @see #setMinimumHeight(int) 17669 * 17670 * @attr ref android.R.styleable#View_minHeight 17671 */ 17672 public int getMinimumHeight() { 17673 return mMinHeight; 17674 } 17675 17676 /** 17677 * Sets the minimum height of the view. It is not guaranteed the view will 17678 * be able to achieve this minimum height (for example, if its parent layout 17679 * constrains it with less available height). 17680 * 17681 * @param minHeight The minimum height the view will try to be. 17682 * 17683 * @see #getMinimumHeight() 17684 * 17685 * @attr ref android.R.styleable#View_minHeight 17686 */ 17687 public void setMinimumHeight(int minHeight) { 17688 mMinHeight = minHeight; 17689 requestLayout(); 17690 } 17691 17692 /** 17693 * Returns the minimum width of the view. 17694 * 17695 * @return the minimum width the view will try to be. 17696 * 17697 * @see #setMinimumWidth(int) 17698 * 17699 * @attr ref android.R.styleable#View_minWidth 17700 */ 17701 public int getMinimumWidth() { 17702 return mMinWidth; 17703 } 17704 17705 /** 17706 * Sets the minimum width of the view. It is not guaranteed the view will 17707 * be able to achieve this minimum width (for example, if its parent layout 17708 * constrains it with less available width). 17709 * 17710 * @param minWidth The minimum width the view will try to be. 17711 * 17712 * @see #getMinimumWidth() 17713 * 17714 * @attr ref android.R.styleable#View_minWidth 17715 */ 17716 public void setMinimumWidth(int minWidth) { 17717 mMinWidth = minWidth; 17718 requestLayout(); 17719 17720 } 17721 17722 /** 17723 * Get the animation currently associated with this view. 17724 * 17725 * @return The animation that is currently playing or 17726 * scheduled to play for this view. 17727 */ 17728 public Animation getAnimation() { 17729 return mCurrentAnimation; 17730 } 17731 17732 /** 17733 * Start the specified animation now. 17734 * 17735 * @param animation the animation to start now 17736 */ 17737 public void startAnimation(Animation animation) { 17738 animation.setStartTime(Animation.START_ON_FIRST_FRAME); 17739 setAnimation(animation); 17740 invalidateParentCaches(); 17741 invalidate(true); 17742 } 17743 17744 /** 17745 * Cancels any animations for this view. 17746 */ 17747 public void clearAnimation() { 17748 if (mCurrentAnimation != null) { 17749 mCurrentAnimation.detach(); 17750 } 17751 mCurrentAnimation = null; 17752 invalidateParentIfNeeded(); 17753 } 17754 17755 /** 17756 * Sets the next animation to play for this view. 17757 * If you want the animation to play immediately, use 17758 * {@link #startAnimation(android.view.animation.Animation)} instead. 17759 * This method provides allows fine-grained 17760 * control over the start time and invalidation, but you 17761 * must make sure that 1) the animation has a start time set, and 17762 * 2) the view's parent (which controls animations on its children) 17763 * will be invalidated when the animation is supposed to 17764 * start. 17765 * 17766 * @param animation The next animation, or null. 17767 */ 17768 public void setAnimation(Animation animation) { 17769 mCurrentAnimation = animation; 17770 17771 if (animation != null) { 17772 // If the screen is off assume the animation start time is now instead of 17773 // the next frame we draw. Keeping the START_ON_FIRST_FRAME start time 17774 // would cause the animation to start when the screen turns back on 17775 if (mAttachInfo != null && mAttachInfo.mDisplayState == Display.STATE_OFF 17776 && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { 17777 animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); 17778 } 17779 animation.reset(); 17780 } 17781 } 17782 17783 /** 17784 * Invoked by a parent ViewGroup to notify the start of the animation 17785 * currently associated with this view. If you override this method, 17786 * always call super.onAnimationStart(); 17787 * 17788 * @see #setAnimation(android.view.animation.Animation) 17789 * @see #getAnimation() 17790 */ 17791 protected void onAnimationStart() { 17792 mPrivateFlags |= PFLAG_ANIMATION_STARTED; 17793 } 17794 17795 /** 17796 * Invoked by a parent ViewGroup to notify the end of the animation 17797 * currently associated with this view. If you override this method, 17798 * always call super.onAnimationEnd(); 17799 * 17800 * @see #setAnimation(android.view.animation.Animation) 17801 * @see #getAnimation() 17802 */ 17803 protected void onAnimationEnd() { 17804 mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 17805 } 17806 17807 /** 17808 * Invoked if there is a Transform that involves alpha. Subclass that can 17809 * draw themselves with the specified alpha should return true, and then 17810 * respect that alpha when their onDraw() is called. If this returns false 17811 * then the view may be redirected to draw into an offscreen buffer to 17812 * fulfill the request, which will look fine, but may be slower than if the 17813 * subclass handles it internally. The default implementation returns false. 17814 * 17815 * @param alpha The alpha (0..255) to apply to the view's drawing 17816 * @return true if the view can draw with the specified alpha. 17817 */ 17818 protected boolean onSetAlpha(int alpha) { 17819 return false; 17820 } 17821 17822 /** 17823 * This is used by the RootView to perform an optimization when 17824 * the view hierarchy contains one or several SurfaceView. 17825 * SurfaceView is always considered transparent, but its children are not, 17826 * therefore all View objects remove themselves from the global transparent 17827 * region (passed as a parameter to this function). 17828 * 17829 * @param region The transparent region for this ViewAncestor (window). 17830 * 17831 * @return Returns true if the effective visibility of the view at this 17832 * point is opaque, regardless of the transparent region; returns false 17833 * if it is possible for underlying windows to be seen behind the view. 17834 * 17835 * {@hide} 17836 */ 17837 public boolean gatherTransparentRegion(Region region) { 17838 final AttachInfo attachInfo = mAttachInfo; 17839 if (region != null && attachInfo != null) { 17840 final int pflags = mPrivateFlags; 17841 if ((pflags & PFLAG_SKIP_DRAW) == 0) { 17842 // The SKIP_DRAW flag IS NOT set, so this view draws. We need to 17843 // remove it from the transparent region. 17844 final int[] location = attachInfo.mTransparentLocation; 17845 getLocationInWindow(location); 17846 region.op(location[0], location[1], location[0] + mRight - mLeft, 17847 location[1] + mBottom - mTop, Region.Op.DIFFERENCE); 17848 } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && 17849 mBackground.getOpacity() != PixelFormat.TRANSPARENT) { 17850 // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable 17851 // exists, so we remove the background drawable's non-transparent 17852 // parts from this transparent region. 17853 applyDrawableToTransparentRegion(mBackground, region); 17854 } 17855 } 17856 return true; 17857 } 17858 17859 /** 17860 * Play a sound effect for this view. 17861 * 17862 * <p>The framework will play sound effects for some built in actions, such as 17863 * clicking, but you may wish to play these effects in your widget, 17864 * for instance, for internal navigation. 17865 * 17866 * <p>The sound effect will only be played if sound effects are enabled by the user, and 17867 * {@link #isSoundEffectsEnabled()} is true. 17868 * 17869 * @param soundConstant One of the constants defined in {@link SoundEffectConstants} 17870 */ 17871 public void playSoundEffect(int soundConstant) { 17872 if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) { 17873 return; 17874 } 17875 mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant); 17876 } 17877 17878 /** 17879 * BZZZTT!!1! 17880 * 17881 * <p>Provide haptic feedback to the user for this view. 17882 * 17883 * <p>The framework will provide haptic feedback for some built in actions, 17884 * such as long presses, but you may wish to provide feedback for your 17885 * own widget. 17886 * 17887 * <p>The feedback will only be performed if 17888 * {@link #isHapticFeedbackEnabled()} is true. 17889 * 17890 * @param feedbackConstant One of the constants defined in 17891 * {@link HapticFeedbackConstants} 17892 */ 17893 public boolean performHapticFeedback(int feedbackConstant) { 17894 return performHapticFeedback(feedbackConstant, 0); 17895 } 17896 17897 /** 17898 * BZZZTT!!1! 17899 * 17900 * <p>Like {@link #performHapticFeedback(int)}, with additional options. 17901 * 17902 * @param feedbackConstant One of the constants defined in 17903 * {@link HapticFeedbackConstants} 17904 * @param flags Additional flags as per {@link HapticFeedbackConstants}. 17905 */ 17906 public boolean performHapticFeedback(int feedbackConstant, int flags) { 17907 if (mAttachInfo == null) { 17908 return false; 17909 } 17910 //noinspection SimplifiableIfStatement 17911 if ((flags & HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0 17912 && !isHapticFeedbackEnabled()) { 17913 return false; 17914 } 17915 return mAttachInfo.mRootCallbacks.performHapticFeedback(feedbackConstant, 17916 (flags & HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0); 17917 } 17918 17919 /** 17920 * Request that the visibility of the status bar or other screen/window 17921 * decorations be changed. 17922 * 17923 * <p>This method is used to put the over device UI into temporary modes 17924 * where the user's attention is focused more on the application content, 17925 * by dimming or hiding surrounding system affordances. This is typically 17926 * used in conjunction with {@link Window#FEATURE_ACTION_BAR_OVERLAY 17927 * Window.FEATURE_ACTION_BAR_OVERLAY}, allowing the applications content 17928 * to be placed behind the action bar (and with these flags other system 17929 * affordances) so that smooth transitions between hiding and showing them 17930 * can be done. 17931 * 17932 * <p>Two representative examples of the use of system UI visibility is 17933 * implementing a content browsing application (like a magazine reader) 17934 * and a video playing application. 17935 * 17936 * <p>The first code shows a typical implementation of a View in a content 17937 * browsing application. In this implementation, the application goes 17938 * into a content-oriented mode by hiding the status bar and action bar, 17939 * and putting the navigation elements into lights out mode. The user can 17940 * then interact with content while in this mode. Such an application should 17941 * provide an easy way for the user to toggle out of the mode (such as to 17942 * check information in the status bar or access notifications). In the 17943 * implementation here, this is done simply by tapping on the content. 17944 * 17945 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/ContentBrowserActivity.java 17946 * content} 17947 * 17948 * <p>This second code sample shows a typical implementation of a View 17949 * in a video playing application. In this situation, while the video is 17950 * playing the application would like to go into a complete full-screen mode, 17951 * to use as much of the display as possible for the video. When in this state 17952 * the user can not interact with the application; the system intercepts 17953 * touching on the screen to pop the UI out of full screen mode. See 17954 * {@link #fitSystemWindows(Rect)} for a sample layout that goes with this code. 17955 * 17956 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/VideoPlayerActivity.java 17957 * content} 17958 * 17959 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17960 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17961 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17962 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17963 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17964 */ 17965 public void setSystemUiVisibility(int visibility) { 17966 if (visibility != mSystemUiVisibility) { 17967 mSystemUiVisibility = visibility; 17968 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 17969 mParent.recomputeViewAttributes(this); 17970 } 17971 } 17972 } 17973 17974 /** 17975 * Returns the last {@link #setSystemUiVisibility(int)} that this view has requested. 17976 * @return Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 17977 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, {@link #SYSTEM_UI_FLAG_FULLSCREEN}, 17978 * {@link #SYSTEM_UI_FLAG_LAYOUT_STABLE}, {@link #SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION}, 17979 * {@link #SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}, {@link #SYSTEM_UI_FLAG_IMMERSIVE}, 17980 * and {@link #SYSTEM_UI_FLAG_IMMERSIVE_STICKY}. 17981 */ 17982 public int getSystemUiVisibility() { 17983 return mSystemUiVisibility; 17984 } 17985 17986 /** 17987 * Returns the current system UI visibility that is currently set for 17988 * the entire window. This is the combination of the 17989 * {@link #setSystemUiVisibility(int)} values supplied by all of the 17990 * views in the window. 17991 */ 17992 public int getWindowSystemUiVisibility() { 17993 return mAttachInfo != null ? mAttachInfo.mSystemUiVisibility : 0; 17994 } 17995 17996 /** 17997 * Override to find out when the window's requested system UI visibility 17998 * has changed, that is the value returned by {@link #getWindowSystemUiVisibility()}. 17999 * This is different from the callbacks received through 18000 * {@link #setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener)} 18001 * in that this is only telling you about the local request of the window, 18002 * not the actual values applied by the system. 18003 */ 18004 public void onWindowSystemUiVisibilityChanged(int visible) { 18005 } 18006 18007 /** 18008 * Dispatch callbacks to {@link #onWindowSystemUiVisibilityChanged(int)} down 18009 * the view hierarchy. 18010 */ 18011 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 18012 onWindowSystemUiVisibilityChanged(visible); 18013 } 18014 18015 /** 18016 * Set a listener to receive callbacks when the visibility of the system bar changes. 18017 * @param l The {@link OnSystemUiVisibilityChangeListener} to receive callbacks. 18018 */ 18019 public void setOnSystemUiVisibilityChangeListener(OnSystemUiVisibilityChangeListener l) { 18020 getListenerInfo().mOnSystemUiVisibilityChangeListener = l; 18021 if (mParent != null && mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 18022 mParent.recomputeViewAttributes(this); 18023 } 18024 } 18025 18026 /** 18027 * Dispatch callbacks to {@link #setOnSystemUiVisibilityChangeListener} down 18028 * the view hierarchy. 18029 */ 18030 public void dispatchSystemUiVisibilityChanged(int visibility) { 18031 ListenerInfo li = mListenerInfo; 18032 if (li != null && li.mOnSystemUiVisibilityChangeListener != null) { 18033 li.mOnSystemUiVisibilityChangeListener.onSystemUiVisibilityChange( 18034 visibility & PUBLIC_STATUS_BAR_VISIBILITY_MASK); 18035 } 18036 } 18037 18038 boolean updateLocalSystemUiVisibility(int localValue, int localChanges) { 18039 int val = (mSystemUiVisibility&~localChanges) | (localValue&localChanges); 18040 if (val != mSystemUiVisibility) { 18041 setSystemUiVisibility(val); 18042 return true; 18043 } 18044 return false; 18045 } 18046 18047 /** @hide */ 18048 public void setDisabledSystemUiVisibility(int flags) { 18049 if (mAttachInfo != null) { 18050 if (mAttachInfo.mDisabledSystemUiVisibility != flags) { 18051 mAttachInfo.mDisabledSystemUiVisibility = flags; 18052 if (mParent != null) { 18053 mParent.recomputeViewAttributes(this); 18054 } 18055 } 18056 } 18057 } 18058 18059 /** 18060 * Creates an image that the system displays during the drag and drop 18061 * operation. This is called a "drag shadow". The default implementation 18062 * for a DragShadowBuilder based on a View returns an image that has exactly the same 18063 * appearance as the given View. The default also positions the center of the drag shadow 18064 * directly under the touch point. If no View is provided (the constructor with no parameters 18065 * is used), and {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} and 18066 * {@link #onDrawShadow(Canvas) onDrawShadow()} are not overriden, then the 18067 * default is an invisible drag shadow. 18068 * <p> 18069 * You are not required to use the View you provide to the constructor as the basis of the 18070 * drag shadow. The {@link #onDrawShadow(Canvas) onDrawShadow()} method allows you to draw 18071 * anything you want as the drag shadow. 18072 * </p> 18073 * <p> 18074 * You pass a DragShadowBuilder object to the system when you start the drag. The system 18075 * calls {@link #onProvideShadowMetrics(Point,Point) onProvideShadowMetrics()} to get the 18076 * size and position of the drag shadow. It uses this data to construct a 18077 * {@link android.graphics.Canvas} object, then it calls {@link #onDrawShadow(Canvas) onDrawShadow()} 18078 * so that your application can draw the shadow image in the Canvas. 18079 * </p> 18080 * 18081 * <div class="special reference"> 18082 * <h3>Developer Guides</h3> 18083 * <p>For a guide to implementing drag and drop features, read the 18084 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 18085 * </div> 18086 */ 18087 public static class DragShadowBuilder { 18088 private final WeakReference<View> mView; 18089 18090 /** 18091 * Constructs a shadow image builder based on a View. By default, the resulting drag 18092 * shadow will have the same appearance and dimensions as the View, with the touch point 18093 * over the center of the View. 18094 * @param view A View. Any View in scope can be used. 18095 */ 18096 public DragShadowBuilder(View view) { 18097 mView = new WeakReference<View>(view); 18098 } 18099 18100 /** 18101 * Construct a shadow builder object with no associated View. This 18102 * constructor variant is only useful when the {@link #onProvideShadowMetrics(Point, Point)} 18103 * and {@link #onDrawShadow(Canvas)} methods are also overridden in order 18104 * to supply the drag shadow's dimensions and appearance without 18105 * reference to any View object. If they are not overridden, then the result is an 18106 * invisible drag shadow. 18107 */ 18108 public DragShadowBuilder() { 18109 mView = new WeakReference<View>(null); 18110 } 18111 18112 /** 18113 * Returns the View object that had been passed to the 18114 * {@link #View.DragShadowBuilder(View)} 18115 * constructor. If that View parameter was {@code null} or if the 18116 * {@link #View.DragShadowBuilder()} 18117 * constructor was used to instantiate the builder object, this method will return 18118 * null. 18119 * 18120 * @return The View object associate with this builder object. 18121 */ 18122 @SuppressWarnings({"JavadocReference"}) 18123 final public View getView() { 18124 return mView.get(); 18125 } 18126 18127 /** 18128 * Provides the metrics for the shadow image. These include the dimensions of 18129 * the shadow image, and the point within that shadow that should 18130 * be centered under the touch location while dragging. 18131 * <p> 18132 * The default implementation sets the dimensions of the shadow to be the 18133 * same as the dimensions of the View itself and centers the shadow under 18134 * the touch point. 18135 * </p> 18136 * 18137 * @param shadowSize A {@link android.graphics.Point} containing the width and height 18138 * of the shadow image. Your application must set {@link android.graphics.Point#x} to the 18139 * desired width and must set {@link android.graphics.Point#y} to the desired height of the 18140 * image. 18141 * 18142 * @param shadowTouchPoint A {@link android.graphics.Point} for the position within the 18143 * shadow image that should be underneath the touch point during the drag and drop 18144 * operation. Your application must set {@link android.graphics.Point#x} to the 18145 * X coordinate and {@link android.graphics.Point#y} to the Y coordinate of this position. 18146 */ 18147 public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) { 18148 final View view = mView.get(); 18149 if (view != null) { 18150 shadowSize.set(view.getWidth(), view.getHeight()); 18151 shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2); 18152 } else { 18153 Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view"); 18154 } 18155 } 18156 18157 /** 18158 * Draws the shadow image. The system creates the {@link android.graphics.Canvas} object 18159 * based on the dimensions it received from the 18160 * {@link #onProvideShadowMetrics(Point, Point)} callback. 18161 * 18162 * @param canvas A {@link android.graphics.Canvas} object in which to draw the shadow image. 18163 */ 18164 public void onDrawShadow(Canvas canvas) { 18165 final View view = mView.get(); 18166 if (view != null) { 18167 view.draw(canvas); 18168 } else { 18169 Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view"); 18170 } 18171 } 18172 } 18173 18174 /** 18175 * Starts a drag and drop operation. When your application calls this method, it passes a 18176 * {@link android.view.View.DragShadowBuilder} object to the system. The 18177 * system calls this object's {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} 18178 * to get metrics for the drag shadow, and then calls the object's 18179 * {@link DragShadowBuilder#onDrawShadow(Canvas)} to draw the drag shadow itself. 18180 * <p> 18181 * Once the system has the drag shadow, it begins the drag and drop operation by sending 18182 * drag events to all the View objects in your application that are currently visible. It does 18183 * this either by calling the View object's drag listener (an implementation of 18184 * {@link android.view.View.OnDragListener#onDrag(View,DragEvent) onDrag()} or by calling the 18185 * View object's {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} method. 18186 * Both are passed a {@link android.view.DragEvent} object that has a 18187 * {@link android.view.DragEvent#getAction()} value of 18188 * {@link android.view.DragEvent#ACTION_DRAG_STARTED}. 18189 * </p> 18190 * <p> 18191 * Your application can invoke startDrag() on any attached View object. The View object does not 18192 * need to be the one used in {@link android.view.View.DragShadowBuilder}, nor does it need to 18193 * be related to the View the user selected for dragging. 18194 * </p> 18195 * @param data A {@link android.content.ClipData} object pointing to the data to be 18196 * transferred by the drag and drop operation. 18197 * @param shadowBuilder A {@link android.view.View.DragShadowBuilder} object for building the 18198 * drag shadow. 18199 * @param myLocalState An {@link java.lang.Object} containing local data about the drag and 18200 * drop operation. This Object is put into every DragEvent object sent by the system during the 18201 * current drag. 18202 * <p> 18203 * myLocalState is a lightweight mechanism for the sending information from the dragged View 18204 * to the target Views. For example, it can contain flags that differentiate between a 18205 * a copy operation and a move operation. 18206 * </p> 18207 * @param flags Flags that control the drag and drop operation. No flags are currently defined, 18208 * so the parameter should be set to 0. 18209 * @return {@code true} if the method completes successfully, or 18210 * {@code false} if it fails anywhere. Returning {@code false} means the system was unable to 18211 * do a drag, and so no drag operation is in progress. 18212 */ 18213 public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder, 18214 Object myLocalState, int flags) { 18215 if (ViewDebug.DEBUG_DRAG) { 18216 Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " flags=" + flags); 18217 } 18218 boolean okay = false; 18219 18220 Point shadowSize = new Point(); 18221 Point shadowTouchPoint = new Point(); 18222 shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint); 18223 18224 if ((shadowSize.x < 0) || (shadowSize.y < 0) || 18225 (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) { 18226 throw new IllegalStateException("Drag shadow dimensions must not be negative"); 18227 } 18228 18229 if (ViewDebug.DEBUG_DRAG) { 18230 Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y 18231 + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y); 18232 } 18233 Surface surface = new Surface(); 18234 try { 18235 IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow, 18236 flags, shadowSize.x, shadowSize.y, surface); 18237 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token 18238 + " surface=" + surface); 18239 if (token != null) { 18240 Canvas canvas = surface.lockCanvas(null); 18241 try { 18242 canvas.drawColor(0, PorterDuff.Mode.CLEAR); 18243 shadowBuilder.onDrawShadow(canvas); 18244 } finally { 18245 surface.unlockCanvasAndPost(canvas); 18246 } 18247 18248 final ViewRootImpl root = getViewRootImpl(); 18249 18250 // Cache the local state object for delivery with DragEvents 18251 root.setLocalDragState(myLocalState); 18252 18253 // repurpose 'shadowSize' for the last touch point 18254 root.getLastTouchPoint(shadowSize); 18255 18256 okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token, 18257 shadowSize.x, shadowSize.y, 18258 shadowTouchPoint.x, shadowTouchPoint.y, data); 18259 if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay); 18260 18261 // Off and running! Release our local surface instance; the drag 18262 // shadow surface is now managed by the system process. 18263 surface.release(); 18264 } 18265 } catch (Exception e) { 18266 Log.e(VIEW_LOG_TAG, "Unable to initiate drag", e); 18267 surface.destroy(); 18268 } 18269 18270 return okay; 18271 } 18272 18273 /** 18274 * Handles drag events sent by the system following a call to 18275 * {@link android.view.View#startDrag(ClipData,DragShadowBuilder,Object,int) startDrag()}. 18276 *<p> 18277 * When the system calls this method, it passes a 18278 * {@link android.view.DragEvent} object. A call to 18279 * {@link android.view.DragEvent#getAction()} returns one of the action type constants defined 18280 * in DragEvent. The method uses these to determine what is happening in the drag and drop 18281 * operation. 18282 * @param event The {@link android.view.DragEvent} sent by the system. 18283 * The {@link android.view.DragEvent#getAction()} method returns an action type constant defined 18284 * in DragEvent, indicating the type of drag event represented by this object. 18285 * @return {@code true} if the method was successful, otherwise {@code false}. 18286 * <p> 18287 * The method should return {@code true} in response to an action type of 18288 * {@link android.view.DragEvent#ACTION_DRAG_STARTED} to receive drag events for the current 18289 * operation. 18290 * </p> 18291 * <p> 18292 * The method should also return {@code true} in response to an action type of 18293 * {@link android.view.DragEvent#ACTION_DROP} if it consumed the drop, or 18294 * {@code false} if it didn't. 18295 * </p> 18296 */ 18297 public boolean onDragEvent(DragEvent event) { 18298 return false; 18299 } 18300 18301 /** 18302 * Detects if this View is enabled and has a drag event listener. 18303 * If both are true, then it calls the drag event listener with the 18304 * {@link android.view.DragEvent} it received. If the drag event listener returns 18305 * {@code true}, then dispatchDragEvent() returns {@code true}. 18306 * <p> 18307 * For all other cases, the method calls the 18308 * {@link android.view.View#onDragEvent(DragEvent) onDragEvent()} drag event handler 18309 * method and returns its result. 18310 * </p> 18311 * <p> 18312 * This ensures that a drag event is always consumed, even if the View does not have a drag 18313 * event listener. However, if the View has a listener and the listener returns true, then 18314 * onDragEvent() is not called. 18315 * </p> 18316 */ 18317 public boolean dispatchDragEvent(DragEvent event) { 18318 ListenerInfo li = mListenerInfo; 18319 //noinspection SimplifiableIfStatement 18320 if (li != null && li.mOnDragListener != null && (mViewFlags & ENABLED_MASK) == ENABLED 18321 && li.mOnDragListener.onDrag(this, event)) { 18322 return true; 18323 } 18324 return onDragEvent(event); 18325 } 18326 18327 boolean canAcceptDrag() { 18328 return (mPrivateFlags2 & PFLAG2_DRAG_CAN_ACCEPT) != 0; 18329 } 18330 18331 /** 18332 * This needs to be a better API (NOT ON VIEW) before it is exposed. If 18333 * it is ever exposed at all. 18334 * @hide 18335 */ 18336 public void onCloseSystemDialogs(String reason) { 18337 } 18338 18339 /** 18340 * Given a Drawable whose bounds have been set to draw into this view, 18341 * update a Region being computed for 18342 * {@link #gatherTransparentRegion(android.graphics.Region)} so 18343 * that any non-transparent parts of the Drawable are removed from the 18344 * given transparent region. 18345 * 18346 * @param dr The Drawable whose transparency is to be applied to the region. 18347 * @param region A Region holding the current transparency information, 18348 * where any parts of the region that are set are considered to be 18349 * transparent. On return, this region will be modified to have the 18350 * transparency information reduced by the corresponding parts of the 18351 * Drawable that are not transparent. 18352 * {@hide} 18353 */ 18354 public void applyDrawableToTransparentRegion(Drawable dr, Region region) { 18355 if (DBG) { 18356 Log.i("View", "Getting transparent region for: " + this); 18357 } 18358 final Region r = dr.getTransparentRegion(); 18359 final Rect db = dr.getBounds(); 18360 final AttachInfo attachInfo = mAttachInfo; 18361 if (r != null && attachInfo != null) { 18362 final int w = getRight()-getLeft(); 18363 final int h = getBottom()-getTop(); 18364 if (db.left > 0) { 18365 //Log.i("VIEW", "Drawable left " + db.left + " > view 0"); 18366 r.op(0, 0, db.left, h, Region.Op.UNION); 18367 } 18368 if (db.right < w) { 18369 //Log.i("VIEW", "Drawable right " + db.right + " < view " + w); 18370 r.op(db.right, 0, w, h, Region.Op.UNION); 18371 } 18372 if (db.top > 0) { 18373 //Log.i("VIEW", "Drawable top " + db.top + " > view 0"); 18374 r.op(0, 0, w, db.top, Region.Op.UNION); 18375 } 18376 if (db.bottom < h) { 18377 //Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h); 18378 r.op(0, db.bottom, w, h, Region.Op.UNION); 18379 } 18380 final int[] location = attachInfo.mTransparentLocation; 18381 getLocationInWindow(location); 18382 r.translate(location[0], location[1]); 18383 region.op(r, Region.Op.INTERSECT); 18384 } else { 18385 region.op(db, Region.Op.DIFFERENCE); 18386 } 18387 } 18388 18389 private void checkForLongClick(int delayOffset) { 18390 if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) { 18391 mHasPerformedLongPress = false; 18392 18393 if (mPendingCheckForLongPress == null) { 18394 mPendingCheckForLongPress = new CheckForLongPress(); 18395 } 18396 mPendingCheckForLongPress.rememberWindowAttachCount(); 18397 postDelayed(mPendingCheckForLongPress, 18398 ViewConfiguration.getLongPressTimeout() - delayOffset); 18399 } 18400 } 18401 18402 /** 18403 * Inflate a view from an XML resource. This convenience method wraps the {@link 18404 * LayoutInflater} class, which provides a full range of options for view inflation. 18405 * 18406 * @param context The Context object for your activity or application. 18407 * @param resource The resource ID to inflate 18408 * @param root A view group that will be the parent. Used to properly inflate the 18409 * layout_* parameters. 18410 * @see LayoutInflater 18411 */ 18412 public static View inflate(Context context, int resource, ViewGroup root) { 18413 LayoutInflater factory = LayoutInflater.from(context); 18414 return factory.inflate(resource, root); 18415 } 18416 18417 /** 18418 * Scroll the view with standard behavior for scrolling beyond the normal 18419 * content boundaries. Views that call this method should override 18420 * {@link #onOverScrolled(int, int, boolean, boolean)} to respond to the 18421 * results of an over-scroll operation. 18422 * 18423 * Views can use this method to handle any touch or fling-based scrolling. 18424 * 18425 * @param deltaX Change in X in pixels 18426 * @param deltaY Change in Y in pixels 18427 * @param scrollX Current X scroll value in pixels before applying deltaX 18428 * @param scrollY Current Y scroll value in pixels before applying deltaY 18429 * @param scrollRangeX Maximum content scroll range along the X axis 18430 * @param scrollRangeY Maximum content scroll range along the Y axis 18431 * @param maxOverScrollX Number of pixels to overscroll by in either direction 18432 * along the X axis. 18433 * @param maxOverScrollY Number of pixels to overscroll by in either direction 18434 * along the Y axis. 18435 * @param isTouchEvent true if this scroll operation is the result of a touch event. 18436 * @return true if scrolling was clamped to an over-scroll boundary along either 18437 * axis, false otherwise. 18438 */ 18439 @SuppressWarnings({"UnusedParameters"}) 18440 protected boolean overScrollBy(int deltaX, int deltaY, 18441 int scrollX, int scrollY, 18442 int scrollRangeX, int scrollRangeY, 18443 int maxOverScrollX, int maxOverScrollY, 18444 boolean isTouchEvent) { 18445 final int overScrollMode = mOverScrollMode; 18446 final boolean canScrollHorizontal = 18447 computeHorizontalScrollRange() > computeHorizontalScrollExtent(); 18448 final boolean canScrollVertical = 18449 computeVerticalScrollRange() > computeVerticalScrollExtent(); 18450 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS || 18451 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); 18452 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS || 18453 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); 18454 18455 int newScrollX = scrollX + deltaX; 18456 if (!overScrollHorizontal) { 18457 maxOverScrollX = 0; 18458 } 18459 18460 int newScrollY = scrollY + deltaY; 18461 if (!overScrollVertical) { 18462 maxOverScrollY = 0; 18463 } 18464 18465 // Clamp values if at the limits and record 18466 final int left = -maxOverScrollX; 18467 final int right = maxOverScrollX + scrollRangeX; 18468 final int top = -maxOverScrollY; 18469 final int bottom = maxOverScrollY + scrollRangeY; 18470 18471 boolean clampedX = false; 18472 if (newScrollX > right) { 18473 newScrollX = right; 18474 clampedX = true; 18475 } else if (newScrollX < left) { 18476 newScrollX = left; 18477 clampedX = true; 18478 } 18479 18480 boolean clampedY = false; 18481 if (newScrollY > bottom) { 18482 newScrollY = bottom; 18483 clampedY = true; 18484 } else if (newScrollY < top) { 18485 newScrollY = top; 18486 clampedY = true; 18487 } 18488 18489 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); 18490 18491 return clampedX || clampedY; 18492 } 18493 18494 /** 18495 * Called by {@link #overScrollBy(int, int, int, int, int, int, int, int, boolean)} to 18496 * respond to the results of an over-scroll operation. 18497 * 18498 * @param scrollX New X scroll value in pixels 18499 * @param scrollY New Y scroll value in pixels 18500 * @param clampedX True if scrollX was clamped to an over-scroll boundary 18501 * @param clampedY True if scrollY was clamped to an over-scroll boundary 18502 */ 18503 protected void onOverScrolled(int scrollX, int scrollY, 18504 boolean clampedX, boolean clampedY) { 18505 // Intentionally empty. 18506 } 18507 18508 /** 18509 * Returns the over-scroll mode for this view. The result will be 18510 * one of {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18511 * (allow over-scrolling only if the view content is larger than the container), 18512 * or {@link #OVER_SCROLL_NEVER}. 18513 * 18514 * @return This view's over-scroll mode. 18515 */ 18516 public int getOverScrollMode() { 18517 return mOverScrollMode; 18518 } 18519 18520 /** 18521 * Set the over-scroll mode for this view. Valid over-scroll modes are 18522 * {@link #OVER_SCROLL_ALWAYS} (default), {@link #OVER_SCROLL_IF_CONTENT_SCROLLS} 18523 * (allow over-scrolling only if the view content is larger than the container), 18524 * or {@link #OVER_SCROLL_NEVER}. 18525 * 18526 * Setting the over-scroll mode of a view will have an effect only if the 18527 * view is capable of scrolling. 18528 * 18529 * @param overScrollMode The new over-scroll mode for this view. 18530 */ 18531 public void setOverScrollMode(int overScrollMode) { 18532 if (overScrollMode != OVER_SCROLL_ALWAYS && 18533 overScrollMode != OVER_SCROLL_IF_CONTENT_SCROLLS && 18534 overScrollMode != OVER_SCROLL_NEVER) { 18535 throw new IllegalArgumentException("Invalid overscroll mode " + overScrollMode); 18536 } 18537 mOverScrollMode = overScrollMode; 18538 } 18539 18540 /** 18541 * Enable or disable nested scrolling for this view. 18542 * 18543 * <p>If this property is set to true the view will be permitted to initiate nested 18544 * scrolling operations with a compatible parent view in the current hierarchy. If this 18545 * view does not implement nested scrolling this will have no effect. Disabling nested scrolling 18546 * while a nested scroll is in progress has the effect of {@link #stopNestedScroll() stopping} 18547 * the nested scroll.</p> 18548 * 18549 * @param enabled true to enable nested scrolling, false to disable 18550 * 18551 * @see #isNestedScrollingEnabled() 18552 */ 18553 public void setNestedScrollingEnabled(boolean enabled) { 18554 if (enabled) { 18555 mPrivateFlags3 |= PFLAG3_NESTED_SCROLLING_ENABLED; 18556 } else { 18557 stopNestedScroll(); 18558 mPrivateFlags3 &= ~PFLAG3_NESTED_SCROLLING_ENABLED; 18559 } 18560 } 18561 18562 /** 18563 * Returns true if nested scrolling is enabled for this view. 18564 * 18565 * <p>If nested scrolling is enabled and this View class implementation supports it, 18566 * this view will act as a nested scrolling child view when applicable, forwarding data 18567 * about the scroll operation in progress to a compatible and cooperating nested scrolling 18568 * parent.</p> 18569 * 18570 * @return true if nested scrolling is enabled 18571 * 18572 * @see #setNestedScrollingEnabled(boolean) 18573 */ 18574 public boolean isNestedScrollingEnabled() { 18575 return (mPrivateFlags3 & PFLAG3_NESTED_SCROLLING_ENABLED) == 18576 PFLAG3_NESTED_SCROLLING_ENABLED; 18577 } 18578 18579 /** 18580 * Begin a nestable scroll operation along the given axes. 18581 * 18582 * <p>A view starting a nested scroll promises to abide by the following contract:</p> 18583 * 18584 * <p>The view will call startNestedScroll upon initiating a scroll operation. In the case 18585 * of a touch scroll this corresponds to the initial {@link MotionEvent#ACTION_DOWN}. 18586 * In the case of touch scrolling the nested scroll will be terminated automatically in 18587 * the same manner as {@link ViewParent#requestDisallowInterceptTouchEvent(boolean)}. 18588 * In the event of programmatic scrolling the caller must explicitly call 18589 * {@link #stopNestedScroll()} to indicate the end of the nested scroll.</p> 18590 * 18591 * <p>If <code>startNestedScroll</code> returns true, a cooperative parent was found. 18592 * If it returns false the caller may ignore the rest of this contract until the next scroll. 18593 * Calling startNestedScroll while a nested scroll is already in progress will return true.</p> 18594 * 18595 * <p>At each incremental step of the scroll the caller should invoke 18596 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} 18597 * once it has calculated the requested scrolling delta. If it returns true the nested scrolling 18598 * parent at least partially consumed the scroll and the caller should adjust the amount it 18599 * scrolls by.</p> 18600 * 18601 * <p>After applying the remainder of the scroll delta the caller should invoke 18602 * {@link #dispatchNestedScroll(int, int, int, int, int[]) dispatchNestedScroll}, passing 18603 * both the delta consumed and the delta unconsumed. A nested scrolling parent may treat 18604 * these values differently. See {@link ViewParent#onNestedScroll(View, int, int, int, int)}. 18605 * </p> 18606 * 18607 * @param axes Flags consisting of a combination of {@link #SCROLL_AXIS_HORIZONTAL} and/or 18608 * {@link #SCROLL_AXIS_VERTICAL}. 18609 * @return true if a cooperative parent was found and nested scrolling has been enabled for 18610 * the current gesture. 18611 * 18612 * @see #stopNestedScroll() 18613 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18614 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18615 */ 18616 public boolean startNestedScroll(int axes) { 18617 if (hasNestedScrollingParent()) { 18618 // Already in progress 18619 return true; 18620 } 18621 if (isNestedScrollingEnabled()) { 18622 ViewParent p = getParent(); 18623 View child = this; 18624 while (p != null) { 18625 try { 18626 if (p.onStartNestedScroll(child, this, axes)) { 18627 mNestedScrollingParent = p; 18628 p.onNestedScrollAccepted(child, this, axes); 18629 return true; 18630 } 18631 } catch (AbstractMethodError e) { 18632 Log.e(VIEW_LOG_TAG, "ViewParent " + p + " does not implement interface " + 18633 "method onStartNestedScroll", e); 18634 // Allow the search upward to continue 18635 } 18636 if (p instanceof View) { 18637 child = (View) p; 18638 } 18639 p = p.getParent(); 18640 } 18641 } 18642 return false; 18643 } 18644 18645 /** 18646 * Stop a nested scroll in progress. 18647 * 18648 * <p>Calling this method when a nested scroll is not currently in progress is harmless.</p> 18649 * 18650 * @see #startNestedScroll(int) 18651 */ 18652 public void stopNestedScroll() { 18653 if (mNestedScrollingParent != null) { 18654 mNestedScrollingParent.onStopNestedScroll(this); 18655 mNestedScrollingParent = null; 18656 } 18657 } 18658 18659 /** 18660 * Returns true if this view has a nested scrolling parent. 18661 * 18662 * <p>The presence of a nested scrolling parent indicates that this view has initiated 18663 * a nested scroll and it was accepted by an ancestor view further up the view hierarchy.</p> 18664 * 18665 * @return whether this view has a nested scrolling parent 18666 */ 18667 public boolean hasNestedScrollingParent() { 18668 return mNestedScrollingParent != null; 18669 } 18670 18671 /** 18672 * Dispatch one step of a nested scroll in progress. 18673 * 18674 * <p>Implementations of views that support nested scrolling should call this to report 18675 * info about a scroll in progress to the current nested scrolling parent. If a nested scroll 18676 * is not currently in progress or nested scrolling is not 18677 * {@link #isNestedScrollingEnabled() enabled} for this view this method does nothing.</p> 18678 * 18679 * <p>Compatible View implementations should also call 18680 * {@link #dispatchNestedPreScroll(int, int, int[], int[]) dispatchNestedPreScroll} before 18681 * consuming a component of the scroll event themselves.</p> 18682 * 18683 * @param dxConsumed Horizontal distance in pixels consumed by this view during this scroll step 18684 * @param dyConsumed Vertical distance in pixels consumed by this view during this scroll step 18685 * @param dxUnconsumed Horizontal scroll distance in pixels not consumed by this view 18686 * @param dyUnconsumed Horizontal scroll distance in pixels not consumed by this view 18687 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18688 * in local view coordinates of this view from before this operation 18689 * to after it completes. View implementations may use this to adjust 18690 * expected input coordinate tracking. 18691 * @return true if the event was dispatched, false if it could not be dispatched. 18692 * @see #dispatchNestedPreScroll(int, int, int[], int[]) 18693 */ 18694 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, 18695 int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) { 18696 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18697 if (dxConsumed != 0 || dyConsumed != 0 || dxUnconsumed != 0 || dyUnconsumed != 0) { 18698 int startX = 0; 18699 int startY = 0; 18700 if (offsetInWindow != null) { 18701 getLocationInWindow(offsetInWindow); 18702 startX = offsetInWindow[0]; 18703 startY = offsetInWindow[1]; 18704 } 18705 18706 mNestedScrollingParent.onNestedScroll(this, dxConsumed, dyConsumed, 18707 dxUnconsumed, dyUnconsumed); 18708 18709 if (offsetInWindow != null) { 18710 getLocationInWindow(offsetInWindow); 18711 offsetInWindow[0] -= startX; 18712 offsetInWindow[1] -= startY; 18713 } 18714 return true; 18715 } else if (offsetInWindow != null) { 18716 // No motion, no dispatch. Keep offsetInWindow up to date. 18717 offsetInWindow[0] = 0; 18718 offsetInWindow[1] = 0; 18719 } 18720 } 18721 return false; 18722 } 18723 18724 /** 18725 * Dispatch one step of a nested scroll in progress before this view consumes any portion of it. 18726 * 18727 * <p>Nested pre-scroll events are to nested scroll events what touch intercept is to touch. 18728 * <code>dispatchNestedPreScroll</code> offers an opportunity for the parent view in a nested 18729 * scrolling operation to consume some or all of the scroll operation before the child view 18730 * consumes it.</p> 18731 * 18732 * @param dx Horizontal scroll distance in pixels 18733 * @param dy Vertical scroll distance in pixels 18734 * @param consumed Output. If not null, consumed[0] will contain the consumed component of dx 18735 * and consumed[1] the consumed dy. 18736 * @param offsetInWindow Optional. If not null, on return this will contain the offset 18737 * in local view coordinates of this view from before this operation 18738 * to after it completes. View implementations may use this to adjust 18739 * expected input coordinate tracking. 18740 * @return true if the parent consumed some or all of the scroll delta 18741 * @see #dispatchNestedScroll(int, int, int, int, int[]) 18742 */ 18743 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 18744 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18745 if (dx != 0 || dy != 0) { 18746 int startX = 0; 18747 int startY = 0; 18748 if (offsetInWindow != null) { 18749 getLocationInWindow(offsetInWindow); 18750 startX = offsetInWindow[0]; 18751 startY = offsetInWindow[1]; 18752 } 18753 18754 if (consumed == null) { 18755 if (mTempNestedScrollConsumed == null) { 18756 mTempNestedScrollConsumed = new int[2]; 18757 } 18758 consumed = mTempNestedScrollConsumed; 18759 } 18760 consumed[0] = 0; 18761 consumed[1] = 0; 18762 mNestedScrollingParent.onNestedPreScroll(this, dx, dy, consumed); 18763 18764 if (offsetInWindow != null) { 18765 getLocationInWindow(offsetInWindow); 18766 offsetInWindow[0] -= startX; 18767 offsetInWindow[1] -= startY; 18768 } 18769 return consumed[0] != 0 || consumed[1] != 0; 18770 } else if (offsetInWindow != null) { 18771 offsetInWindow[0] = 0; 18772 offsetInWindow[1] = 0; 18773 } 18774 } 18775 return false; 18776 } 18777 18778 /** 18779 * Dispatch a fling to a nested scrolling parent. 18780 * 18781 * <p>This method should be used to indicate that a nested scrolling child has detected 18782 * suitable conditions for a fling. Generally this means that a touch scroll has ended with a 18783 * {@link VelocityTracker velocity} in the direction of scrolling that meets or exceeds 18784 * the {@link ViewConfiguration#getScaledMinimumFlingVelocity() minimum fling velocity} 18785 * along a scrollable axis.</p> 18786 * 18787 * <p>If a nested scrolling child view would normally fling but it is at the edge of 18788 * its own content, it can use this method to delegate the fling to its nested scrolling 18789 * parent instead. The parent may optionally consume the fling or observe a child fling.</p> 18790 * 18791 * @param velocityX Horizontal fling velocity in pixels per second 18792 * @param velocityY Vertical fling velocity in pixels per second 18793 * @param consumed true if the child consumed the fling, false otherwise 18794 * @return true if the nested scrolling parent consumed or otherwise reacted to the fling 18795 */ 18796 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 18797 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18798 return mNestedScrollingParent.onNestedFling(this, velocityX, velocityY, consumed); 18799 } 18800 return false; 18801 } 18802 18803 /** 18804 * Dispatch a fling to a nested scrolling parent before it is processed by this view. 18805 * 18806 * <p>Nested pre-fling events are to nested fling events what touch intercept is to touch 18807 * and what nested pre-scroll is to nested scroll. <code>dispatchNestedPreFling</code> 18808 * offsets an opportunity for the parent view in a nested fling to fully consume the fling 18809 * before the child view consumes it. If this method returns <code>true</code>, a nested 18810 * parent view consumed the fling and this view should not scroll as a result.</p> 18811 * 18812 * <p>For a better user experience, only one view in a nested scrolling chain should consume 18813 * the fling at a time. If a parent view consumed the fling this method will return false. 18814 * Custom view implementations should account for this in two ways:</p> 18815 * 18816 * <ul> 18817 * <li>If a custom view is paged and needs to settle to a fixed page-point, do not 18818 * call <code>dispatchNestedPreFling</code>; consume the fling and settle to a valid 18819 * position regardless.</li> 18820 * <li>If a nested parent does consume the fling, this view should not scroll at all, 18821 * even to settle back to a valid idle position.</li> 18822 * </ul> 18823 * 18824 * <p>Views should also not offer fling velocities to nested parent views along an axis 18825 * where scrolling is not currently supported; a {@link android.widget.ScrollView ScrollView} 18826 * should not offer a horizontal fling velocity to its parents since scrolling along that 18827 * axis is not permitted and carrying velocity along that motion does not make sense.</p> 18828 * 18829 * @param velocityX Horizontal fling velocity in pixels per second 18830 * @param velocityY Vertical fling velocity in pixels per second 18831 * @return true if a nested scrolling parent consumed the fling 18832 */ 18833 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 18834 if (isNestedScrollingEnabled() && mNestedScrollingParent != null) { 18835 return mNestedScrollingParent.onNestedPreFling(this, velocityX, velocityY); 18836 } 18837 return false; 18838 } 18839 18840 /** 18841 * Gets a scale factor that determines the distance the view should scroll 18842 * vertically in response to {@link MotionEvent#ACTION_SCROLL}. 18843 * @return The vertical scroll scale factor. 18844 * @hide 18845 */ 18846 protected float getVerticalScrollFactor() { 18847 if (mVerticalScrollFactor == 0) { 18848 TypedValue outValue = new TypedValue(); 18849 if (!mContext.getTheme().resolveAttribute( 18850 com.android.internal.R.attr.listPreferredItemHeight, outValue, true)) { 18851 throw new IllegalStateException( 18852 "Expected theme to define listPreferredItemHeight."); 18853 } 18854 mVerticalScrollFactor = outValue.getDimension( 18855 mContext.getResources().getDisplayMetrics()); 18856 } 18857 return mVerticalScrollFactor; 18858 } 18859 18860 /** 18861 * Gets a scale factor that determines the distance the view should scroll 18862 * horizontally in response to {@link MotionEvent#ACTION_SCROLL}. 18863 * @return The horizontal scroll scale factor. 18864 * @hide 18865 */ 18866 protected float getHorizontalScrollFactor() { 18867 // TODO: Should use something else. 18868 return getVerticalScrollFactor(); 18869 } 18870 18871 /** 18872 * Return the value specifying the text direction or policy that was set with 18873 * {@link #setTextDirection(int)}. 18874 * 18875 * @return the defined text direction. It can be one of: 18876 * 18877 * {@link #TEXT_DIRECTION_INHERIT}, 18878 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18879 * {@link #TEXT_DIRECTION_ANY_RTL}, 18880 * {@link #TEXT_DIRECTION_LTR}, 18881 * {@link #TEXT_DIRECTION_RTL}, 18882 * {@link #TEXT_DIRECTION_LOCALE} 18883 * 18884 * @attr ref android.R.styleable#View_textDirection 18885 * 18886 * @hide 18887 */ 18888 @ViewDebug.ExportedProperty(category = "text", mapping = { 18889 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18890 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18891 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18892 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18893 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18894 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18895 }) 18896 public int getRawTextDirection() { 18897 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_MASK) >> PFLAG2_TEXT_DIRECTION_MASK_SHIFT; 18898 } 18899 18900 /** 18901 * Set the text direction. 18902 * 18903 * @param textDirection the direction to set. Should be one of: 18904 * 18905 * {@link #TEXT_DIRECTION_INHERIT}, 18906 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18907 * {@link #TEXT_DIRECTION_ANY_RTL}, 18908 * {@link #TEXT_DIRECTION_LTR}, 18909 * {@link #TEXT_DIRECTION_RTL}, 18910 * {@link #TEXT_DIRECTION_LOCALE} 18911 * 18912 * Resolution will be done if the value is set to TEXT_DIRECTION_INHERIT. The resolution 18913 * proceeds up the parent chain of the view to get the value. If there is no parent, then it will 18914 * return the default {@link #TEXT_DIRECTION_FIRST_STRONG}. 18915 * 18916 * @attr ref android.R.styleable#View_textDirection 18917 */ 18918 public void setTextDirection(int textDirection) { 18919 if (getRawTextDirection() != textDirection) { 18920 // Reset the current text direction and the resolved one 18921 mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; 18922 resetResolvedTextDirection(); 18923 // Set the new text direction 18924 mPrivateFlags2 |= ((textDirection << PFLAG2_TEXT_DIRECTION_MASK_SHIFT) & PFLAG2_TEXT_DIRECTION_MASK); 18925 // Do resolution 18926 resolveTextDirection(); 18927 // Notify change 18928 onRtlPropertiesChanged(getLayoutDirection()); 18929 // Refresh 18930 requestLayout(); 18931 invalidate(true); 18932 } 18933 } 18934 18935 /** 18936 * Return the resolved text direction. 18937 * 18938 * @return the resolved text direction. Returns one of: 18939 * 18940 * {@link #TEXT_DIRECTION_FIRST_STRONG} 18941 * {@link #TEXT_DIRECTION_ANY_RTL}, 18942 * {@link #TEXT_DIRECTION_LTR}, 18943 * {@link #TEXT_DIRECTION_RTL}, 18944 * {@link #TEXT_DIRECTION_LOCALE} 18945 * 18946 * @attr ref android.R.styleable#View_textDirection 18947 */ 18948 @ViewDebug.ExportedProperty(category = "text", mapping = { 18949 @ViewDebug.IntToString(from = TEXT_DIRECTION_INHERIT, to = "INHERIT"), 18950 @ViewDebug.IntToString(from = TEXT_DIRECTION_FIRST_STRONG, to = "FIRST_STRONG"), 18951 @ViewDebug.IntToString(from = TEXT_DIRECTION_ANY_RTL, to = "ANY_RTL"), 18952 @ViewDebug.IntToString(from = TEXT_DIRECTION_LTR, to = "LTR"), 18953 @ViewDebug.IntToString(from = TEXT_DIRECTION_RTL, to = "RTL"), 18954 @ViewDebug.IntToString(from = TEXT_DIRECTION_LOCALE, to = "LOCALE") 18955 }) 18956 public int getTextDirection() { 18957 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; 18958 } 18959 18960 /** 18961 * Resolve the text direction. 18962 * 18963 * @return true if resolution has been done, false otherwise. 18964 * 18965 * @hide 18966 */ 18967 public boolean resolveTextDirection() { 18968 // Reset any previous text direction resolution 18969 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 18970 18971 if (hasRtlSupport()) { 18972 // Set resolved text direction flag depending on text direction flag 18973 final int textDirection = getRawTextDirection(); 18974 switch(textDirection) { 18975 case TEXT_DIRECTION_INHERIT: 18976 if (!canResolveTextDirection()) { 18977 // We cannot do the resolution if there is no parent, so use the default one 18978 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18979 // Resolution will need to happen again later 18980 return false; 18981 } 18982 18983 // Parent has not yet resolved, so we still return the default 18984 try { 18985 if (!mParent.isTextDirectionResolved()) { 18986 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18987 // Resolution will need to happen again later 18988 return false; 18989 } 18990 } catch (AbstractMethodError e) { 18991 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 18992 " does not fully implement ViewParent", e); 18993 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED | 18994 PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 18995 return true; 18996 } 18997 18998 // Set current resolved direction to the same value as the parent's one 18999 int parentResolvedDirection; 19000 try { 19001 parentResolvedDirection = mParent.getTextDirection(); 19002 } catch (AbstractMethodError e) { 19003 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19004 " does not fully implement ViewParent", e); 19005 parentResolvedDirection = TEXT_DIRECTION_LTR; 19006 } 19007 switch (parentResolvedDirection) { 19008 case TEXT_DIRECTION_FIRST_STRONG: 19009 case TEXT_DIRECTION_ANY_RTL: 19010 case TEXT_DIRECTION_LTR: 19011 case TEXT_DIRECTION_RTL: 19012 case TEXT_DIRECTION_LOCALE: 19013 mPrivateFlags2 |= 19014 (parentResolvedDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19015 break; 19016 default: 19017 // Default resolved direction is "first strong" heuristic 19018 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19019 } 19020 break; 19021 case TEXT_DIRECTION_FIRST_STRONG: 19022 case TEXT_DIRECTION_ANY_RTL: 19023 case TEXT_DIRECTION_LTR: 19024 case TEXT_DIRECTION_RTL: 19025 case TEXT_DIRECTION_LOCALE: 19026 // Resolved direction is the same as text direction 19027 mPrivateFlags2 |= (textDirection << PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT); 19028 break; 19029 default: 19030 // Default resolved direction is "first strong" heuristic 19031 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19032 } 19033 } else { 19034 // Default resolved direction is "first strong" heuristic 19035 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19036 } 19037 19038 // Set to resolved 19039 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED; 19040 return true; 19041 } 19042 19043 /** 19044 * Check if text direction resolution can be done. 19045 * 19046 * @return true if text direction resolution can be done otherwise return false. 19047 */ 19048 public boolean canResolveTextDirection() { 19049 switch (getRawTextDirection()) { 19050 case TEXT_DIRECTION_INHERIT: 19051 if (mParent != null) { 19052 try { 19053 return mParent.canResolveTextDirection(); 19054 } catch (AbstractMethodError e) { 19055 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19056 " does not fully implement ViewParent", e); 19057 } 19058 } 19059 return false; 19060 19061 default: 19062 return true; 19063 } 19064 } 19065 19066 /** 19067 * Reset resolved text direction. Text direction will be resolved during a call to 19068 * {@link #onMeasure(int, int)}. 19069 * 19070 * @hide 19071 */ 19072 public void resetResolvedTextDirection() { 19073 // Reset any previous text direction resolution 19074 mPrivateFlags2 &= ~(PFLAG2_TEXT_DIRECTION_RESOLVED | PFLAG2_TEXT_DIRECTION_RESOLVED_MASK); 19075 // Set to default value 19076 mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_RESOLVED_DEFAULT; 19077 } 19078 19079 /** 19080 * @return true if text direction is inherited. 19081 * 19082 * @hide 19083 */ 19084 public boolean isTextDirectionInherited() { 19085 return (getRawTextDirection() == TEXT_DIRECTION_INHERIT); 19086 } 19087 19088 /** 19089 * @return true if text direction is resolved. 19090 */ 19091 public boolean isTextDirectionResolved() { 19092 return (mPrivateFlags2 & PFLAG2_TEXT_DIRECTION_RESOLVED) == PFLAG2_TEXT_DIRECTION_RESOLVED; 19093 } 19094 19095 /** 19096 * Return the value specifying the text alignment or policy that was set with 19097 * {@link #setTextAlignment(int)}. 19098 * 19099 * @return the defined text alignment. It can be one of: 19100 * 19101 * {@link #TEXT_ALIGNMENT_INHERIT}, 19102 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19103 * {@link #TEXT_ALIGNMENT_CENTER}, 19104 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19105 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19106 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19107 * {@link #TEXT_ALIGNMENT_VIEW_END} 19108 * 19109 * @attr ref android.R.styleable#View_textAlignment 19110 * 19111 * @hide 19112 */ 19113 @ViewDebug.ExportedProperty(category = "text", mapping = { 19114 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19115 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19116 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19117 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19118 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19119 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19120 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19121 }) 19122 @TextAlignment 19123 public int getRawTextAlignment() { 19124 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_MASK) >> PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT; 19125 } 19126 19127 /** 19128 * Set the text alignment. 19129 * 19130 * @param textAlignment The text alignment to set. Should be one of 19131 * 19132 * {@link #TEXT_ALIGNMENT_INHERIT}, 19133 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19134 * {@link #TEXT_ALIGNMENT_CENTER}, 19135 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19136 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19137 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19138 * {@link #TEXT_ALIGNMENT_VIEW_END} 19139 * 19140 * Resolution will be done if the value is set to TEXT_ALIGNMENT_INHERIT. The resolution 19141 * proceeds up the parent chain of the view to get the value. If there is no parent, then it 19142 * will return the default {@link #TEXT_ALIGNMENT_GRAVITY}. 19143 * 19144 * @attr ref android.R.styleable#View_textAlignment 19145 */ 19146 public void setTextAlignment(@TextAlignment int textAlignment) { 19147 if (textAlignment != getRawTextAlignment()) { 19148 // Reset the current and resolved text alignment 19149 mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; 19150 resetResolvedTextAlignment(); 19151 // Set the new text alignment 19152 mPrivateFlags2 |= 19153 ((textAlignment << PFLAG2_TEXT_ALIGNMENT_MASK_SHIFT) & PFLAG2_TEXT_ALIGNMENT_MASK); 19154 // Do resolution 19155 resolveTextAlignment(); 19156 // Notify change 19157 onRtlPropertiesChanged(getLayoutDirection()); 19158 // Refresh 19159 requestLayout(); 19160 invalidate(true); 19161 } 19162 } 19163 19164 /** 19165 * Return the resolved text alignment. 19166 * 19167 * @return the resolved text alignment. Returns one of: 19168 * 19169 * {@link #TEXT_ALIGNMENT_GRAVITY}, 19170 * {@link #TEXT_ALIGNMENT_CENTER}, 19171 * {@link #TEXT_ALIGNMENT_TEXT_START}, 19172 * {@link #TEXT_ALIGNMENT_TEXT_END}, 19173 * {@link #TEXT_ALIGNMENT_VIEW_START}, 19174 * {@link #TEXT_ALIGNMENT_VIEW_END} 19175 * 19176 * @attr ref android.R.styleable#View_textAlignment 19177 */ 19178 @ViewDebug.ExportedProperty(category = "text", mapping = { 19179 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_INHERIT, to = "INHERIT"), 19180 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_GRAVITY, to = "GRAVITY"), 19181 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_START, to = "TEXT_START"), 19182 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_TEXT_END, to = "TEXT_END"), 19183 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_CENTER, to = "CENTER"), 19184 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_START, to = "VIEW_START"), 19185 @ViewDebug.IntToString(from = TEXT_ALIGNMENT_VIEW_END, to = "VIEW_END") 19186 }) 19187 @TextAlignment 19188 public int getTextAlignment() { 19189 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> 19190 PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; 19191 } 19192 19193 /** 19194 * Resolve the text alignment. 19195 * 19196 * @return true if resolution has been done, false otherwise. 19197 * 19198 * @hide 19199 */ 19200 public boolean resolveTextAlignment() { 19201 // Reset any previous text alignment resolution 19202 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19203 19204 if (hasRtlSupport()) { 19205 // Set resolved text alignment flag depending on text alignment flag 19206 final int textAlignment = getRawTextAlignment(); 19207 switch (textAlignment) { 19208 case TEXT_ALIGNMENT_INHERIT: 19209 // Check if we can resolve the text alignment 19210 if (!canResolveTextAlignment()) { 19211 // We cannot do the resolution if there is no parent so use the default 19212 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19213 // Resolution will need to happen again later 19214 return false; 19215 } 19216 19217 // Parent has not yet resolved, so we still return the default 19218 try { 19219 if (!mParent.isTextAlignmentResolved()) { 19220 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19221 // Resolution will need to happen again later 19222 return false; 19223 } 19224 } catch (AbstractMethodError e) { 19225 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19226 " does not fully implement ViewParent", e); 19227 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED | 19228 PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19229 return true; 19230 } 19231 19232 int parentResolvedTextAlignment; 19233 try { 19234 parentResolvedTextAlignment = mParent.getTextAlignment(); 19235 } catch (AbstractMethodError e) { 19236 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19237 " does not fully implement ViewParent", e); 19238 parentResolvedTextAlignment = TEXT_ALIGNMENT_GRAVITY; 19239 } 19240 switch (parentResolvedTextAlignment) { 19241 case TEXT_ALIGNMENT_GRAVITY: 19242 case TEXT_ALIGNMENT_TEXT_START: 19243 case TEXT_ALIGNMENT_TEXT_END: 19244 case TEXT_ALIGNMENT_CENTER: 19245 case TEXT_ALIGNMENT_VIEW_START: 19246 case TEXT_ALIGNMENT_VIEW_END: 19247 // Resolved text alignment is the same as the parent resolved 19248 // text alignment 19249 mPrivateFlags2 |= 19250 (parentResolvedTextAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19251 break; 19252 default: 19253 // Use default resolved text alignment 19254 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19255 } 19256 break; 19257 case TEXT_ALIGNMENT_GRAVITY: 19258 case TEXT_ALIGNMENT_TEXT_START: 19259 case TEXT_ALIGNMENT_TEXT_END: 19260 case TEXT_ALIGNMENT_CENTER: 19261 case TEXT_ALIGNMENT_VIEW_START: 19262 case TEXT_ALIGNMENT_VIEW_END: 19263 // Resolved text alignment is the same as text alignment 19264 mPrivateFlags2 |= (textAlignment << PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT); 19265 break; 19266 default: 19267 // Use default resolved text alignment 19268 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19269 } 19270 } else { 19271 // Use default resolved text alignment 19272 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19273 } 19274 19275 // Set the resolved 19276 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19277 return true; 19278 } 19279 19280 /** 19281 * Check if text alignment resolution can be done. 19282 * 19283 * @return true if text alignment resolution can be done otherwise return false. 19284 */ 19285 public boolean canResolveTextAlignment() { 19286 switch (getRawTextAlignment()) { 19287 case TEXT_DIRECTION_INHERIT: 19288 if (mParent != null) { 19289 try { 19290 return mParent.canResolveTextAlignment(); 19291 } catch (AbstractMethodError e) { 19292 Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() + 19293 " does not fully implement ViewParent", e); 19294 } 19295 } 19296 return false; 19297 19298 default: 19299 return true; 19300 } 19301 } 19302 19303 /** 19304 * Reset resolved text alignment. Text alignment will be resolved during a call to 19305 * {@link #onMeasure(int, int)}. 19306 * 19307 * @hide 19308 */ 19309 public void resetResolvedTextAlignment() { 19310 // Reset any previous text alignment resolution 19311 mPrivateFlags2 &= ~(PFLAG2_TEXT_ALIGNMENT_RESOLVED | PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK); 19312 // Set to default 19313 mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_RESOLVED_DEFAULT; 19314 } 19315 19316 /** 19317 * @return true if text alignment is inherited. 19318 * 19319 * @hide 19320 */ 19321 public boolean isTextAlignmentInherited() { 19322 return (getRawTextAlignment() == TEXT_ALIGNMENT_INHERIT); 19323 } 19324 19325 /** 19326 * @return true if text alignment is resolved. 19327 */ 19328 public boolean isTextAlignmentResolved() { 19329 return (mPrivateFlags2 & PFLAG2_TEXT_ALIGNMENT_RESOLVED) == PFLAG2_TEXT_ALIGNMENT_RESOLVED; 19330 } 19331 19332 /** 19333 * Generate a value suitable for use in {@link #setId(int)}. 19334 * This value will not collide with ID values generated at build time by aapt for R.id. 19335 * 19336 * @return a generated ID value 19337 */ 19338 public static int generateViewId() { 19339 for (;;) { 19340 final int result = sNextGeneratedId.get(); 19341 // aapt-generated IDs have the high byte nonzero; clamp to the range under that. 19342 int newValue = result + 1; 19343 if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0. 19344 if (sNextGeneratedId.compareAndSet(result, newValue)) { 19345 return result; 19346 } 19347 } 19348 } 19349 19350 /** 19351 * Gets the Views in the hierarchy affected by entering and exiting Activity Scene transitions. 19352 * @param transitioningViews This View will be added to transitioningViews if it is VISIBLE and 19353 * a normal View or a ViewGroup with 19354 * {@link android.view.ViewGroup#isTransitionGroup()} true. 19355 * @hide 19356 */ 19357 public void captureTransitioningViews(List<View> transitioningViews) { 19358 if (getVisibility() == View.VISIBLE) { 19359 transitioningViews.add(this); 19360 } 19361 } 19362 19363 /** 19364 * Adds all Views that have {@link #getTransitionName()} non-null to namedElements. 19365 * @param namedElements Will contain all Views in the hierarchy having a transitionName. 19366 * @hide 19367 */ 19368 public void findNamedViews(Map<String, View> namedElements) { 19369 if (getVisibility() == VISIBLE || mGhostView != null) { 19370 String transitionName = getTransitionName(); 19371 if (transitionName != null) { 19372 namedElements.put(transitionName, this); 19373 } 19374 } 19375 } 19376 19377 // 19378 // Properties 19379 // 19380 /** 19381 * A Property wrapper around the <code>alpha</code> functionality handled by the 19382 * {@link View#setAlpha(float)} and {@link View#getAlpha()} methods. 19383 */ 19384 public static final Property<View, Float> ALPHA = new FloatProperty<View>("alpha") { 19385 @Override 19386 public void setValue(View object, float value) { 19387 object.setAlpha(value); 19388 } 19389 19390 @Override 19391 public Float get(View object) { 19392 return object.getAlpha(); 19393 } 19394 }; 19395 19396 /** 19397 * A Property wrapper around the <code>translationX</code> functionality handled by the 19398 * {@link View#setTranslationX(float)} and {@link View#getTranslationX()} methods. 19399 */ 19400 public static final Property<View, Float> TRANSLATION_X = new FloatProperty<View>("translationX") { 19401 @Override 19402 public void setValue(View object, float value) { 19403 object.setTranslationX(value); 19404 } 19405 19406 @Override 19407 public Float get(View object) { 19408 return object.getTranslationX(); 19409 } 19410 }; 19411 19412 /** 19413 * A Property wrapper around the <code>translationY</code> functionality handled by the 19414 * {@link View#setTranslationY(float)} and {@link View#getTranslationY()} methods. 19415 */ 19416 public static final Property<View, Float> TRANSLATION_Y = new FloatProperty<View>("translationY") { 19417 @Override 19418 public void setValue(View object, float value) { 19419 object.setTranslationY(value); 19420 } 19421 19422 @Override 19423 public Float get(View object) { 19424 return object.getTranslationY(); 19425 } 19426 }; 19427 19428 /** 19429 * A Property wrapper around the <code>translationZ</code> functionality handled by the 19430 * {@link View#setTranslationZ(float)} and {@link View#getTranslationZ()} methods. 19431 */ 19432 public static final Property<View, Float> TRANSLATION_Z = new FloatProperty<View>("translationZ") { 19433 @Override 19434 public void setValue(View object, float value) { 19435 object.setTranslationZ(value); 19436 } 19437 19438 @Override 19439 public Float get(View object) { 19440 return object.getTranslationZ(); 19441 } 19442 }; 19443 19444 /** 19445 * A Property wrapper around the <code>x</code> functionality handled by the 19446 * {@link View#setX(float)} and {@link View#getX()} methods. 19447 */ 19448 public static final Property<View, Float> X = new FloatProperty<View>("x") { 19449 @Override 19450 public void setValue(View object, float value) { 19451 object.setX(value); 19452 } 19453 19454 @Override 19455 public Float get(View object) { 19456 return object.getX(); 19457 } 19458 }; 19459 19460 /** 19461 * A Property wrapper around the <code>y</code> functionality handled by the 19462 * {@link View#setY(float)} and {@link View#getY()} methods. 19463 */ 19464 public static final Property<View, Float> Y = new FloatProperty<View>("y") { 19465 @Override 19466 public void setValue(View object, float value) { 19467 object.setY(value); 19468 } 19469 19470 @Override 19471 public Float get(View object) { 19472 return object.getY(); 19473 } 19474 }; 19475 19476 /** 19477 * A Property wrapper around the <code>z</code> functionality handled by the 19478 * {@link View#setZ(float)} and {@link View#getZ()} methods. 19479 */ 19480 public static final Property<View, Float> Z = new FloatProperty<View>("z") { 19481 @Override 19482 public void setValue(View object, float value) { 19483 object.setZ(value); 19484 } 19485 19486 @Override 19487 public Float get(View object) { 19488 return object.getZ(); 19489 } 19490 }; 19491 19492 /** 19493 * A Property wrapper around the <code>rotation</code> functionality handled by the 19494 * {@link View#setRotation(float)} and {@link View#getRotation()} methods. 19495 */ 19496 public static final Property<View, Float> ROTATION = new FloatProperty<View>("rotation") { 19497 @Override 19498 public void setValue(View object, float value) { 19499 object.setRotation(value); 19500 } 19501 19502 @Override 19503 public Float get(View object) { 19504 return object.getRotation(); 19505 } 19506 }; 19507 19508 /** 19509 * A Property wrapper around the <code>rotationX</code> functionality handled by the 19510 * {@link View#setRotationX(float)} and {@link View#getRotationX()} methods. 19511 */ 19512 public static final Property<View, Float> ROTATION_X = new FloatProperty<View>("rotationX") { 19513 @Override 19514 public void setValue(View object, float value) { 19515 object.setRotationX(value); 19516 } 19517 19518 @Override 19519 public Float get(View object) { 19520 return object.getRotationX(); 19521 } 19522 }; 19523 19524 /** 19525 * A Property wrapper around the <code>rotationY</code> functionality handled by the 19526 * {@link View#setRotationY(float)} and {@link View#getRotationY()} methods. 19527 */ 19528 public static final Property<View, Float> ROTATION_Y = new FloatProperty<View>("rotationY") { 19529 @Override 19530 public void setValue(View object, float value) { 19531 object.setRotationY(value); 19532 } 19533 19534 @Override 19535 public Float get(View object) { 19536 return object.getRotationY(); 19537 } 19538 }; 19539 19540 /** 19541 * A Property wrapper around the <code>scaleX</code> functionality handled by the 19542 * {@link View#setScaleX(float)} and {@link View#getScaleX()} methods. 19543 */ 19544 public static final Property<View, Float> SCALE_X = new FloatProperty<View>("scaleX") { 19545 @Override 19546 public void setValue(View object, float value) { 19547 object.setScaleX(value); 19548 } 19549 19550 @Override 19551 public Float get(View object) { 19552 return object.getScaleX(); 19553 } 19554 }; 19555 19556 /** 19557 * A Property wrapper around the <code>scaleY</code> functionality handled by the 19558 * {@link View#setScaleY(float)} and {@link View#getScaleY()} methods. 19559 */ 19560 public static final Property<View, Float> SCALE_Y = new FloatProperty<View>("scaleY") { 19561 @Override 19562 public void setValue(View object, float value) { 19563 object.setScaleY(value); 19564 } 19565 19566 @Override 19567 public Float get(View object) { 19568 return object.getScaleY(); 19569 } 19570 }; 19571 19572 /** 19573 * A MeasureSpec encapsulates the layout requirements passed from parent to child. 19574 * Each MeasureSpec represents a requirement for either the width or the height. 19575 * A MeasureSpec is comprised of a size and a mode. There are three possible 19576 * modes: 19577 * <dl> 19578 * <dt>UNSPECIFIED</dt> 19579 * <dd> 19580 * The parent has not imposed any constraint on the child. It can be whatever size 19581 * it wants. 19582 * </dd> 19583 * 19584 * <dt>EXACTLY</dt> 19585 * <dd> 19586 * The parent has determined an exact size for the child. The child is going to be 19587 * given those bounds regardless of how big it wants to be. 19588 * </dd> 19589 * 19590 * <dt>AT_MOST</dt> 19591 * <dd> 19592 * The child can be as large as it wants up to the specified size. 19593 * </dd> 19594 * </dl> 19595 * 19596 * MeasureSpecs are implemented as ints to reduce object allocation. This class 19597 * is provided to pack and unpack the <size, mode> tuple into the int. 19598 */ 19599 public static class MeasureSpec { 19600 private static final int MODE_SHIFT = 30; 19601 private static final int MODE_MASK = 0x3 << MODE_SHIFT; 19602 19603 /** 19604 * Measure specification mode: The parent has not imposed any constraint 19605 * on the child. It can be whatever size it wants. 19606 */ 19607 public static final int UNSPECIFIED = 0 << MODE_SHIFT; 19608 19609 /** 19610 * Measure specification mode: The parent has determined an exact size 19611 * for the child. The child is going to be given those bounds regardless 19612 * of how big it wants to be. 19613 */ 19614 public static final int EXACTLY = 1 << MODE_SHIFT; 19615 19616 /** 19617 * Measure specification mode: The child can be as large as it wants up 19618 * to the specified size. 19619 */ 19620 public static final int AT_MOST = 2 << MODE_SHIFT; 19621 19622 /** 19623 * Creates a measure specification based on the supplied size and mode. 19624 * 19625 * The mode must always be one of the following: 19626 * <ul> 19627 * <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li> 19628 * <li>{@link android.view.View.MeasureSpec#EXACTLY}</li> 19629 * <li>{@link android.view.View.MeasureSpec#AT_MOST}</li> 19630 * </ul> 19631 * 19632 * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's 19633 * implementation was such that the order of arguments did not matter 19634 * and overflow in either value could impact the resulting MeasureSpec. 19635 * {@link android.widget.RelativeLayout} was affected by this bug. 19636 * Apps targeting API levels greater than 17 will get the fixed, more strict 19637 * behavior.</p> 19638 * 19639 * @param size the size of the measure specification 19640 * @param mode the mode of the measure specification 19641 * @return the measure specification based on size and mode 19642 */ 19643 public static int makeMeasureSpec(int size, int mode) { 19644 if (sUseBrokenMakeMeasureSpec) { 19645 return size + mode; 19646 } else { 19647 return (size & ~MODE_MASK) | (mode & MODE_MASK); 19648 } 19649 } 19650 19651 /** 19652 * Extracts the mode from the supplied measure specification. 19653 * 19654 * @param measureSpec the measure specification to extract the mode from 19655 * @return {@link android.view.View.MeasureSpec#UNSPECIFIED}, 19656 * {@link android.view.View.MeasureSpec#AT_MOST} or 19657 * {@link android.view.View.MeasureSpec#EXACTLY} 19658 */ 19659 public static int getMode(int measureSpec) { 19660 return (measureSpec & MODE_MASK); 19661 } 19662 19663 /** 19664 * Extracts the size from the supplied measure specification. 19665 * 19666 * @param measureSpec the measure specification to extract the size from 19667 * @return the size in pixels defined in the supplied measure specification 19668 */ 19669 public static int getSize(int measureSpec) { 19670 return (measureSpec & ~MODE_MASK); 19671 } 19672 19673 static int adjust(int measureSpec, int delta) { 19674 final int mode = getMode(measureSpec); 19675 if (mode == UNSPECIFIED) { 19676 // No need to adjust size for UNSPECIFIED mode. 19677 return makeMeasureSpec(0, UNSPECIFIED); 19678 } 19679 int size = getSize(measureSpec) + delta; 19680 if (size < 0) { 19681 Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size + 19682 ") spec: " + toString(measureSpec) + " delta: " + delta); 19683 size = 0; 19684 } 19685 return makeMeasureSpec(size, mode); 19686 } 19687 19688 /** 19689 * Returns a String representation of the specified measure 19690 * specification. 19691 * 19692 * @param measureSpec the measure specification to convert to a String 19693 * @return a String with the following format: "MeasureSpec: MODE SIZE" 19694 */ 19695 public static String toString(int measureSpec) { 19696 int mode = getMode(measureSpec); 19697 int size = getSize(measureSpec); 19698 19699 StringBuilder sb = new StringBuilder("MeasureSpec: "); 19700 19701 if (mode == UNSPECIFIED) 19702 sb.append("UNSPECIFIED "); 19703 else if (mode == EXACTLY) 19704 sb.append("EXACTLY "); 19705 else if (mode == AT_MOST) 19706 sb.append("AT_MOST "); 19707 else 19708 sb.append(mode).append(" "); 19709 19710 sb.append(size); 19711 return sb.toString(); 19712 } 19713 } 19714 19715 private final class CheckForLongPress implements Runnable { 19716 private int mOriginalWindowAttachCount; 19717 19718 @Override 19719 public void run() { 19720 if (isPressed() && (mParent != null) 19721 && mOriginalWindowAttachCount == mWindowAttachCount) { 19722 if (performLongClick()) { 19723 mHasPerformedLongPress = true; 19724 } 19725 } 19726 } 19727 19728 public void rememberWindowAttachCount() { 19729 mOriginalWindowAttachCount = mWindowAttachCount; 19730 } 19731 } 19732 19733 private final class CheckForTap implements Runnable { 19734 public float x; 19735 public float y; 19736 19737 @Override 19738 public void run() { 19739 mPrivateFlags &= ~PFLAG_PREPRESSED; 19740 setPressed(true, x, y); 19741 checkForLongClick(ViewConfiguration.getTapTimeout()); 19742 } 19743 } 19744 19745 private final class PerformClick implements Runnable { 19746 @Override 19747 public void run() { 19748 performClick(); 19749 } 19750 } 19751 19752 /** @hide */ 19753 public void hackTurnOffWindowResizeAnim(boolean off) { 19754 mAttachInfo.mTurnOffWindowResizeAnim = off; 19755 } 19756 19757 /** 19758 * This method returns a ViewPropertyAnimator object, which can be used to animate 19759 * specific properties on this View. 19760 * 19761 * @return ViewPropertyAnimator The ViewPropertyAnimator associated with this View. 19762 */ 19763 public ViewPropertyAnimator animate() { 19764 if (mAnimator == null) { 19765 mAnimator = new ViewPropertyAnimator(this); 19766 } 19767 return mAnimator; 19768 } 19769 19770 /** 19771 * Sets the name of the View to be used to identify Views in Transitions. 19772 * Names should be unique in the View hierarchy. 19773 * 19774 * @param transitionName The name of the View to uniquely identify it for Transitions. 19775 */ 19776 public final void setTransitionName(String transitionName) { 19777 mTransitionName = transitionName; 19778 } 19779 19780 /** 19781 * Returns the name of the View to be used to identify Views in Transitions. 19782 * Names should be unique in the View hierarchy. 19783 * 19784 * <p>This returns null if the View has not been given a name.</p> 19785 * 19786 * @return The name used of the View to be used to identify Views in Transitions or null 19787 * if no name has been given. 19788 */ 19789 @ViewDebug.ExportedProperty 19790 public String getTransitionName() { 19791 return mTransitionName; 19792 } 19793 19794 /** 19795 * Interface definition for a callback to be invoked when a hardware key event is 19796 * dispatched to this view. The callback will be invoked before the key event is 19797 * given to the view. This is only useful for hardware keyboards; a software input 19798 * method has no obligation to trigger this listener. 19799 */ 19800 public interface OnKeyListener { 19801 /** 19802 * Called when a hardware key is dispatched to a view. This allows listeners to 19803 * get a chance to respond before the target view. 19804 * <p>Key presses in software keyboards will generally NOT trigger this method, 19805 * although some may elect to do so in some situations. Do not assume a 19806 * software input method has to be key-based; even if it is, it may use key presses 19807 * in a different way than you expect, so there is no way to reliably catch soft 19808 * input key presses. 19809 * 19810 * @param v The view the key has been dispatched to. 19811 * @param keyCode The code for the physical key that was pressed 19812 * @param event The KeyEvent object containing full information about 19813 * the event. 19814 * @return True if the listener has consumed the event, false otherwise. 19815 */ 19816 boolean onKey(View v, int keyCode, KeyEvent event); 19817 } 19818 19819 /** 19820 * Interface definition for a callback to be invoked when a touch event is 19821 * dispatched to this view. The callback will be invoked before the touch 19822 * event is given to the view. 19823 */ 19824 public interface OnTouchListener { 19825 /** 19826 * Called when a touch event is dispatched to a view. This allows listeners to 19827 * get a chance to respond before the target view. 19828 * 19829 * @param v The view the touch event has been dispatched to. 19830 * @param event The MotionEvent object containing full information about 19831 * the event. 19832 * @return True if the listener has consumed the event, false otherwise. 19833 */ 19834 boolean onTouch(View v, MotionEvent event); 19835 } 19836 19837 /** 19838 * Interface definition for a callback to be invoked when a hover event is 19839 * dispatched to this view. The callback will be invoked before the hover 19840 * event is given to the view. 19841 */ 19842 public interface OnHoverListener { 19843 /** 19844 * Called when a hover event is dispatched to a view. This allows listeners to 19845 * get a chance to respond before the target view. 19846 * 19847 * @param v The view the hover event has been dispatched to. 19848 * @param event The MotionEvent object containing full information about 19849 * the event. 19850 * @return True if the listener has consumed the event, false otherwise. 19851 */ 19852 boolean onHover(View v, MotionEvent event); 19853 } 19854 19855 /** 19856 * Interface definition for a callback to be invoked when a generic motion event is 19857 * dispatched to this view. The callback will be invoked before the generic motion 19858 * event is given to the view. 19859 */ 19860 public interface OnGenericMotionListener { 19861 /** 19862 * Called when a generic motion event is dispatched to a view. This allows listeners to 19863 * get a chance to respond before the target view. 19864 * 19865 * @param v The view the generic motion event has been dispatched to. 19866 * @param event The MotionEvent object containing full information about 19867 * the event. 19868 * @return True if the listener has consumed the event, false otherwise. 19869 */ 19870 boolean onGenericMotion(View v, MotionEvent event); 19871 } 19872 19873 /** 19874 * Interface definition for a callback to be invoked when a view has been clicked and held. 19875 */ 19876 public interface OnLongClickListener { 19877 /** 19878 * Called when a view has been clicked and held. 19879 * 19880 * @param v The view that was clicked and held. 19881 * 19882 * @return true if the callback consumed the long click, false otherwise. 19883 */ 19884 boolean onLongClick(View v); 19885 } 19886 19887 /** 19888 * Interface definition for a callback to be invoked when a drag is being dispatched 19889 * to this view. The callback will be invoked before the hosting view's own 19890 * onDrag(event) method. If the listener wants to fall back to the hosting view's 19891 * onDrag(event) behavior, it should return 'false' from this callback. 19892 * 19893 * <div class="special reference"> 19894 * <h3>Developer Guides</h3> 19895 * <p>For a guide to implementing drag and drop features, read the 19896 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p> 19897 * </div> 19898 */ 19899 public interface OnDragListener { 19900 /** 19901 * Called when a drag event is dispatched to a view. This allows listeners 19902 * to get a chance to override base View behavior. 19903 * 19904 * @param v The View that received the drag event. 19905 * @param event The {@link android.view.DragEvent} object for the drag event. 19906 * @return {@code true} if the drag event was handled successfully, or {@code false} 19907 * if the drag event was not handled. Note that {@code false} will trigger the View 19908 * to call its {@link #onDragEvent(DragEvent) onDragEvent()} handler. 19909 */ 19910 boolean onDrag(View v, DragEvent event); 19911 } 19912 19913 /** 19914 * Interface definition for a callback to be invoked when the focus state of 19915 * a view changed. 19916 */ 19917 public interface OnFocusChangeListener { 19918 /** 19919 * Called when the focus state of a view has changed. 19920 * 19921 * @param v The view whose state has changed. 19922 * @param hasFocus The new focus state of v. 19923 */ 19924 void onFocusChange(View v, boolean hasFocus); 19925 } 19926 19927 /** 19928 * Interface definition for a callback to be invoked when a view is clicked. 19929 */ 19930 public interface OnClickListener { 19931 /** 19932 * Called when a view has been clicked. 19933 * 19934 * @param v The view that was clicked. 19935 */ 19936 void onClick(View v); 19937 } 19938 19939 /** 19940 * Interface definition for a callback to be invoked when the context menu 19941 * for this view is being built. 19942 */ 19943 public interface OnCreateContextMenuListener { 19944 /** 19945 * Called when the context menu for this view is being built. It is not 19946 * safe to hold onto the menu after this method returns. 19947 * 19948 * @param menu The context menu that is being built 19949 * @param v The view for which the context menu is being built 19950 * @param menuInfo Extra information about the item for which the 19951 * context menu should be shown. This information will vary 19952 * depending on the class of v. 19953 */ 19954 void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo); 19955 } 19956 19957 /** 19958 * Interface definition for a callback to be invoked when the status bar changes 19959 * visibility. This reports <strong>global</strong> changes to the system UI 19960 * state, not what the application is requesting. 19961 * 19962 * @see View#setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener) 19963 */ 19964 public interface OnSystemUiVisibilityChangeListener { 19965 /** 19966 * Called when the status bar changes visibility because of a call to 19967 * {@link View#setSystemUiVisibility(int)}. 19968 * 19969 * @param visibility Bitwise-or of flags {@link #SYSTEM_UI_FLAG_LOW_PROFILE}, 19970 * {@link #SYSTEM_UI_FLAG_HIDE_NAVIGATION}, and {@link #SYSTEM_UI_FLAG_FULLSCREEN}. 19971 * This tells you the <strong>global</strong> state of these UI visibility 19972 * flags, not what your app is currently applying. 19973 */ 19974 public void onSystemUiVisibilityChange(int visibility); 19975 } 19976 19977 /** 19978 * Interface definition for a callback to be invoked when this view is attached 19979 * or detached from its window. 19980 */ 19981 public interface OnAttachStateChangeListener { 19982 /** 19983 * Called when the view is attached to a window. 19984 * @param v The view that was attached 19985 */ 19986 public void onViewAttachedToWindow(View v); 19987 /** 19988 * Called when the view is detached from a window. 19989 * @param v The view that was detached 19990 */ 19991 public void onViewDetachedFromWindow(View v); 19992 } 19993 19994 /** 19995 * Listener for applying window insets on a view in a custom way. 19996 * 19997 * <p>Apps may choose to implement this interface if they want to apply custom policy 19998 * to the way that window insets are treated for a view. If an OnApplyWindowInsetsListener 19999 * is set, its 20000 * {@link OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) onApplyWindowInsets} 20001 * method will be called instead of the View's own 20002 * {@link #onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. The listener 20003 * may optionally call the parameter View's <code>onApplyWindowInsets</code> method to apply 20004 * the View's normal behavior as part of its own.</p> 20005 */ 20006 public interface OnApplyWindowInsetsListener { 20007 /** 20008 * When {@link View#setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener) set} 20009 * on a View, this listener method will be called instead of the view's own 20010 * {@link View#onApplyWindowInsets(WindowInsets) onApplyWindowInsets} method. 20011 * 20012 * @param v The view applying window insets 20013 * @param insets The insets to apply 20014 * @return The insets supplied, minus any insets that were consumed 20015 */ 20016 public WindowInsets onApplyWindowInsets(View v, WindowInsets insets); 20017 } 20018 20019 private final class UnsetPressedState implements Runnable { 20020 @Override 20021 public void run() { 20022 setPressed(false); 20023 } 20024 } 20025 20026 /** 20027 * Base class for derived classes that want to save and restore their own 20028 * state in {@link android.view.View#onSaveInstanceState()}. 20029 */ 20030 public static class BaseSavedState extends AbsSavedState { 20031 /** 20032 * Constructor used when reading from a parcel. Reads the state of the superclass. 20033 * 20034 * @param source 20035 */ 20036 public BaseSavedState(Parcel source) { 20037 super(source); 20038 } 20039 20040 /** 20041 * Constructor called by derived classes when creating their SavedState objects 20042 * 20043 * @param superState The state of the superclass of this view 20044 */ 20045 public BaseSavedState(Parcelable superState) { 20046 super(superState); 20047 } 20048 20049 public static final Parcelable.Creator<BaseSavedState> CREATOR = 20050 new Parcelable.Creator<BaseSavedState>() { 20051 public BaseSavedState createFromParcel(Parcel in) { 20052 return new BaseSavedState(in); 20053 } 20054 20055 public BaseSavedState[] newArray(int size) { 20056 return new BaseSavedState[size]; 20057 } 20058 }; 20059 } 20060 20061 /** 20062 * A set of information given to a view when it is attached to its parent 20063 * window. 20064 */ 20065 final static class AttachInfo { 20066 interface Callbacks { 20067 void playSoundEffect(int effectId); 20068 boolean performHapticFeedback(int effectId, boolean always); 20069 } 20070 20071 /** 20072 * InvalidateInfo is used to post invalidate(int, int, int, int) messages 20073 * to a Handler. This class contains the target (View) to invalidate and 20074 * the coordinates of the dirty rectangle. 20075 * 20076 * For performance purposes, this class also implements a pool of up to 20077 * POOL_LIMIT objects that get reused. This reduces memory allocations 20078 * whenever possible. 20079 */ 20080 static class InvalidateInfo { 20081 private static final int POOL_LIMIT = 10; 20082 20083 private static final SynchronizedPool<InvalidateInfo> sPool = 20084 new SynchronizedPool<InvalidateInfo>(POOL_LIMIT); 20085 20086 View target; 20087 20088 int left; 20089 int top; 20090 int right; 20091 int bottom; 20092 20093 public static InvalidateInfo obtain() { 20094 InvalidateInfo instance = sPool.acquire(); 20095 return (instance != null) ? instance : new InvalidateInfo(); 20096 } 20097 20098 public void recycle() { 20099 target = null; 20100 sPool.release(this); 20101 } 20102 } 20103 20104 final IWindowSession mSession; 20105 20106 final IWindow mWindow; 20107 20108 final IBinder mWindowToken; 20109 20110 final Display mDisplay; 20111 20112 final Callbacks mRootCallbacks; 20113 20114 IWindowId mIWindowId; 20115 WindowId mWindowId; 20116 20117 /** 20118 * The top view of the hierarchy. 20119 */ 20120 View mRootView; 20121 20122 IBinder mPanelParentWindowToken; 20123 20124 boolean mHardwareAccelerated; 20125 boolean mHardwareAccelerationRequested; 20126 HardwareRenderer mHardwareRenderer; 20127 List<RenderNode> mPendingAnimatingRenderNodes; 20128 20129 /** 20130 * The state of the display to which the window is attached, as reported 20131 * by {@link Display#getState()}. Note that the display state constants 20132 * declared by {@link Display} do not exactly line up with the screen state 20133 * constants declared by {@link View} (there are more display states than 20134 * screen states). 20135 */ 20136 int mDisplayState = Display.STATE_UNKNOWN; 20137 20138 /** 20139 * Scale factor used by the compatibility mode 20140 */ 20141 float mApplicationScale; 20142 20143 /** 20144 * Indicates whether the application is in compatibility mode 20145 */ 20146 boolean mScalingRequired; 20147 20148 /** 20149 * If set, ViewRootImpl doesn't use its lame animation for when the window resizes. 20150 */ 20151 boolean mTurnOffWindowResizeAnim; 20152 20153 /** 20154 * Left position of this view's window 20155 */ 20156 int mWindowLeft; 20157 20158 /** 20159 * Top position of this view's window 20160 */ 20161 int mWindowTop; 20162 20163 /** 20164 * Indicates whether views need to use 32-bit drawing caches 20165 */ 20166 boolean mUse32BitDrawingCache; 20167 20168 /** 20169 * For windows that are full-screen but using insets to layout inside 20170 * of the screen areas, these are the current insets to appear inside 20171 * the overscan area of the display. 20172 */ 20173 final Rect mOverscanInsets = new Rect(); 20174 20175 /** 20176 * For windows that are full-screen but using insets to layout inside 20177 * of the screen decorations, these are the current insets for the 20178 * content of the window. 20179 */ 20180 final Rect mContentInsets = new Rect(); 20181 20182 /** 20183 * For windows that are full-screen but using insets to layout inside 20184 * of the screen decorations, these are the current insets for the 20185 * actual visible parts of the window. 20186 */ 20187 final Rect mVisibleInsets = new Rect(); 20188 20189 /** 20190 * For windows that are full-screen but using insets to layout inside 20191 * of the screen decorations, these are the current insets for the 20192 * stable system windows. 20193 */ 20194 final Rect mStableInsets = new Rect(); 20195 20196 /** 20197 * The internal insets given by this window. This value is 20198 * supplied by the client (through 20199 * {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will 20200 * be given to the window manager when changed to be used in laying 20201 * out windows behind it. 20202 */ 20203 final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets 20204 = new ViewTreeObserver.InternalInsetsInfo(); 20205 20206 /** 20207 * Set to true when mGivenInternalInsets is non-empty. 20208 */ 20209 boolean mHasNonEmptyGivenInternalInsets; 20210 20211 /** 20212 * All views in the window's hierarchy that serve as scroll containers, 20213 * used to determine if the window can be resized or must be panned 20214 * to adjust for a soft input area. 20215 */ 20216 final ArrayList<View> mScrollContainers = new ArrayList<View>(); 20217 20218 final KeyEvent.DispatcherState mKeyDispatchState 20219 = new KeyEvent.DispatcherState(); 20220 20221 /** 20222 * Indicates whether the view's window currently has the focus. 20223 */ 20224 boolean mHasWindowFocus; 20225 20226 /** 20227 * The current visibility of the window. 20228 */ 20229 int mWindowVisibility; 20230 20231 /** 20232 * Indicates the time at which drawing started to occur. 20233 */ 20234 long mDrawingTime; 20235 20236 /** 20237 * Indicates whether or not ignoring the DIRTY_MASK flags. 20238 */ 20239 boolean mIgnoreDirtyState; 20240 20241 /** 20242 * This flag tracks when the mIgnoreDirtyState flag is set during draw(), 20243 * to avoid clearing that flag prematurely. 20244 */ 20245 boolean mSetIgnoreDirtyState = false; 20246 20247 /** 20248 * Indicates whether the view's window is currently in touch mode. 20249 */ 20250 boolean mInTouchMode; 20251 20252 /** 20253 * Indicates whether the view has requested unbuffered input dispatching for the current 20254 * event stream. 20255 */ 20256 boolean mUnbufferedDispatchRequested; 20257 20258 /** 20259 * Indicates that ViewAncestor should trigger a global layout change 20260 * the next time it performs a traversal 20261 */ 20262 boolean mRecomputeGlobalAttributes; 20263 20264 /** 20265 * Always report new attributes at next traversal. 20266 */ 20267 boolean mForceReportNewAttributes; 20268 20269 /** 20270 * Set during a traveral if any views want to keep the screen on. 20271 */ 20272 boolean mKeepScreenOn; 20273 20274 /** 20275 * Bitwise-or of all of the values that views have passed to setSystemUiVisibility(). 20276 */ 20277 int mSystemUiVisibility; 20278 20279 /** 20280 * Hack to force certain system UI visibility flags to be cleared. 20281 */ 20282 int mDisabledSystemUiVisibility; 20283 20284 /** 20285 * Last global system UI visibility reported by the window manager. 20286 */ 20287 int mGlobalSystemUiVisibility; 20288 20289 /** 20290 * True if a view in this hierarchy has an OnSystemUiVisibilityChangeListener 20291 * attached. 20292 */ 20293 boolean mHasSystemUiListeners; 20294 20295 /** 20296 * Set if the window has requested to extend into the overscan region 20297 * via WindowManager.LayoutParams.FLAG_LAYOUT_IN_OVERSCAN. 20298 */ 20299 boolean mOverscanRequested; 20300 20301 /** 20302 * Set if the visibility of any views has changed. 20303 */ 20304 boolean mViewVisibilityChanged; 20305 20306 /** 20307 * Set to true if a view has been scrolled. 20308 */ 20309 boolean mViewScrollChanged; 20310 20311 /** 20312 * Set to true if high contrast mode enabled 20313 */ 20314 boolean mHighContrastText; 20315 20316 /** 20317 * Global to the view hierarchy used as a temporary for dealing with 20318 * x/y points in the transparent region computations. 20319 */ 20320 final int[] mTransparentLocation = new int[2]; 20321 20322 /** 20323 * Global to the view hierarchy used as a temporary for dealing with 20324 * x/y points in the ViewGroup.invalidateChild implementation. 20325 */ 20326 final int[] mInvalidateChildLocation = new int[2]; 20327 20328 /** 20329 * Global to the view hierarchy used as a temporary for dealng with 20330 * computing absolute on-screen location. 20331 */ 20332 final int[] mTmpLocation = new int[2]; 20333 20334 /** 20335 * Global to the view hierarchy used as a temporary for dealing with 20336 * x/y location when view is transformed. 20337 */ 20338 final float[] mTmpTransformLocation = new float[2]; 20339 20340 /** 20341 * The view tree observer used to dispatch global events like 20342 * layout, pre-draw, touch mode change, etc. 20343 */ 20344 final ViewTreeObserver mTreeObserver = new ViewTreeObserver(); 20345 20346 /** 20347 * A Canvas used by the view hierarchy to perform bitmap caching. 20348 */ 20349 Canvas mCanvas; 20350 20351 /** 20352 * The view root impl. 20353 */ 20354 final ViewRootImpl mViewRootImpl; 20355 20356 /** 20357 * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This 20358 * handler can be used to pump events in the UI events queue. 20359 */ 20360 final Handler mHandler; 20361 20362 /** 20363 * Temporary for use in computing invalidate rectangles while 20364 * calling up the hierarchy. 20365 */ 20366 final Rect mTmpInvalRect = new Rect(); 20367 20368 /** 20369 * Temporary for use in computing hit areas with transformed views 20370 */ 20371 final RectF mTmpTransformRect = new RectF(); 20372 20373 /** 20374 * Temporary for use in computing hit areas with transformed views 20375 */ 20376 final RectF mTmpTransformRect1 = new RectF(); 20377 20378 /** 20379 * Temporary list of rectanges. 20380 */ 20381 final List<RectF> mTmpRectList = new ArrayList<>(); 20382 20383 /** 20384 * Temporary for use in transforming invalidation rect 20385 */ 20386 final Matrix mTmpMatrix = new Matrix(); 20387 20388 /** 20389 * Temporary for use in transforming invalidation rect 20390 */ 20391 final Transformation mTmpTransformation = new Transformation(); 20392 20393 /** 20394 * Temporary for use in querying outlines from OutlineProviders 20395 */ 20396 final Outline mTmpOutline = new Outline(); 20397 20398 /** 20399 * Temporary list for use in collecting focusable descendents of a view. 20400 */ 20401 final ArrayList<View> mTempArrayList = new ArrayList<View>(24); 20402 20403 /** 20404 * The id of the window for accessibility purposes. 20405 */ 20406 int mAccessibilityWindowId = AccessibilityNodeInfo.UNDEFINED_ITEM_ID; 20407 20408 /** 20409 * Flags related to accessibility processing. 20410 * 20411 * @see AccessibilityNodeInfo#FLAG_INCLUDE_NOT_IMPORTANT_VIEWS 20412 * @see AccessibilityNodeInfo#FLAG_REPORT_VIEW_IDS 20413 */ 20414 int mAccessibilityFetchFlags; 20415 20416 /** 20417 * The drawable for highlighting accessibility focus. 20418 */ 20419 Drawable mAccessibilityFocusDrawable; 20420 20421 /** 20422 * Show where the margins, bounds and layout bounds are for each view. 20423 */ 20424 boolean mDebugLayout = SystemProperties.getBoolean(DEBUG_LAYOUT_PROPERTY, false); 20425 20426 /** 20427 * Point used to compute visible regions. 20428 */ 20429 final Point mPoint = new Point(); 20430 20431 /** 20432 * Used to track which View originated a requestLayout() call, used when 20433 * requestLayout() is called during layout. 20434 */ 20435 View mViewRequestingLayout; 20436 20437 /** 20438 * Creates a new set of attachment information with the specified 20439 * events handler and thread. 20440 * 20441 * @param handler the events handler the view must use 20442 */ 20443 AttachInfo(IWindowSession session, IWindow window, Display display, 20444 ViewRootImpl viewRootImpl, Handler handler, Callbacks effectPlayer) { 20445 mSession = session; 20446 mWindow = window; 20447 mWindowToken = window.asBinder(); 20448 mDisplay = display; 20449 mViewRootImpl = viewRootImpl; 20450 mHandler = handler; 20451 mRootCallbacks = effectPlayer; 20452 } 20453 } 20454 20455 /** 20456 * <p>ScrollabilityCache holds various fields used by a View when scrolling 20457 * is supported. This avoids keeping too many unused fields in most 20458 * instances of View.</p> 20459 */ 20460 private static class ScrollabilityCache implements Runnable { 20461 20462 /** 20463 * Scrollbars are not visible 20464 */ 20465 public static final int OFF = 0; 20466 20467 /** 20468 * Scrollbars are visible 20469 */ 20470 public static final int ON = 1; 20471 20472 /** 20473 * Scrollbars are fading away 20474 */ 20475 public static final int FADING = 2; 20476 20477 public boolean fadeScrollBars; 20478 20479 public int fadingEdgeLength; 20480 public int scrollBarDefaultDelayBeforeFade; 20481 public int scrollBarFadeDuration; 20482 20483 public int scrollBarSize; 20484 public ScrollBarDrawable scrollBar; 20485 public float[] interpolatorValues; 20486 public View host; 20487 20488 public final Paint paint; 20489 public final Matrix matrix; 20490 public Shader shader; 20491 20492 public final Interpolator scrollBarInterpolator = new Interpolator(1, 2); 20493 20494 private static final float[] OPAQUE = { 255 }; 20495 private static final float[] TRANSPARENT = { 0.0f }; 20496 20497 /** 20498 * When fading should start. This time moves into the future every time 20499 * a new scroll happens. Measured based on SystemClock.uptimeMillis() 20500 */ 20501 public long fadeStartTime; 20502 20503 20504 /** 20505 * The current state of the scrollbars: ON, OFF, or FADING 20506 */ 20507 public int state = OFF; 20508 20509 private int mLastColor; 20510 20511 public ScrollabilityCache(ViewConfiguration configuration, View host) { 20512 fadingEdgeLength = configuration.getScaledFadingEdgeLength(); 20513 scrollBarSize = configuration.getScaledScrollBarSize(); 20514 scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); 20515 scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); 20516 20517 paint = new Paint(); 20518 matrix = new Matrix(); 20519 // use use a height of 1, and then wack the matrix each time we 20520 // actually use it. 20521 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20522 paint.setShader(shader); 20523 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20524 20525 this.host = host; 20526 } 20527 20528 public void setFadeColor(int color) { 20529 if (color != mLastColor) { 20530 mLastColor = color; 20531 20532 if (color != 0) { 20533 shader = new LinearGradient(0, 0, 0, 1, color | 0xFF000000, 20534 color & 0x00FFFFFF, Shader.TileMode.CLAMP); 20535 paint.setShader(shader); 20536 // Restore the default transfer mode (src_over) 20537 paint.setXfermode(null); 20538 } else { 20539 shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP); 20540 paint.setShader(shader); 20541 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 20542 } 20543 } 20544 } 20545 20546 public void run() { 20547 long now = AnimationUtils.currentAnimationTimeMillis(); 20548 if (now >= fadeStartTime) { 20549 20550 // the animation fades the scrollbars out by changing 20551 // the opacity (alpha) from fully opaque to fully 20552 // transparent 20553 int nextFrame = (int) now; 20554 int framesCount = 0; 20555 20556 Interpolator interpolator = scrollBarInterpolator; 20557 20558 // Start opaque 20559 interpolator.setKeyFrame(framesCount++, nextFrame, OPAQUE); 20560 20561 // End transparent 20562 nextFrame += scrollBarFadeDuration; 20563 interpolator.setKeyFrame(framesCount, nextFrame, TRANSPARENT); 20564 20565 state = FADING; 20566 20567 // Kick off the fade animation 20568 host.invalidate(true); 20569 } 20570 } 20571 } 20572 20573 /** 20574 * Resuable callback for sending 20575 * {@link AccessibilityEvent#TYPE_VIEW_SCROLLED} accessibility event. 20576 */ 20577 private class SendViewScrolledAccessibilityEvent implements Runnable { 20578 public volatile boolean mIsPending; 20579 20580 public void run() { 20581 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SCROLLED); 20582 mIsPending = false; 20583 } 20584 } 20585 20586 /** 20587 * <p> 20588 * This class represents a delegate that can be registered in a {@link View} 20589 * to enhance accessibility support via composition rather via inheritance. 20590 * It is specifically targeted to widget developers that extend basic View 20591 * classes i.e. classes in package android.view, that would like their 20592 * applications to be backwards compatible. 20593 * </p> 20594 * <div class="special reference"> 20595 * <h3>Developer Guides</h3> 20596 * <p>For more information about making applications accessible, read the 20597 * <a href="{@docRoot}guide/topics/ui/accessibility/index.html">Accessibility</a> 20598 * developer guide.</p> 20599 * </div> 20600 * <p> 20601 * A scenario in which a developer would like to use an accessibility delegate 20602 * is overriding a method introduced in a later API version then the minimal API 20603 * version supported by the application. For example, the method 20604 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} is not available 20605 * in API version 4 when the accessibility APIs were first introduced. If a 20606 * developer would like his application to run on API version 4 devices (assuming 20607 * all other APIs used by the application are version 4 or lower) and take advantage 20608 * of this method, instead of overriding the method which would break the application's 20609 * backwards compatibility, he can override the corresponding method in this 20610 * delegate and register the delegate in the target View if the API version of 20611 * the system is high enough i.e. the API version is same or higher to the API 20612 * version that introduced 20613 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)}. 20614 * </p> 20615 * <p> 20616 * Here is an example implementation: 20617 * </p> 20618 * <code><pre><p> 20619 * if (Build.VERSION.SDK_INT >= 14) { 20620 * // If the API version is equal of higher than the version in 20621 * // which onInitializeAccessibilityNodeInfo was introduced we 20622 * // register a delegate with a customized implementation. 20623 * View view = findViewById(R.id.view_id); 20624 * view.setAccessibilityDelegate(new AccessibilityDelegate() { 20625 * public void onInitializeAccessibilityNodeInfo(View host, 20626 * AccessibilityNodeInfo info) { 20627 * // Let the default implementation populate the info. 20628 * super.onInitializeAccessibilityNodeInfo(host, info); 20629 * // Set some other information. 20630 * info.setEnabled(host.isEnabled()); 20631 * } 20632 * }); 20633 * } 20634 * </code></pre></p> 20635 * <p> 20636 * This delegate contains methods that correspond to the accessibility methods 20637 * in View. If a delegate has been specified the implementation in View hands 20638 * off handling to the corresponding method in this delegate. The default 20639 * implementation the delegate methods behaves exactly as the corresponding 20640 * method in View for the case of no accessibility delegate been set. Hence, 20641 * to customize the behavior of a View method, clients can override only the 20642 * corresponding delegate method without altering the behavior of the rest 20643 * accessibility related methods of the host view. 20644 * </p> 20645 */ 20646 public static class AccessibilityDelegate { 20647 20648 /** 20649 * Sends an accessibility event of the given type. If accessibility is not 20650 * enabled this method has no effect. 20651 * <p> 20652 * The default implementation behaves as {@link View#sendAccessibilityEvent(int) 20653 * View#sendAccessibilityEvent(int)} for the case of no accessibility delegate 20654 * been set. 20655 * </p> 20656 * 20657 * @param host The View hosting the delegate. 20658 * @param eventType The type of the event to send. 20659 * 20660 * @see View#sendAccessibilityEvent(int) View#sendAccessibilityEvent(int) 20661 */ 20662 public void sendAccessibilityEvent(View host, int eventType) { 20663 host.sendAccessibilityEventInternal(eventType); 20664 } 20665 20666 /** 20667 * Performs the specified accessibility action on the view. For 20668 * possible accessibility actions look at {@link AccessibilityNodeInfo}. 20669 * <p> 20670 * The default implementation behaves as 20671 * {@link View#performAccessibilityAction(int, Bundle) 20672 * View#performAccessibilityAction(int, Bundle)} for the case of 20673 * no accessibility delegate been set. 20674 * </p> 20675 * 20676 * @param action The action to perform. 20677 * @return Whether the action was performed. 20678 * 20679 * @see View#performAccessibilityAction(int, Bundle) 20680 * View#performAccessibilityAction(int, Bundle) 20681 */ 20682 public boolean performAccessibilityAction(View host, int action, Bundle args) { 20683 return host.performAccessibilityActionInternal(action, args); 20684 } 20685 20686 /** 20687 * Sends an accessibility event. This method behaves exactly as 20688 * {@link #sendAccessibilityEvent(View, int)} but takes as an argument an 20689 * empty {@link AccessibilityEvent} and does not perform a check whether 20690 * accessibility is enabled. 20691 * <p> 20692 * The default implementation behaves as 20693 * {@link View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20694 * View#sendAccessibilityEventUnchecked(AccessibilityEvent)} for 20695 * the case of no accessibility delegate been set. 20696 * </p> 20697 * 20698 * @param host The View hosting the delegate. 20699 * @param event The event to send. 20700 * 20701 * @see View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20702 * View#sendAccessibilityEventUnchecked(AccessibilityEvent) 20703 */ 20704 public void sendAccessibilityEventUnchecked(View host, AccessibilityEvent event) { 20705 host.sendAccessibilityEventUncheckedInternal(event); 20706 } 20707 20708 /** 20709 * Dispatches an {@link AccessibilityEvent} to the host {@link View} first and then 20710 * to its children for adding their text content to the event. 20711 * <p> 20712 * The default implementation behaves as 20713 * {@link View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20714 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent)} for 20715 * the case of no accessibility delegate been set. 20716 * </p> 20717 * 20718 * @param host The View hosting the delegate. 20719 * @param event The event. 20720 * @return True if the event population was completed. 20721 * 20722 * @see View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20723 * View#dispatchPopulateAccessibilityEvent(AccessibilityEvent) 20724 */ 20725 public boolean dispatchPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20726 return host.dispatchPopulateAccessibilityEventInternal(event); 20727 } 20728 20729 /** 20730 * Gives a chance to the host View to populate the accessibility event with its 20731 * text content. 20732 * <p> 20733 * The default implementation behaves as 20734 * {@link View#onPopulateAccessibilityEvent(AccessibilityEvent) 20735 * View#onPopulateAccessibilityEvent(AccessibilityEvent)} for 20736 * the case of no accessibility delegate been set. 20737 * </p> 20738 * 20739 * @param host The View hosting the delegate. 20740 * @param event The accessibility event which to populate. 20741 * 20742 * @see View#onPopulateAccessibilityEvent(AccessibilityEvent) 20743 * View#onPopulateAccessibilityEvent(AccessibilityEvent) 20744 */ 20745 public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { 20746 host.onPopulateAccessibilityEventInternal(event); 20747 } 20748 20749 /** 20750 * Initializes an {@link AccessibilityEvent} with information about the 20751 * the host View which is the event source. 20752 * <p> 20753 * The default implementation behaves as 20754 * {@link View#onInitializeAccessibilityEvent(AccessibilityEvent) 20755 * View#onInitializeAccessibilityEvent(AccessibilityEvent)} for 20756 * the case of no accessibility delegate been set. 20757 * </p> 20758 * 20759 * @param host The View hosting the delegate. 20760 * @param event The event to initialize. 20761 * 20762 * @see View#onInitializeAccessibilityEvent(AccessibilityEvent) 20763 * View#onInitializeAccessibilityEvent(AccessibilityEvent) 20764 */ 20765 public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { 20766 host.onInitializeAccessibilityEventInternal(event); 20767 } 20768 20769 /** 20770 * Initializes an {@link AccessibilityNodeInfo} with information about the host view. 20771 * <p> 20772 * The default implementation behaves as 20773 * {@link View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20774 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} for 20775 * the case of no accessibility delegate been set. 20776 * </p> 20777 * 20778 * @param host The View hosting the delegate. 20779 * @param info The instance to initialize. 20780 * 20781 * @see View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20782 * View#onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo) 20783 */ 20784 public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { 20785 host.onInitializeAccessibilityNodeInfoInternal(info); 20786 } 20787 20788 /** 20789 * Called when a child of the host View has requested sending an 20790 * {@link AccessibilityEvent} and gives an opportunity to the parent (the host) 20791 * to augment the event. 20792 * <p> 20793 * The default implementation behaves as 20794 * {@link ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20795 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent)} for 20796 * the case of no accessibility delegate been set. 20797 * </p> 20798 * 20799 * @param host The View hosting the delegate. 20800 * @param child The child which requests sending the event. 20801 * @param event The event to be sent. 20802 * @return True if the event should be sent 20803 * 20804 * @see ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20805 * ViewGroup#onRequestSendAccessibilityEvent(View, AccessibilityEvent) 20806 */ 20807 public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, 20808 AccessibilityEvent event) { 20809 return host.onRequestSendAccessibilityEventInternal(child, event); 20810 } 20811 20812 /** 20813 * Gets the provider for managing a virtual view hierarchy rooted at this View 20814 * and reported to {@link android.accessibilityservice.AccessibilityService}s 20815 * that explore the window content. 20816 * <p> 20817 * The default implementation behaves as 20818 * {@link View#getAccessibilityNodeProvider() View#getAccessibilityNodeProvider()} for 20819 * the case of no accessibility delegate been set. 20820 * </p> 20821 * 20822 * @return The provider. 20823 * 20824 * @see AccessibilityNodeProvider 20825 */ 20826 public AccessibilityNodeProvider getAccessibilityNodeProvider(View host) { 20827 return null; 20828 } 20829 20830 /** 20831 * Returns an {@link AccessibilityNodeInfo} representing the host view from the 20832 * point of view of an {@link android.accessibilityservice.AccessibilityService}. 20833 * This method is responsible for obtaining an accessibility node info from a 20834 * pool of reusable instances and calling 20835 * {@link #onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo)} on the host 20836 * view to initialize the former. 20837 * <p> 20838 * <strong>Note:</strong> The client is responsible for recycling the obtained 20839 * instance by calling {@link AccessibilityNodeInfo#recycle()} to minimize object 20840 * creation. 20841 * </p> 20842 * <p> 20843 * The default implementation behaves as 20844 * {@link View#createAccessibilityNodeInfo() View#createAccessibilityNodeInfo()} for 20845 * the case of no accessibility delegate been set. 20846 * </p> 20847 * @return A populated {@link AccessibilityNodeInfo}. 20848 * 20849 * @see AccessibilityNodeInfo 20850 * 20851 * @hide 20852 */ 20853 public AccessibilityNodeInfo createAccessibilityNodeInfo(View host) { 20854 return host.createAccessibilityNodeInfoInternal(); 20855 } 20856 } 20857 20858 private class MatchIdPredicate implements Predicate<View> { 20859 public int mId; 20860 20861 @Override 20862 public boolean apply(View view) { 20863 return (view.mID == mId); 20864 } 20865 } 20866 20867 private class MatchLabelForPredicate implements Predicate<View> { 20868 private int mLabeledId; 20869 20870 @Override 20871 public boolean apply(View view) { 20872 return (view.mLabelForId == mLabeledId); 20873 } 20874 } 20875 20876 private class SendViewStateChangedAccessibilityEvent implements Runnable { 20877 private int mChangeTypes = 0; 20878 private boolean mPosted; 20879 private boolean mPostedWithDelay; 20880 private long mLastEventTimeMillis; 20881 20882 @Override 20883 public void run() { 20884 mPosted = false; 20885 mPostedWithDelay = false; 20886 mLastEventTimeMillis = SystemClock.uptimeMillis(); 20887 if (AccessibilityManager.getInstance(mContext).isEnabled()) { 20888 final AccessibilityEvent event = AccessibilityEvent.obtain(); 20889 event.setEventType(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED); 20890 event.setContentChangeTypes(mChangeTypes); 20891 sendAccessibilityEventUnchecked(event); 20892 } 20893 mChangeTypes = 0; 20894 } 20895 20896 public void runOrPost(int changeType) { 20897 mChangeTypes |= changeType; 20898 20899 // If this is a live region or the child of a live region, collect 20900 // all events from this frame and send them on the next frame. 20901 if (inLiveRegion()) { 20902 // If we're already posted with a delay, remove that. 20903 if (mPostedWithDelay) { 20904 removeCallbacks(this); 20905 mPostedWithDelay = false; 20906 } 20907 // Only post if we're not already posted. 20908 if (!mPosted) { 20909 post(this); 20910 mPosted = true; 20911 } 20912 return; 20913 } 20914 20915 if (mPosted) { 20916 return; 20917 } 20918 20919 final long timeSinceLastMillis = SystemClock.uptimeMillis() - mLastEventTimeMillis; 20920 final long minEventIntevalMillis = 20921 ViewConfiguration.getSendRecurringAccessibilityEventsInterval(); 20922 if (timeSinceLastMillis >= minEventIntevalMillis) { 20923 removeCallbacks(this); 20924 run(); 20925 } else { 20926 postDelayed(this, minEventIntevalMillis - timeSinceLastMillis); 20927 mPostedWithDelay = true; 20928 } 20929 } 20930 } 20931 20932 private boolean inLiveRegion() { 20933 if (getAccessibilityLiveRegion() != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20934 return true; 20935 } 20936 20937 ViewParent parent = getParent(); 20938 while (parent instanceof View) { 20939 if (((View) parent).getAccessibilityLiveRegion() 20940 != View.ACCESSIBILITY_LIVE_REGION_NONE) { 20941 return true; 20942 } 20943 parent = parent.getParent(); 20944 } 20945 20946 return false; 20947 } 20948 20949 /** 20950 * Dump all private flags in readable format, useful for documentation and 20951 * sanity checking. 20952 */ 20953 private static void dumpFlags() { 20954 final HashMap<String, String> found = Maps.newHashMap(); 20955 try { 20956 for (Field field : View.class.getDeclaredFields()) { 20957 final int modifiers = field.getModifiers(); 20958 if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) { 20959 if (field.getType().equals(int.class)) { 20960 final int value = field.getInt(null); 20961 dumpFlag(found, field.getName(), value); 20962 } else if (field.getType().equals(int[].class)) { 20963 final int[] values = (int[]) field.get(null); 20964 for (int i = 0; i < values.length; i++) { 20965 dumpFlag(found, field.getName() + "[" + i + "]", values[i]); 20966 } 20967 } 20968 } 20969 } 20970 } catch (IllegalAccessException e) { 20971 throw new RuntimeException(e); 20972 } 20973 20974 final ArrayList<String> keys = Lists.newArrayList(); 20975 keys.addAll(found.keySet()); 20976 Collections.sort(keys); 20977 for (String key : keys) { 20978 Log.d(VIEW_LOG_TAG, found.get(key)); 20979 } 20980 } 20981 20982 private static void dumpFlag(HashMap<String, String> found, String name, int value) { 20983 // Sort flags by prefix, then by bits, always keeping unique keys 20984 final String bits = String.format("%32s", Integer.toBinaryString(value)).replace('0', ' '); 20985 final int prefix = name.indexOf('_'); 20986 final String key = (prefix > 0 ? name.substring(0, prefix) : name) + bits + name; 20987 final String output = bits + " " + name; 20988 found.put(key, output); 20989 } 20990} 20991